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