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