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