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