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