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