1efc39a35ecd2eb4eda800d7c745b3362302e74d
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / ARMELFStreamer.cpp
1 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file assembles .s files and emits ARM ELF .o object files. Different
11 // from generic ELF streamer in emitting mapping symbols ($a, $t and $d) to
12 // delimit regions of data and code.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "ARMRegisterInfo.h"
17 #include "ARMUnwindOpAsm.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCCodeEmitter.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCELF.h"
26 #include "llvm/MC/MCELFStreamer.h"
27 #include "llvm/MC/MCELFSymbolFlags.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstPrinter.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCObjectStreamer.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCSectionELF.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCValue.h"
39 #include "llvm/Support/ARMBuildAttributes.h"
40 #include "llvm/Support/ARMEHABI.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ELF.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48
49 using namespace llvm;
50
51 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
52   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
53          "Invalid personality index");
54   return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
55 }
56
57 namespace {
58
59 class ARMELFStreamer;
60
61 class ARMTargetAsmStreamer : public ARMTargetStreamer {
62   formatted_raw_ostream &OS;
63   MCInstPrinter &InstPrinter;
64   bool IsVerboseAsm;
65
66   void emitFnStart() override;
67   void emitFnEnd() override;
68   void emitCantUnwind() override;
69   void emitPersonality(const MCSymbol *Personality) override;
70   void emitPersonalityIndex(unsigned Index) override;
71   void emitHandlerData() override;
72   void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
73   void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
74   void emitPad(int64_t Offset) override;
75   void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
76                    bool isVector) override;
77   void emitUnwindRaw(int64_t Offset,
78                      const SmallVectorImpl<uint8_t> &Opcodes) override;
79
80   void switchVendor(StringRef Vendor) override;
81   void emitAttribute(unsigned Attribute, unsigned Value) override;
82   void emitTextAttribute(unsigned Attribute, StringRef String) override;
83   void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
84                             StringRef StrinValue) override;
85   void emitArch(unsigned Arch) override;
86   void emitArchExtension(unsigned ArchExt) override;
87   void emitObjectArch(unsigned Arch) override;
88   void emitFPU(unsigned FPU) override;
89   void emitInst(uint32_t Inst, char Suffix = '\0') override;
90   void finishAttributeSection() override;
91
92   void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
93   void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
94
95 public:
96   ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
97                        MCInstPrinter &InstPrinter, bool VerboseAsm);
98 };
99
100 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
101                                            formatted_raw_ostream &OS,
102                                            MCInstPrinter &InstPrinter,
103                                            bool VerboseAsm)
104     : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
105       IsVerboseAsm(VerboseAsm) {}
106 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
107 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
108 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
109 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
110   OS << "\t.personality " << Personality->getName() << '\n';
111 }
112 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
113   OS << "\t.personalityindex " << Index << '\n';
114 }
115 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
116 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
117                                      int64_t Offset) {
118   OS << "\t.setfp\t";
119   InstPrinter.printRegName(OS, FpReg);
120   OS << ", ";
121   InstPrinter.printRegName(OS, SpReg);
122   if (Offset)
123     OS << ", #" << Offset;
124   OS << '\n';
125 }
126 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
127   assert((Reg != ARM::SP && Reg != ARM::PC) &&
128          "the operand of .movsp cannot be either sp or pc");
129
130   OS << "\t.movsp\t";
131   InstPrinter.printRegName(OS, Reg);
132   if (Offset)
133     OS << ", #" << Offset;
134   OS << '\n';
135 }
136 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
137   OS << "\t.pad\t#" << Offset << '\n';
138 }
139 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
140                                        bool isVector) {
141   assert(RegList.size() && "RegList should not be empty");
142   if (isVector)
143     OS << "\t.vsave\t{";
144   else
145     OS << "\t.save\t{";
146
147   InstPrinter.printRegName(OS, RegList[0]);
148
149   for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
150     OS << ", ";
151     InstPrinter.printRegName(OS, RegList[i]);
152   }
153
154   OS << "}\n";
155 }
156 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
157 }
158 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
159   OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
160   if (IsVerboseAsm) {
161     StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
162     if (!Name.empty())
163       OS << "\t@ " << Name;
164   }
165   OS << "\n";
166 }
167 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
168                                              StringRef String) {
169   switch (Attribute) {
170   case ARMBuildAttrs::CPU_name:
171     OS << "\t.cpu\t" << String.lower();
172     break;
173   default:
174     OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
175     if (IsVerboseAsm) {
176       StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
177       if (!Name.empty())
178         OS << "\t@ " << Name;
179     }
180     break;
181   }
182   OS << "\n";
183 }
184 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
185                                                 unsigned IntValue,
186                                                 StringRef StringValue) {
187   switch (Attribute) {
188   default: llvm_unreachable("unsupported multi-value attribute in asm mode");
189   case ARMBuildAttrs::compatibility:
190     OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
191     if (!StringValue.empty())
192       OS << ", \"" << StringValue << "\"";
193     if (IsVerboseAsm)
194       OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
195     break;
196   }
197   OS << "\n";
198 }
199 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
200   OS << "\t.arch\t" << ARMTargetParser::getArchName(Arch) << "\n";
201 }
202 void ARMTargetAsmStreamer::emitArchExtension(unsigned ArchExt) {
203   OS << "\t.arch_extension\t" << ARMTargetParser::getArchExtName(ArchExt) << "\n";
204 }
205 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
206   OS << "\t.object_arch\t" << ARMTargetParser::getArchName(Arch) << '\n';
207 }
208 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
209   OS << "\t.fpu\t" << ARMTargetParser::getFPUName(FPU) << "\n";
210 }
211 void ARMTargetAsmStreamer::finishAttributeSection() {
212 }
213 void
214 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
215   OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
216 }
217
218 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
219   OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
220 }
221
222 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
223   OS << "\t.inst";
224   if (Suffix)
225     OS << "." << Suffix;
226   OS << "\t0x" << utohexstr(Inst) << "\n";
227 }
228
229 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
230                                       const SmallVectorImpl<uint8_t> &Opcodes) {
231   OS << "\t.unwind_raw " << Offset;
232   for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
233                                                 OCE = Opcodes.end();
234        OCI != OCE; ++OCI)
235     OS << ", 0x" << utohexstr(*OCI);
236   OS << '\n';
237 }
238
239 class ARMTargetELFStreamer : public ARMTargetStreamer {
240 private:
241   // This structure holds all attributes, accounting for
242   // their string/numeric value, so we can later emmit them
243   // in declaration order, keeping all in the same vector
244   struct AttributeItem {
245     enum {
246       HiddenAttribute = 0,
247       NumericAttribute,
248       TextAttribute,
249       NumericAndTextAttributes
250     } Type;
251     unsigned Tag;
252     unsigned IntValue;
253     StringRef StringValue;
254
255     static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
256       // The conformance tag must be emitted first when serialised
257       // into an object file. Specifically, the addenda to the ARM ABI
258       // states that (2.3.7.4):
259       //
260       // "To simplify recognition by consumers in the common case of
261       // claiming conformity for the whole file, this tag should be
262       // emitted first in a file-scope sub-subsection of the first
263       // public subsection of the attributes section."
264       //
265       // So it is special-cased in this comparison predicate when the
266       // attributes are sorted in finishAttributeSection().
267       return (RHS.Tag != ARMBuildAttrs::conformance) &&
268              ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
269     }
270   };
271
272   StringRef CurrentVendor;
273   unsigned FPU;
274   unsigned Arch;
275   unsigned EmittedArch;
276   SmallVector<AttributeItem, 64> Contents;
277
278   const MCSection *AttributeSection;
279
280   AttributeItem *getAttributeItem(unsigned Attribute) {
281     for (size_t i = 0; i < Contents.size(); ++i)
282       if (Contents[i].Tag == Attribute)
283         return &Contents[i];
284     return nullptr;
285   }
286
287   void setAttributeItem(unsigned Attribute, unsigned Value,
288                         bool OverwriteExisting) {
289     // Look for existing attribute item
290     if (AttributeItem *Item = getAttributeItem(Attribute)) {
291       if (!OverwriteExisting)
292         return;
293       Item->Type = AttributeItem::NumericAttribute;
294       Item->IntValue = Value;
295       return;
296     }
297
298     // Create new attribute item
299     AttributeItem Item = {
300       AttributeItem::NumericAttribute,
301       Attribute,
302       Value,
303       StringRef("")
304     };
305     Contents.push_back(Item);
306   }
307
308   void setAttributeItem(unsigned Attribute, StringRef Value,
309                         bool OverwriteExisting) {
310     // Look for existing attribute item
311     if (AttributeItem *Item = getAttributeItem(Attribute)) {
312       if (!OverwriteExisting)
313         return;
314       Item->Type = AttributeItem::TextAttribute;
315       Item->StringValue = Value;
316       return;
317     }
318
319     // Create new attribute item
320     AttributeItem Item = {
321       AttributeItem::TextAttribute,
322       Attribute,
323       0,
324       Value
325     };
326     Contents.push_back(Item);
327   }
328
329   void setAttributeItems(unsigned Attribute, unsigned IntValue,
330                          StringRef StringValue, bool OverwriteExisting) {
331     // Look for existing attribute item
332     if (AttributeItem *Item = getAttributeItem(Attribute)) {
333       if (!OverwriteExisting)
334         return;
335       Item->Type = AttributeItem::NumericAndTextAttributes;
336       Item->IntValue = IntValue;
337       Item->StringValue = StringValue;
338       return;
339     }
340
341     // Create new attribute item
342     AttributeItem Item = {
343       AttributeItem::NumericAndTextAttributes,
344       Attribute,
345       IntValue,
346       StringValue
347     };
348     Contents.push_back(Item);
349   }
350
351   void emitArchDefaultAttributes();
352   void emitFPUDefaultAttributes();
353
354   ARMELFStreamer &getStreamer();
355
356   void emitFnStart() override;
357   void emitFnEnd() override;
358   void emitCantUnwind() override;
359   void emitPersonality(const MCSymbol *Personality) override;
360   void emitPersonalityIndex(unsigned Index) override;
361   void emitHandlerData() override;
362   void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
363   void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
364   void emitPad(int64_t Offset) override;
365   void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
366                    bool isVector) override;
367   void emitUnwindRaw(int64_t Offset,
368                      const SmallVectorImpl<uint8_t> &Opcodes) override;
369
370   void switchVendor(StringRef Vendor) override;
371   void emitAttribute(unsigned Attribute, unsigned Value) override;
372   void emitTextAttribute(unsigned Attribute, StringRef String) override;
373   void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
374                             StringRef StringValue) override;
375   void emitArch(unsigned Arch) override;
376   void emitObjectArch(unsigned Arch) override;
377   void emitFPU(unsigned FPU) override;
378   void emitInst(uint32_t Inst, char Suffix = '\0') override;
379   void finishAttributeSection() override;
380   void emitLabel(MCSymbol *Symbol) override;
381
382   void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
383   void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
384
385   size_t calculateContentSize() const;
386
387 public:
388   ARMTargetELFStreamer(MCStreamer &S)
389     : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::FK_INVALID),
390       Arch(ARM::AK_INVALID), EmittedArch(ARM::AK_INVALID),
391       AttributeSection(nullptr) {}
392 };
393
394 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
395 /// the appropriate points in the object files. These symbols are defined in the
396 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
397 ///
398 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
399 /// region of ARM code, Thumb code or data in a section. In practice, this
400 /// emission does not rely on explicit assembler directives but on inherent
401 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
402 /// r0, r0, r0" an instruction).
403 ///
404 /// As a result this system is orthogonal to the DataRegion infrastructure used
405 /// by MachO. Beware!
406 class ARMELFStreamer : public MCELFStreamer {
407 public:
408   friend class ARMTargetELFStreamer;
409
410   ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_pwrite_stream &OS,
411                  MCCodeEmitter *Emitter, bool IsThumb)
412       : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
413         MappingSymbolCounter(0), LastEMS(EMS_None) {
414     Reset();
415   }
416
417   ~ARMELFStreamer() {}
418
419   void FinishImpl() override;
420
421   // ARM exception handling directives
422   void emitFnStart();
423   void emitFnEnd();
424   void emitCantUnwind();
425   void emitPersonality(const MCSymbol *Per);
426   void emitPersonalityIndex(unsigned index);
427   void emitHandlerData();
428   void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
429   void emitMovSP(unsigned Reg, int64_t Offset = 0);
430   void emitPad(int64_t Offset);
431   void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
432   void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
433
434   void ChangeSection(const MCSection *Section,
435                      const MCExpr *Subsection) override {
436     // We have to keep track of the mapping symbol state of any sections we
437     // use. Each one should start off as EMS_None, which is provided as the
438     // default constructor by DenseMap::lookup.
439     LastMappingSymbols[getPreviousSection().first] = LastEMS;
440     LastEMS = LastMappingSymbols.lookup(Section);
441
442     MCELFStreamer::ChangeSection(Section, Subsection);
443   }
444
445   /// This function is the one used to emit instruction data into the ELF
446   /// streamer. We override it to add the appropriate mapping symbol if
447   /// necessary.
448   void EmitInstruction(const MCInst& Inst,
449                        const MCSubtargetInfo &STI) override {
450     if (IsThumb)
451       EmitThumbMappingSymbol();
452     else
453       EmitARMMappingSymbol();
454
455     MCELFStreamer::EmitInstruction(Inst, STI);
456   }
457
458   void emitInst(uint32_t Inst, char Suffix) {
459     unsigned Size;
460     char Buffer[4];
461     const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
462
463     switch (Suffix) {
464     case '\0':
465       Size = 4;
466
467       assert(!IsThumb);
468       EmitARMMappingSymbol();
469       for (unsigned II = 0, IE = Size; II != IE; II++) {
470         const unsigned I = LittleEndian ? (Size - II - 1) : II;
471         Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
472       }
473
474       break;
475     case 'n':
476     case 'w':
477       Size = (Suffix == 'n' ? 2 : 4);
478
479       assert(IsThumb);
480       EmitThumbMappingSymbol();
481       for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
482         const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
483         const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
484         Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
485         Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
486       }
487
488       break;
489     default:
490       llvm_unreachable("Invalid Suffix");
491     }
492
493     MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
494   }
495
496   /// This is one of the functions used to emit data into an ELF section, so the
497   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
498   /// necessary.
499   void EmitBytes(StringRef Data) override {
500     EmitDataMappingSymbol();
501     MCELFStreamer::EmitBytes(Data);
502   }
503
504   /// This is one of the functions used to emit data into an ELF section, so the
505   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
506   /// necessary.
507   void EmitValueImpl(const MCExpr *Value, unsigned Size,
508                      const SMLoc &Loc) override {
509     if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value))
510       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4))
511         getContext().FatalError(Loc, "relocated expression must be 32-bit");
512
513     EmitDataMappingSymbol();
514     MCELFStreamer::EmitValueImpl(Value, Size);
515   }
516
517   void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
518     MCELFStreamer::EmitAssemblerFlag(Flag);
519
520     switch (Flag) {
521     case MCAF_SyntaxUnified:
522       return; // no-op here.
523     case MCAF_Code16:
524       IsThumb = true;
525       return; // Change to Thumb mode
526     case MCAF_Code32:
527       IsThumb = false;
528       return; // Change to ARM mode
529     case MCAF_Code64:
530       return;
531     case MCAF_SubsectionsViaSymbols:
532       return;
533     }
534   }
535
536 private:
537   enum ElfMappingSymbol {
538     EMS_None,
539     EMS_ARM,
540     EMS_Thumb,
541     EMS_Data
542   };
543
544   void EmitDataMappingSymbol() {
545     if (LastEMS == EMS_Data) return;
546     EmitMappingSymbol("$d");
547     LastEMS = EMS_Data;
548   }
549
550   void EmitThumbMappingSymbol() {
551     if (LastEMS == EMS_Thumb) return;
552     EmitMappingSymbol("$t");
553     LastEMS = EMS_Thumb;
554   }
555
556   void EmitARMMappingSymbol() {
557     if (LastEMS == EMS_ARM) return;
558     EmitMappingSymbol("$a");
559     LastEMS = EMS_ARM;
560   }
561
562   void EmitMappingSymbol(StringRef Name) {
563     MCSymbol *Start = getContext().CreateTempSymbol();
564     EmitLabel(Start);
565
566     MCSymbol *Symbol =
567       getContext().GetOrCreateSymbol(Name + "." +
568                                      Twine(MappingSymbolCounter++));
569
570     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
571     MCELF::SetType(SD, ELF::STT_NOTYPE);
572     MCELF::SetBinding(SD, ELF::STB_LOCAL);
573     SD.setExternal(false);
574     AssignSection(Symbol, getCurrentSection().first);
575
576     const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
577     Symbol->setVariableValue(Value);
578   }
579
580   void EmitThumbFunc(MCSymbol *Func) override {
581     getAssembler().setIsThumbFunc(Func);
582     EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
583   }
584
585   // Helper functions for ARM exception handling directives
586   void Reset();
587
588   void EmitPersonalityFixup(StringRef Name);
589   void FlushPendingOffset();
590   void FlushUnwindOpcodes(bool NoHandlerData);
591
592   void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
593                          SectionKind Kind, const MCSymbol &Fn);
594   void SwitchToExTabSection(const MCSymbol &FnStart);
595   void SwitchToExIdxSection(const MCSymbol &FnStart);
596
597   void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
598
599   bool IsThumb;
600   int64_t MappingSymbolCounter;
601
602   DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
603   ElfMappingSymbol LastEMS;
604
605   // ARM Exception Handling Frame Information
606   MCSymbol *ExTab;
607   MCSymbol *FnStart;
608   const MCSymbol *Personality;
609   unsigned PersonalityIndex;
610   unsigned FPReg; // Frame pointer register
611   int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
612   int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
613   int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
614   bool UsedFP;
615   bool CantUnwind;
616   SmallVector<uint8_t, 64> Opcodes;
617   UnwindOpcodeAssembler UnwindOpAsm;
618 };
619 } // end anonymous namespace
620
621 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
622   return static_cast<ARMELFStreamer &>(Streamer);
623 }
624
625 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
626 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
627 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
628 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
629   getStreamer().emitPersonality(Personality);
630 }
631 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
632   getStreamer().emitPersonalityIndex(Index);
633 }
634 void ARMTargetELFStreamer::emitHandlerData() {
635   getStreamer().emitHandlerData();
636 }
637 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
638                                      int64_t Offset) {
639   getStreamer().emitSetFP(FpReg, SpReg, Offset);
640 }
641 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
642   getStreamer().emitMovSP(Reg, Offset);
643 }
644 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
645   getStreamer().emitPad(Offset);
646 }
647 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
648                                        bool isVector) {
649   getStreamer().emitRegSave(RegList, isVector);
650 }
651 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
652                                       const SmallVectorImpl<uint8_t> &Opcodes) {
653   getStreamer().emitUnwindRaw(Offset, Opcodes);
654 }
655 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
656   assert(!Vendor.empty() && "Vendor cannot be empty.");
657
658   if (CurrentVendor == Vendor)
659     return;
660
661   if (!CurrentVendor.empty())
662     finishAttributeSection();
663
664   assert(Contents.empty() &&
665          ".ARM.attributes should be flushed before changing vendor");
666   CurrentVendor = Vendor;
667
668 }
669 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
670   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
671 }
672 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
673                                              StringRef Value) {
674   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
675 }
676 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
677                                                 unsigned IntValue,
678                                                 StringRef StringValue) {
679   setAttributeItems(Attribute, IntValue, StringValue,
680                     /* OverwriteExisting= */ true);
681 }
682 void ARMTargetELFStreamer::emitArch(unsigned Value) {
683   Arch = Value;
684 }
685 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
686   EmittedArch = Value;
687 }
688 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
689   using namespace ARMBuildAttrs;
690
691   setAttributeItem(CPU_name,
692                    ARMTargetParser::getArchDefaultCPUName(Arch),
693                    false);
694
695   if (EmittedArch == ARM::AK_INVALID)
696     setAttributeItem(CPU_arch,
697                      ARMTargetParser::getArchDefaultCPUArch(Arch),
698                      false);
699   else
700     setAttributeItem(CPU_arch,
701                      ARMTargetParser::getArchDefaultCPUArch(EmittedArch),
702                      false);
703
704   switch (Arch) {
705   case ARM::AK_ARMV2:
706   case ARM::AK_ARMV2A:
707   case ARM::AK_ARMV3:
708   case ARM::AK_ARMV3M:
709   case ARM::AK_ARMV4:
710   case ARM::AK_ARMV5:
711     setAttributeItem(ARM_ISA_use, Allowed, false);
712     break;
713
714   case ARM::AK_ARMV4T:
715   case ARM::AK_ARMV5T:
716   case ARM::AK_ARMV5TE:
717   case ARM::AK_ARMV6:
718   case ARM::AK_ARMV6J:
719     setAttributeItem(ARM_ISA_use, Allowed, false);
720     setAttributeItem(THUMB_ISA_use, Allowed, false);
721     break;
722
723   case ARM::AK_ARMV6T2:
724     setAttributeItem(ARM_ISA_use, Allowed, false);
725     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
726     break;
727
728   case ARM::AK_ARMV6K:
729   case ARM::AK_ARMV6Z:
730   case ARM::AK_ARMV6ZK:
731     setAttributeItem(ARM_ISA_use, Allowed, false);
732     setAttributeItem(THUMB_ISA_use, Allowed, false);
733     setAttributeItem(Virtualization_use, AllowTZ, false);
734     break;
735
736   case ARM::AK_ARMV6M:
737     setAttributeItem(THUMB_ISA_use, Allowed, false);
738     break;
739
740   case ARM::AK_ARMV7:
741     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
742     break;
743
744   case ARM::AK_ARMV7A:
745     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
746     setAttributeItem(ARM_ISA_use, Allowed, false);
747     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
748     break;
749
750   case ARM::AK_ARMV7R:
751     setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
752     setAttributeItem(ARM_ISA_use, Allowed, false);
753     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
754     break;
755
756   case ARM::AK_ARMV7M:
757     setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
758     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
759     break;
760
761   case ARM::AK_ARMV8A:
762   case ARM::AK_ARMV8_1A:
763     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
764     setAttributeItem(ARM_ISA_use, Allowed, false);
765     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
766     setAttributeItem(MPextension_use, Allowed, false);
767     setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
768     break;
769
770   case ARM::AK_IWMMXT:
771     setAttributeItem(ARM_ISA_use, Allowed, false);
772     setAttributeItem(THUMB_ISA_use, Allowed, false);
773     setAttributeItem(WMMX_arch, AllowWMMXv1, false);
774     break;
775
776   case ARM::AK_IWMMXT2:
777     setAttributeItem(ARM_ISA_use, Allowed, false);
778     setAttributeItem(THUMB_ISA_use, Allowed, false);
779     setAttributeItem(WMMX_arch, AllowWMMXv2, false);
780     break;
781
782   default:
783     report_fatal_error("Unknown Arch: " + Twine(Arch));
784     break;
785   }
786 }
787 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
788   FPU = Value;
789 }
790 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
791   switch (FPU) {
792   case ARM::FK_VFP:
793   case ARM::FK_VFPV2:
794     setAttributeItem(ARMBuildAttrs::FP_arch,
795                      ARMBuildAttrs::AllowFPv2,
796                      /* OverwriteExisting= */ false);
797     break;
798
799   case ARM::FK_VFPV3:
800     setAttributeItem(ARMBuildAttrs::FP_arch,
801                      ARMBuildAttrs::AllowFPv3A,
802                      /* OverwriteExisting= */ false);
803     break;
804
805   case ARM::FK_VFPV3_D16:
806     setAttributeItem(ARMBuildAttrs::FP_arch,
807                      ARMBuildAttrs::AllowFPv3B,
808                      /* OverwriteExisting= */ false);
809     break;
810
811   case ARM::FK_VFPV4:
812     setAttributeItem(ARMBuildAttrs::FP_arch,
813                      ARMBuildAttrs::AllowFPv4A,
814                      /* OverwriteExisting= */ false);
815     break;
816
817   case ARM::FK_VFPV4_D16:
818     setAttributeItem(ARMBuildAttrs::FP_arch,
819                      ARMBuildAttrs::AllowFPv4B,
820                      /* OverwriteExisting= */ false);
821     break;
822
823   case ARM::FK_FP_ARMV8:
824     setAttributeItem(ARMBuildAttrs::FP_arch,
825                      ARMBuildAttrs::AllowFPARMv8A,
826                      /* OverwriteExisting= */ false);
827     break;
828
829   // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
830   // uses the FP_ARMV8_D16 build attribute.
831   case ARM::FK_FPV5_D16:
832     setAttributeItem(ARMBuildAttrs::FP_arch,
833                      ARMBuildAttrs::AllowFPARMv8B,
834                      /* OverwriteExisting= */ false);
835     break;
836
837   case ARM::FK_NEON:
838     setAttributeItem(ARMBuildAttrs::FP_arch,
839                      ARMBuildAttrs::AllowFPv3A,
840                      /* OverwriteExisting= */ false);
841     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
842                      ARMBuildAttrs::AllowNeon,
843                      /* OverwriteExisting= */ false);
844     break;
845
846   case ARM::FK_NEON_VFPV4:
847     setAttributeItem(ARMBuildAttrs::FP_arch,
848                      ARMBuildAttrs::AllowFPv4A,
849                      /* OverwriteExisting= */ false);
850     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
851                      ARMBuildAttrs::AllowNeon2,
852                      /* OverwriteExisting= */ false);
853     break;
854
855   case ARM::FK_NEON_FP_ARMV8:
856   case ARM::FK_CRYPTO_NEON_FP_ARMV8:
857     setAttributeItem(ARMBuildAttrs::FP_arch,
858                      ARMBuildAttrs::AllowFPARMv8A,
859                      /* OverwriteExisting= */ false);
860     // 'Advanced_SIMD_arch' must be emitted not here, but within
861     // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
862     break;
863
864   case ARM::FK_SOFTVFP:
865     break;
866
867   default:
868     report_fatal_error("Unknown FPU: " + Twine(FPU));
869     break;
870   }
871 }
872 size_t ARMTargetELFStreamer::calculateContentSize() const {
873   size_t Result = 0;
874   for (size_t i = 0; i < Contents.size(); ++i) {
875     AttributeItem item = Contents[i];
876     switch (item.Type) {
877     case AttributeItem::HiddenAttribute:
878       break;
879     case AttributeItem::NumericAttribute:
880       Result += getULEB128Size(item.Tag);
881       Result += getULEB128Size(item.IntValue);
882       break;
883     case AttributeItem::TextAttribute:
884       Result += getULEB128Size(item.Tag);
885       Result += item.StringValue.size() + 1; // string + '\0'
886       break;
887     case AttributeItem::NumericAndTextAttributes:
888       Result += getULEB128Size(item.Tag);
889       Result += getULEB128Size(item.IntValue);
890       Result += item.StringValue.size() + 1; // string + '\0';
891       break;
892     }
893   }
894   return Result;
895 }
896 void ARMTargetELFStreamer::finishAttributeSection() {
897   // <format-version>
898   // [ <section-length> "vendor-name"
899   // [ <file-tag> <size> <attribute>*
900   //   | <section-tag> <size> <section-number>* 0 <attribute>*
901   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
902   //   ]+
903   // ]*
904
905   if (FPU != ARM::FK_INVALID)
906     emitFPUDefaultAttributes();
907
908   if (Arch != ARM::AK_INVALID)
909     emitArchDefaultAttributes();
910
911   if (Contents.empty())
912     return;
913
914   std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
915
916   ARMELFStreamer &Streamer = getStreamer();
917
918   // Switch to .ARM.attributes section
919   if (AttributeSection) {
920     Streamer.SwitchSection(AttributeSection);
921   } else {
922     AttributeSection = Streamer.getContext().getELFSection(
923         ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
924     Streamer.SwitchSection(AttributeSection);
925
926     // Format version
927     Streamer.EmitIntValue(0x41, 1);
928   }
929
930   // Vendor size + Vendor name + '\0'
931   const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
932
933   // Tag + Tag Size
934   const size_t TagHeaderSize = 1 + 4;
935
936   const size_t ContentsSize = calculateContentSize();
937
938   Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
939   Streamer.EmitBytes(CurrentVendor);
940   Streamer.EmitIntValue(0, 1); // '\0'
941
942   Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
943   Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
944
945   // Size should have been accounted for already, now
946   // emit each field as its type (ULEB or String)
947   for (size_t i = 0; i < Contents.size(); ++i) {
948     AttributeItem item = Contents[i];
949     Streamer.EmitULEB128IntValue(item.Tag);
950     switch (item.Type) {
951     default: llvm_unreachable("Invalid attribute type");
952     case AttributeItem::NumericAttribute:
953       Streamer.EmitULEB128IntValue(item.IntValue);
954       break;
955     case AttributeItem::TextAttribute:
956       Streamer.EmitBytes(item.StringValue);
957       Streamer.EmitIntValue(0, 1); // '\0'
958       break;
959     case AttributeItem::NumericAndTextAttributes:
960       Streamer.EmitULEB128IntValue(item.IntValue);
961       Streamer.EmitBytes(item.StringValue);
962       Streamer.EmitIntValue(0, 1); // '\0'
963       break;
964     }
965   }
966
967   Contents.clear();
968   FPU = ARM::FK_INVALID;
969 }
970
971 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
972   ARMELFStreamer &Streamer = getStreamer();
973   if (!Streamer.IsThumb)
974     return;
975
976   const MCSymbolData &SD = Streamer.getOrCreateSymbolData(Symbol);
977   unsigned Type = MCELF::GetType(SD);
978   if (Type == ELF_STT_Func || Type == ELF_STT_GnuIFunc)
979     Streamer.EmitThumbFunc(Symbol);
980 }
981
982 void
983 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
984   getStreamer().EmitFixup(S, FK_Data_4);
985 }
986
987 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
988   if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
989     const MCSymbol &Sym = SRE->getSymbol();
990     if (!Sym.isDefined()) {
991       getStreamer().EmitAssignment(Symbol, Value);
992       return;
993     }
994   }
995
996   getStreamer().EmitThumbFunc(Symbol);
997   getStreamer().EmitAssignment(Symbol, Value);
998 }
999
1000 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1001   getStreamer().emitInst(Inst, Suffix);
1002 }
1003
1004 void ARMELFStreamer::FinishImpl() {
1005   MCTargetStreamer &TS = *getTargetStreamer();
1006   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1007   ATS.finishAttributeSection();
1008
1009   MCELFStreamer::FinishImpl();
1010 }
1011
1012 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1013                                               unsigned Type,
1014                                               unsigned Flags,
1015                                               SectionKind Kind,
1016                                               const MCSymbol &Fn) {
1017   const MCSectionELF &FnSection =
1018     static_cast<const MCSectionELF &>(Fn.getSection());
1019
1020   // Create the name for new section
1021   StringRef FnSecName(FnSection.getSectionName());
1022   SmallString<128> EHSecName(Prefix);
1023   if (FnSecName != ".text") {
1024     EHSecName += FnSecName;
1025   }
1026
1027   // Get .ARM.extab or .ARM.exidx section
1028   const MCSymbol *Group = FnSection.getGroup();
1029   if (Group)
1030     Flags |= ELF::SHF_GROUP;
1031   const MCSectionELF *EHSection =
1032       getContext().getELFSection(EHSecName, Type, Flags, 0, Group,
1033                                  FnSection.getUniqueID(), nullptr, &FnSection);
1034
1035   assert(EHSection && "Failed to get the required EH section");
1036
1037   // Switch to .ARM.extab or .ARM.exidx section
1038   SwitchSection(EHSection);
1039   EmitCodeAlignment(4);
1040 }
1041
1042 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1043   SwitchToEHSection(".ARM.extab",
1044                     ELF::SHT_PROGBITS,
1045                     ELF::SHF_ALLOC,
1046                     SectionKind::getDataRel(),
1047                     FnStart);
1048 }
1049
1050 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1051   SwitchToEHSection(".ARM.exidx",
1052                     ELF::SHT_ARM_EXIDX,
1053                     ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1054                     SectionKind::getDataRel(),
1055                     FnStart);
1056 }
1057 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1058   MCDataFragment *Frag = getOrCreateDataFragment();
1059   Frag->getFixups().push_back(MCFixup::create(Frag->getContents().size(), Expr,
1060                                               Kind));
1061 }
1062
1063 void ARMELFStreamer::Reset() {
1064   ExTab = nullptr;
1065   FnStart = nullptr;
1066   Personality = nullptr;
1067   PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1068   FPReg = ARM::SP;
1069   FPOffset = 0;
1070   SPOffset = 0;
1071   PendingOffset = 0;
1072   UsedFP = false;
1073   CantUnwind = false;
1074
1075   Opcodes.clear();
1076   UnwindOpAsm.Reset();
1077 }
1078
1079 void ARMELFStreamer::emitFnStart() {
1080   assert(FnStart == nullptr);
1081   FnStart = getContext().CreateTempSymbol();
1082   EmitLabel(FnStart);
1083 }
1084
1085 void ARMELFStreamer::emitFnEnd() {
1086   assert(FnStart && ".fnstart must precedes .fnend");
1087
1088   // Emit unwind opcodes if there is no .handlerdata directive
1089   if (!ExTab && !CantUnwind)
1090     FlushUnwindOpcodes(true);
1091
1092   // Emit the exception index table entry
1093   SwitchToExIdxSection(*FnStart);
1094
1095   if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1096     EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1097
1098   const MCSymbolRefExpr *FnStartRef =
1099     MCSymbolRefExpr::Create(FnStart,
1100                             MCSymbolRefExpr::VK_ARM_PREL31,
1101                             getContext());
1102
1103   EmitValue(FnStartRef, 4);
1104
1105   if (CantUnwind) {
1106     EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1107   } else if (ExTab) {
1108     // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1109     const MCSymbolRefExpr *ExTabEntryRef =
1110       MCSymbolRefExpr::Create(ExTab,
1111                               MCSymbolRefExpr::VK_ARM_PREL31,
1112                               getContext());
1113     EmitValue(ExTabEntryRef, 4);
1114   } else {
1115     // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1116     // the second word of exception index table entry.  The size of the unwind
1117     // opcodes should always be 4 bytes.
1118     assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1119            "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1120     assert(Opcodes.size() == 4u &&
1121            "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1122     uint64_t Intval = Opcodes[0] |
1123                       Opcodes[1] << 8 |
1124                       Opcodes[2] << 16 |
1125                       Opcodes[3] << 24;
1126     EmitIntValue(Intval, Opcodes.size());
1127   }
1128
1129   // Switch to the section containing FnStart
1130   SwitchSection(&FnStart->getSection());
1131
1132   // Clean exception handling frame information
1133   Reset();
1134 }
1135
1136 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1137
1138 // Add the R_ARM_NONE fixup at the same position
1139 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1140   const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
1141
1142   const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
1143       PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1144
1145   visitUsedExpr(*PersonalityRef);
1146   MCDataFragment *DF = getOrCreateDataFragment();
1147   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
1148                                             PersonalityRef,
1149                                             MCFixup::getKindForSize(4, false)));
1150 }
1151
1152 void ARMELFStreamer::FlushPendingOffset() {
1153   if (PendingOffset != 0) {
1154     UnwindOpAsm.EmitSPOffset(-PendingOffset);
1155     PendingOffset = 0;
1156   }
1157 }
1158
1159 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1160   // Emit the unwind opcode to restore $sp.
1161   if (UsedFP) {
1162     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1163     int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1164     UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1165     UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1166   } else {
1167     FlushPendingOffset();
1168   }
1169
1170   // Finalize the unwind opcode sequence
1171   UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1172
1173   // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1174   // section.  Thus, we don't have to create an entry in the .ARM.extab
1175   // section.
1176   if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1177     return;
1178
1179   // Switch to .ARM.extab section.
1180   SwitchToExTabSection(*FnStart);
1181
1182   // Create .ARM.extab label for offset in .ARM.exidx
1183   assert(!ExTab);
1184   ExTab = getContext().CreateTempSymbol();
1185   EmitLabel(ExTab);
1186
1187   // Emit personality
1188   if (Personality) {
1189     const MCSymbolRefExpr *PersonalityRef =
1190       MCSymbolRefExpr::Create(Personality,
1191                               MCSymbolRefExpr::VK_ARM_PREL31,
1192                               getContext());
1193
1194     EmitValue(PersonalityRef, 4);
1195   }
1196
1197   // Emit unwind opcodes
1198   assert((Opcodes.size() % 4) == 0 &&
1199          "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1200   for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1201     uint64_t Intval = Opcodes[I] |
1202                       Opcodes[I + 1] << 8 |
1203                       Opcodes[I + 2] << 16 |
1204                       Opcodes[I + 3] << 24;
1205     EmitIntValue(Intval, 4);
1206   }
1207
1208   // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1209   // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1210   // after the unwind opcodes.  The handler data consists of several 32-bit
1211   // words, and should be terminated by zero.
1212   //
1213   // In case that the .handlerdata directive is not specified by the
1214   // programmer, we should emit zero to terminate the handler data.
1215   if (NoHandlerData && !Personality)
1216     EmitIntValue(0, 4);
1217 }
1218
1219 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1220
1221 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1222   Personality = Per;
1223   UnwindOpAsm.setPersonality(Per);
1224 }
1225
1226 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1227   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1228   PersonalityIndex = Index;
1229 }
1230
1231 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1232                                int64_t Offset) {
1233   assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1234          "the operand of .setfp directive should be either $sp or $fp");
1235
1236   UsedFP = true;
1237   FPReg = NewFPReg;
1238
1239   if (NewSPReg == ARM::SP)
1240     FPOffset = SPOffset + Offset;
1241   else
1242     FPOffset += Offset;
1243 }
1244
1245 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1246   assert((Reg != ARM::SP && Reg != ARM::PC) &&
1247          "the operand of .movsp cannot be either sp or pc");
1248   assert(FPReg == ARM::SP && "current FP must be SP");
1249
1250   FlushPendingOffset();
1251
1252   FPReg = Reg;
1253   FPOffset = SPOffset + Offset;
1254
1255   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1256   UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1257 }
1258
1259 void ARMELFStreamer::emitPad(int64_t Offset) {
1260   // Track the change of the $sp offset
1261   SPOffset -= Offset;
1262
1263   // To squash multiple .pad directives, we should delay the unwind opcode
1264   // until the .save, .vsave, .handlerdata, or .fnend directives.
1265   PendingOffset -= Offset;
1266 }
1267
1268 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1269                                  bool IsVector) {
1270   // Collect the registers in the register list
1271   unsigned Count = 0;
1272   uint32_t Mask = 0;
1273   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1274   for (size_t i = 0; i < RegList.size(); ++i) {
1275     unsigned Reg = MRI->getEncodingValue(RegList[i]);
1276     assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1277     unsigned Bit = (1u << Reg);
1278     if ((Mask & Bit) == 0) {
1279       Mask |= Bit;
1280       ++Count;
1281     }
1282   }
1283
1284   // Track the change the $sp offset: For the .save directive, the
1285   // corresponding push instruction will decrease the $sp by (4 * Count).
1286   // For the .vsave directive, the corresponding vpush instruction will
1287   // decrease $sp by (8 * Count).
1288   SPOffset -= Count * (IsVector ? 8 : 4);
1289
1290   // Emit the opcode
1291   FlushPendingOffset();
1292   if (IsVector)
1293     UnwindOpAsm.EmitVFPRegSave(Mask);
1294   else
1295     UnwindOpAsm.EmitRegSave(Mask);
1296 }
1297
1298 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1299                                    const SmallVectorImpl<uint8_t> &Opcodes) {
1300   FlushPendingOffset();
1301   SPOffset = SPOffset - Offset;
1302   UnwindOpAsm.EmitRaw(Opcodes);
1303 }
1304
1305 namespace llvm {
1306
1307 MCTargetStreamer *createARMTargetAsmStreamer(MCStreamer &S,
1308                                              formatted_raw_ostream &OS,
1309                                              MCInstPrinter *InstPrint,
1310                                              bool isVerboseAsm) {
1311   return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1312 }
1313
1314 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1315   return new ARMTargetStreamer(S);
1316 }
1317
1318 MCTargetStreamer *createARMObjectTargetStreamer(MCStreamer &S,
1319                                                 const MCSubtargetInfo &STI) {
1320   Triple TT(STI.getTargetTriple());
1321   if (TT.getObjectFormat() == Triple::ELF)
1322     return new ARMTargetELFStreamer(S);
1323   return new ARMTargetStreamer(S);
1324 }
1325
1326 MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1327                                     raw_pwrite_stream &OS,
1328                                     MCCodeEmitter *Emitter, bool RelaxAll,
1329                                     bool IsThumb) {
1330     ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1331     // FIXME: This should eventually end up somewhere else where more
1332     // intelligent flag decisions can be made. For now we are just maintaining
1333     // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1334     S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1335
1336     if (RelaxAll)
1337       S->getAssembler().setRelaxAll(true);
1338     return S;
1339   }
1340
1341 }
1342
1343