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