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