1 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file assembles .s files and emits ARM ELF .o object files. Different
10 // from generic ELF streamer in emitting mapping symbols ($a, $t and $d) to
11 // delimit regions of data and code.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMRegisterInfo.h"
16 #include "ARMUnwindOpAsm.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/BinaryFormat/ELF.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/MCELFStreamer.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCFixup.h"
32 #include "llvm/MC/MCFragment.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCObjectWriter.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/MCSubtargetInfo.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/MC/MCSymbolELF.h"
43 #include "llvm/MC/SectionKind.h"
44 #include "llvm/Support/ARMBuildAttributes.h"
45 #include "llvm/Support/ARMEHABI.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/FormattedStream.h"
49 #include "llvm/Support/LEB128.h"
50 #include "llvm/Support/TargetParser.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <climits>
55 #include <cstddef>
56 #include <cstdint>
57 #include <string>
58 
59 using namespace llvm;
60 
61 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
62   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
63          "Invalid personality index");
64   return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
65 }
66 
67 namespace {
68 
69 class ARMELFStreamer;
70 
71 class ARMTargetAsmStreamer : public ARMTargetStreamer {
72   formatted_raw_ostream &OS;
73   MCInstPrinter &InstPrinter;
74   bool IsVerboseAsm;
75 
76   void emitFnStart() override;
77   void emitFnEnd() override;
78   void emitCantUnwind() override;
79   void emitPersonality(const MCSymbol *Personality) override;
80   void emitPersonalityIndex(unsigned Index) override;
81   void emitHandlerData() override;
82   void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
83   void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
84   void emitPad(int64_t Offset) override;
85   void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
86                    bool isVector) override;
87   void emitUnwindRaw(int64_t Offset,
88                      const SmallVectorImpl<uint8_t> &Opcodes) override;
89 
90   void switchVendor(StringRef Vendor) override;
91   void emitAttribute(unsigned Attribute, unsigned Value) override;
92   void emitTextAttribute(unsigned Attribute, StringRef String) override;
93   void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
94                             StringRef StringValue) override;
95   void emitArch(ARM::ArchKind Arch) override;
96   void emitArchExtension(uint64_t ArchExt) override;
97   void emitObjectArch(ARM::ArchKind Arch) override;
98   void emitFPU(unsigned FPU) override;
99   void emitInst(uint32_t Inst, char Suffix = '\0') override;
100   void finishAttributeSection() override;
101 
102   void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
103   void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
104 
105 public:
106   ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
107                        MCInstPrinter &InstPrinter, bool VerboseAsm);
108 };
109 
110 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
111                                            formatted_raw_ostream &OS,
112                                            MCInstPrinter &InstPrinter,
113                                            bool VerboseAsm)
114     : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
115       IsVerboseAsm(VerboseAsm) {}
116 
117 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
118 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
119 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
120 
121 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
122   OS << "\t.personality " << Personality->getName() << '\n';
123 }
124 
125 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
126   OS << "\t.personalityindex " << Index << '\n';
127 }
128 
129 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
130 
131 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
132                                      int64_t Offset) {
133   OS << "\t.setfp\t";
134   InstPrinter.printRegName(OS, FpReg);
135   OS << ", ";
136   InstPrinter.printRegName(OS, SpReg);
137   if (Offset)
138     OS << ", #" << Offset;
139   OS << '\n';
140 }
141 
142 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
143   assert((Reg != ARM::SP && Reg != ARM::PC) &&
144          "the operand of .movsp cannot be either sp or pc");
145 
146   OS << "\t.movsp\t";
147   InstPrinter.printRegName(OS, Reg);
148   if (Offset)
149     OS << ", #" << Offset;
150   OS << '\n';
151 }
152 
153 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
154   OS << "\t.pad\t#" << Offset << '\n';
155 }
156 
157 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
158                                        bool isVector) {
159   assert(RegList.size() && "RegList should not be empty");
160   if (isVector)
161     OS << "\t.vsave\t{";
162   else
163     OS << "\t.save\t{";
164 
165   InstPrinter.printRegName(OS, RegList[0]);
166 
167   for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
168     OS << ", ";
169     InstPrinter.printRegName(OS, RegList[i]);
170   }
171 
172   OS << "}\n";
173 }
174 
175 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {}
176 
177 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
178   OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
179   if (IsVerboseAsm) {
180     StringRef Name =
181         ELFAttrs::attrTypeAsString(Attribute, ARMBuildAttrs::ARMAttributeTags);
182     if (!Name.empty())
183       OS << "\t@ " << Name;
184   }
185   OS << "\n";
186 }
187 
188 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
189                                              StringRef String) {
190   switch (Attribute) {
191   case ARMBuildAttrs::CPU_name:
192     OS << "\t.cpu\t" << String.lower();
193     break;
194   default:
195     OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
196     if (IsVerboseAsm) {
197       StringRef Name = ELFAttrs::attrTypeAsString(
198           Attribute, ARMBuildAttrs::ARMAttributeTags);
199       if (!Name.empty())
200         OS << "\t@ " << Name;
201     }
202     break;
203   }
204   OS << "\n";
205 }
206 
207 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
208                                                 unsigned IntValue,
209                                                 StringRef StringValue) {
210   switch (Attribute) {
211   default: llvm_unreachable("unsupported multi-value attribute in asm mode");
212   case ARMBuildAttrs::compatibility:
213     OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
214     if (!StringValue.empty())
215       OS << ", \"" << StringValue << "\"";
216     if (IsVerboseAsm)
217       OS << "\t@ "
218          << ELFAttrs::attrTypeAsString(Attribute,
219                                        ARMBuildAttrs::ARMAttributeTags);
220     break;
221   }
222   OS << "\n";
223 }
224 
225 void ARMTargetAsmStreamer::emitArch(ARM::ArchKind Arch) {
226   OS << "\t.arch\t" << ARM::getArchName(Arch) << "\n";
227 }
228 
229 void ARMTargetAsmStreamer::emitArchExtension(uint64_t ArchExt) {
230   OS << "\t.arch_extension\t" << ARM::getArchExtName(ArchExt) << "\n";
231 }
232 
233 void ARMTargetAsmStreamer::emitObjectArch(ARM::ArchKind Arch) {
234   OS << "\t.object_arch\t" << ARM::getArchName(Arch) << '\n';
235 }
236 
237 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
238   OS << "\t.fpu\t" << ARM::getFPUName(FPU) << "\n";
239 }
240 
241 void ARMTargetAsmStreamer::finishAttributeSection() {}
242 
243 void
244 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
245   OS << "\t.tlsdescseq\t" << S->getSymbol().getName() << "\n";
246 }
247 
248 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
249   const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
250 
251   OS << "\t.thumb_set\t";
252   Symbol->print(OS, MAI);
253   OS << ", ";
254   Value->print(OS, MAI);
255   OS << '\n';
256 }
257 
258 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
259   OS << "\t.inst";
260   if (Suffix)
261     OS << "." << Suffix;
262   OS << "\t0x" << Twine::utohexstr(Inst) << "\n";
263 }
264 
265 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
266                                       const SmallVectorImpl<uint8_t> &Opcodes) {
267   OS << "\t.unwind_raw " << Offset;
268   for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
269                                                 OCE = Opcodes.end();
270        OCI != OCE; ++OCI)
271     OS << ", 0x" << Twine::utohexstr(*OCI);
272   OS << '\n';
273 }
274 
275 class ARMTargetELFStreamer : public ARMTargetStreamer {
276 private:
277   // This structure holds all attributes, accounting for
278   // their string/numeric value, so we can later emit them
279   // in declaration order, keeping all in the same vector
280   struct AttributeItem {
281     enum {
282       HiddenAttribute = 0,
283       NumericAttribute,
284       TextAttribute,
285       NumericAndTextAttributes
286     } Type;
287     unsigned Tag;
288     unsigned IntValue;
289     std::string StringValue;
290 
291     static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
292       // The conformance tag must be emitted first when serialised
293       // into an object file. Specifically, the addenda to the ARM ABI
294       // states that (2.3.7.4):
295       //
296       // "To simplify recognition by consumers in the common case of
297       // claiming conformity for the whole file, this tag should be
298       // emitted first in a file-scope sub-subsection of the first
299       // public subsection of the attributes section."
300       //
301       // So it is special-cased in this comparison predicate when the
302       // attributes are sorted in finishAttributeSection().
303       return (RHS.Tag != ARMBuildAttrs::conformance) &&
304              ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
305     }
306   };
307 
308   StringRef CurrentVendor;
309   unsigned FPU = ARM::FK_INVALID;
310   ARM::ArchKind Arch = ARM::ArchKind::INVALID;
311   ARM::ArchKind EmittedArch = ARM::ArchKind::INVALID;
312   SmallVector<AttributeItem, 64> Contents;
313 
314   MCSection *AttributeSection = nullptr;
315 
316   AttributeItem *getAttributeItem(unsigned Attribute) {
317     for (size_t i = 0; i < Contents.size(); ++i)
318       if (Contents[i].Tag == Attribute)
319         return &Contents[i];
320     return nullptr;
321   }
322 
323   void setAttributeItem(unsigned Attribute, unsigned Value,
324                         bool OverwriteExisting) {
325     // Look for existing attribute item
326     if (AttributeItem *Item = getAttributeItem(Attribute)) {
327       if (!OverwriteExisting)
328         return;
329       Item->Type = AttributeItem::NumericAttribute;
330       Item->IntValue = Value;
331       return;
332     }
333 
334     // Create new attribute item
335     AttributeItem Item = {AttributeItem::NumericAttribute, Attribute, Value,
336                           std::string(StringRef(""))};
337     Contents.push_back(Item);
338   }
339 
340   void setAttributeItem(unsigned Attribute, StringRef Value,
341                         bool OverwriteExisting) {
342     // Look for existing attribute item
343     if (AttributeItem *Item = getAttributeItem(Attribute)) {
344       if (!OverwriteExisting)
345         return;
346       Item->Type = AttributeItem::TextAttribute;
347       Item->StringValue = std::string(Value);
348       return;
349     }
350 
351     // Create new attribute item
352     AttributeItem Item = {AttributeItem::TextAttribute, Attribute, 0,
353                           std::string(Value)};
354     Contents.push_back(Item);
355   }
356 
357   void setAttributeItems(unsigned Attribute, unsigned IntValue,
358                          StringRef StringValue, bool OverwriteExisting) {
359     // Look for existing attribute item
360     if (AttributeItem *Item = getAttributeItem(Attribute)) {
361       if (!OverwriteExisting)
362         return;
363       Item->Type = AttributeItem::NumericAndTextAttributes;
364       Item->IntValue = IntValue;
365       Item->StringValue = std::string(StringValue);
366       return;
367     }
368 
369     // Create new attribute item
370     AttributeItem Item = {AttributeItem::NumericAndTextAttributes, Attribute,
371                           IntValue, std::string(StringValue)};
372     Contents.push_back(Item);
373   }
374 
375   void emitArchDefaultAttributes();
376   void emitFPUDefaultAttributes();
377 
378   ARMELFStreamer &getStreamer();
379 
380   void emitFnStart() override;
381   void emitFnEnd() override;
382   void emitCantUnwind() override;
383   void emitPersonality(const MCSymbol *Personality) override;
384   void emitPersonalityIndex(unsigned Index) override;
385   void emitHandlerData() override;
386   void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
387   void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
388   void emitPad(int64_t Offset) override;
389   void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
390                    bool isVector) override;
391   void emitUnwindRaw(int64_t Offset,
392                      const SmallVectorImpl<uint8_t> &Opcodes) override;
393 
394   void switchVendor(StringRef Vendor) override;
395   void emitAttribute(unsigned Attribute, unsigned Value) override;
396   void emitTextAttribute(unsigned Attribute, StringRef String) override;
397   void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
398                             StringRef StringValue) override;
399   void emitArch(ARM::ArchKind Arch) override;
400   void emitObjectArch(ARM::ArchKind Arch) override;
401   void emitFPU(unsigned FPU) override;
402   void emitInst(uint32_t Inst, char Suffix = '\0') override;
403   void finishAttributeSection() override;
404   void emitLabel(MCSymbol *Symbol) override;
405 
406   void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
407   void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
408 
409   size_t calculateContentSize() const;
410 
411   // Reset state between object emissions
412   void reset() override;
413 
414 public:
415   ARMTargetELFStreamer(MCStreamer &S)
416     : ARMTargetStreamer(S), CurrentVendor("aeabi") {}
417 };
418 
419 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
420 /// the appropriate points in the object files. These symbols are defined in the
421 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
422 ///
423 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
424 /// region of ARM code, Thumb code or data in a section. In practice, this
425 /// emission does not rely on explicit assembler directives but on inherent
426 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
427 /// r0, r0, r0" an instruction).
428 ///
429 /// As a result this system is orthogonal to the DataRegion infrastructure used
430 /// by MachO. Beware!
431 class ARMELFStreamer : public MCELFStreamer {
432 public:
433   friend class ARMTargetELFStreamer;
434 
435   ARMELFStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> TAB,
436                  std::unique_ptr<MCObjectWriter> OW,
437                  std::unique_ptr<MCCodeEmitter> Emitter, bool IsThumb,
438                  bool IsAndroid)
439       : MCELFStreamer(Context, std::move(TAB), std::move(OW),
440                       std::move(Emitter)),
441         IsThumb(IsThumb), IsAndroid(IsAndroid) {
442     EHReset();
443   }
444 
445   ~ARMELFStreamer() override = default;
446 
447   void finishImpl() override;
448 
449   // ARM exception handling directives
450   void emitFnStart();
451   void emitFnEnd();
452   void emitCantUnwind();
453   void emitPersonality(const MCSymbol *Per);
454   void emitPersonalityIndex(unsigned index);
455   void emitHandlerData();
456   void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
457   void emitMovSP(unsigned Reg, int64_t Offset = 0);
458   void emitPad(int64_t Offset);
459   void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
460   void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
461   void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
462                 SMLoc Loc) override {
463     emitDataMappingSymbol();
464     MCObjectStreamer::emitFill(NumBytes, FillValue, Loc);
465   }
466 
467   void changeSection(MCSection *Section, const MCExpr *Subsection) override {
468     LastMappingSymbols[getCurrentSection().first] = std::move(LastEMSInfo);
469     MCELFStreamer::changeSection(Section, Subsection);
470     auto LastMappingSymbol = LastMappingSymbols.find(Section);
471     if (LastMappingSymbol != LastMappingSymbols.end()) {
472       LastEMSInfo = std::move(LastMappingSymbol->second);
473       return;
474     }
475     LastEMSInfo.reset(new ElfMappingSymbolInfo(SMLoc(), nullptr, 0));
476   }
477 
478   /// This function is the one used to emit instruction data into the ELF
479   /// streamer. We override it to add the appropriate mapping symbol if
480   /// necessary.
481   void emitInstruction(const MCInst &Inst,
482                        const MCSubtargetInfo &STI) override {
483     if (IsThumb)
484       EmitThumbMappingSymbol();
485     else
486       EmitARMMappingSymbol();
487 
488     MCELFStreamer::emitInstruction(Inst, STI);
489   }
490 
491   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       // Thumb wide instructions are emitted as a pair of 16-bit words of the
515       // appropriate endianness.
516       for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
517         const unsigned I0 = LittleEndian ? II + 0 : II + 1;
518         const unsigned I1 = LittleEndian ? II + 1 : II + 0;
519         Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
520         Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
521       }
522 
523       break;
524     default:
525       llvm_unreachable("Invalid Suffix");
526     }
527 
528     MCELFStreamer::emitBytes(StringRef(Buffer, Size));
529   }
530 
531   /// This is one of the functions used to emit data into an ELF section, so the
532   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
533   /// necessary.
534   void emitBytes(StringRef Data) override {
535     emitDataMappingSymbol();
536     MCELFStreamer::emitBytes(Data);
537   }
538 
539   void FlushPendingMappingSymbol() {
540     if (!LastEMSInfo->hasInfo())
541       return;
542     ElfMappingSymbolInfo *EMS = LastEMSInfo.get();
543     EmitMappingSymbol("$d", EMS->Loc, EMS->F, EMS->Offset);
544     EMS->resetInfo();
545   }
546 
547   /// This is one of the functions used to emit data into an ELF section, so the
548   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
549   /// necessary.
550   void emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) override {
551     if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value)) {
552       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4)) {
553         getContext().reportError(Loc, "relocated expression must be 32-bit");
554         return;
555       }
556       getOrCreateDataFragment();
557     }
558 
559     emitDataMappingSymbol();
560     MCELFStreamer::emitValueImpl(Value, Size, Loc);
561   }
562 
563   void emitAssemblerFlag(MCAssemblerFlag Flag) override {
564     MCELFStreamer::emitAssemblerFlag(Flag);
565 
566     switch (Flag) {
567     case MCAF_SyntaxUnified:
568       return; // no-op here.
569     case MCAF_Code16:
570       IsThumb = true;
571       return; // Change to Thumb mode
572     case MCAF_Code32:
573       IsThumb = false;
574       return; // Change to ARM mode
575     case MCAF_Code64:
576       return;
577     case MCAF_SubsectionsViaSymbols:
578       return;
579     }
580   }
581 
582 private:
583   enum ElfMappingSymbol {
584     EMS_None,
585     EMS_ARM,
586     EMS_Thumb,
587     EMS_Data
588   };
589 
590   struct ElfMappingSymbolInfo {
591     explicit ElfMappingSymbolInfo(SMLoc Loc, MCFragment *F, uint64_t O)
592         : Loc(Loc), F(F), Offset(O), State(EMS_None) {}
593     void resetInfo() {
594       F = nullptr;
595       Offset = 0;
596     }
597     bool hasInfo() { return F != nullptr; }
598     SMLoc Loc;
599     MCFragment *F;
600     uint64_t Offset;
601     ElfMappingSymbol State;
602   };
603 
604   void emitDataMappingSymbol() {
605     if (LastEMSInfo->State == EMS_Data)
606       return;
607     else if (LastEMSInfo->State == EMS_None) {
608       // This is a tentative symbol, it won't really be emitted until it's
609       // actually needed.
610       ElfMappingSymbolInfo *EMS = LastEMSInfo.get();
611       auto *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
612       if (!DF)
613         return;
614       EMS->Loc = SMLoc();
615       EMS->F = getCurrentFragment();
616       EMS->Offset = DF->getContents().size();
617       LastEMSInfo->State = EMS_Data;
618       return;
619     }
620     EmitMappingSymbol("$d");
621     LastEMSInfo->State = EMS_Data;
622   }
623 
624   void EmitThumbMappingSymbol() {
625     if (LastEMSInfo->State == EMS_Thumb)
626       return;
627     FlushPendingMappingSymbol();
628     EmitMappingSymbol("$t");
629     LastEMSInfo->State = EMS_Thumb;
630   }
631 
632   void EmitARMMappingSymbol() {
633     if (LastEMSInfo->State == EMS_ARM)
634       return;
635     FlushPendingMappingSymbol();
636     EmitMappingSymbol("$a");
637     LastEMSInfo->State = EMS_ARM;
638   }
639 
640   void EmitMappingSymbol(StringRef Name) {
641     auto *Symbol = cast<MCSymbolELF>(getContext().getOrCreateSymbol(
642         Name + "." + Twine(MappingSymbolCounter++)));
643     emitLabel(Symbol);
644 
645     Symbol->setType(ELF::STT_NOTYPE);
646     Symbol->setBinding(ELF::STB_LOCAL);
647   }
648 
649   void EmitMappingSymbol(StringRef Name, SMLoc Loc, MCFragment *F,
650                          uint64_t Offset) {
651     auto *Symbol = cast<MCSymbolELF>(getContext().getOrCreateSymbol(
652         Name + "." + Twine(MappingSymbolCounter++)));
653     emitLabelAtPos(Symbol, Loc, F, Offset);
654     Symbol->setType(ELF::STT_NOTYPE);
655     Symbol->setBinding(ELF::STB_LOCAL);
656   }
657 
658   void emitThumbFunc(MCSymbol *Func) override {
659     getAssembler().setIsThumbFunc(Func);
660     emitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
661   }
662 
663   // Helper functions for ARM exception handling directives
664   void EHReset();
665 
666   // Reset state between object emissions
667   void reset() override;
668 
669   void EmitPersonalityFixup(StringRef Name);
670   void FlushPendingOffset();
671   void FlushUnwindOpcodes(bool NoHandlerData);
672 
673   void SwitchToEHSection(StringRef Prefix, unsigned Type, unsigned Flags,
674                          SectionKind Kind, const MCSymbol &Fn);
675   void SwitchToExTabSection(const MCSymbol &FnStart);
676   void SwitchToExIdxSection(const MCSymbol &FnStart);
677 
678   void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
679 
680   bool IsThumb;
681   bool IsAndroid;
682   int64_t MappingSymbolCounter = 0;
683 
684   DenseMap<const MCSection *, std::unique_ptr<ElfMappingSymbolInfo>>
685       LastMappingSymbols;
686 
687   std::unique_ptr<ElfMappingSymbolInfo> LastEMSInfo;
688 
689   // ARM Exception Handling Frame Information
690   MCSymbol *ExTab;
691   MCSymbol *FnStart;
692   const MCSymbol *Personality;
693   unsigned PersonalityIndex;
694   unsigned FPReg; // Frame pointer register
695   int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
696   int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
697   int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
698   bool UsedFP;
699   bool CantUnwind;
700   SmallVector<uint8_t, 64> Opcodes;
701   UnwindOpcodeAssembler UnwindOpAsm;
702 };
703 
704 } // end anonymous namespace
705 
706 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
707   return static_cast<ARMELFStreamer &>(Streamer);
708 }
709 
710 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
711 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
712 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
713 
714 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
715   getStreamer().emitPersonality(Personality);
716 }
717 
718 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
719   getStreamer().emitPersonalityIndex(Index);
720 }
721 
722 void ARMTargetELFStreamer::emitHandlerData() {
723   getStreamer().emitHandlerData();
724 }
725 
726 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
727                                      int64_t Offset) {
728   getStreamer().emitSetFP(FpReg, SpReg, Offset);
729 }
730 
731 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
732   getStreamer().emitMovSP(Reg, Offset);
733 }
734 
735 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
736   getStreamer().emitPad(Offset);
737 }
738 
739 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
740                                        bool isVector) {
741   getStreamer().emitRegSave(RegList, isVector);
742 }
743 
744 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
745                                       const SmallVectorImpl<uint8_t> &Opcodes) {
746   getStreamer().emitUnwindRaw(Offset, Opcodes);
747 }
748 
749 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
750   assert(!Vendor.empty() && "Vendor cannot be empty.");
751 
752   if (CurrentVendor == Vendor)
753     return;
754 
755   if (!CurrentVendor.empty())
756     finishAttributeSection();
757 
758   assert(Contents.empty() &&
759          ".ARM.attributes should be flushed before changing vendor");
760   CurrentVendor = Vendor;
761 
762 }
763 
764 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
765   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
766 }
767 
768 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
769                                              StringRef Value) {
770   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
771 }
772 
773 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
774                                                 unsigned IntValue,
775                                                 StringRef StringValue) {
776   setAttributeItems(Attribute, IntValue, StringValue,
777                     /* OverwriteExisting= */ true);
778 }
779 
780 void ARMTargetELFStreamer::emitArch(ARM::ArchKind Value) {
781   Arch = Value;
782 }
783 
784 void ARMTargetELFStreamer::emitObjectArch(ARM::ArchKind Value) {
785   EmittedArch = Value;
786 }
787 
788 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
789   using namespace ARMBuildAttrs;
790 
791   setAttributeItem(CPU_name,
792                    ARM::getCPUAttr(Arch),
793                    false);
794 
795   if (EmittedArch == ARM::ArchKind::INVALID)
796     setAttributeItem(CPU_arch,
797                      ARM::getArchAttr(Arch),
798                      false);
799   else
800     setAttributeItem(CPU_arch,
801                      ARM::getArchAttr(EmittedArch),
802                      false);
803 
804   switch (Arch) {
805   case ARM::ArchKind::ARMV2:
806   case ARM::ArchKind::ARMV2A:
807   case ARM::ArchKind::ARMV3:
808   case ARM::ArchKind::ARMV3M:
809   case ARM::ArchKind::ARMV4:
810     setAttributeItem(ARM_ISA_use, Allowed, false);
811     break;
812 
813   case ARM::ArchKind::ARMV4T:
814   case ARM::ArchKind::ARMV5T:
815   case ARM::ArchKind::ARMV5TE:
816   case ARM::ArchKind::ARMV6:
817     setAttributeItem(ARM_ISA_use, Allowed, false);
818     setAttributeItem(THUMB_ISA_use, Allowed, false);
819     break;
820 
821   case ARM::ArchKind::ARMV6T2:
822     setAttributeItem(ARM_ISA_use, Allowed, false);
823     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
824     break;
825 
826   case ARM::ArchKind::ARMV6K:
827   case ARM::ArchKind::ARMV6KZ:
828     setAttributeItem(ARM_ISA_use, Allowed, false);
829     setAttributeItem(THUMB_ISA_use, Allowed, false);
830     setAttributeItem(Virtualization_use, AllowTZ, false);
831     break;
832 
833   case ARM::ArchKind::ARMV6M:
834     setAttributeItem(THUMB_ISA_use, Allowed, false);
835     break;
836 
837   case ARM::ArchKind::ARMV7A:
838     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
839     setAttributeItem(ARM_ISA_use, Allowed, false);
840     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
841     break;
842 
843   case ARM::ArchKind::ARMV7R:
844     setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
845     setAttributeItem(ARM_ISA_use, Allowed, false);
846     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
847     break;
848 
849   case ARM::ArchKind::ARMV7EM:
850   case ARM::ArchKind::ARMV7M:
851     setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
852     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
853     break;
854 
855   case ARM::ArchKind::ARMV8A:
856   case ARM::ArchKind::ARMV8_1A:
857   case ARM::ArchKind::ARMV8_2A:
858   case ARM::ArchKind::ARMV8_3A:
859   case ARM::ArchKind::ARMV8_4A:
860   case ARM::ArchKind::ARMV8_5A:
861   case ARM::ArchKind::ARMV8_6A:
862     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
863     setAttributeItem(ARM_ISA_use, Allowed, false);
864     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
865     setAttributeItem(MPextension_use, Allowed, false);
866     setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
867     break;
868 
869   case ARM::ArchKind::ARMV8MBaseline:
870   case ARM::ArchKind::ARMV8MMainline:
871     setAttributeItem(THUMB_ISA_use, AllowThumbDerived, false);
872     setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
873     break;
874 
875   case ARM::ArchKind::IWMMXT:
876     setAttributeItem(ARM_ISA_use, Allowed, false);
877     setAttributeItem(THUMB_ISA_use, Allowed, false);
878     setAttributeItem(WMMX_arch, AllowWMMXv1, false);
879     break;
880 
881   case ARM::ArchKind::IWMMXT2:
882     setAttributeItem(ARM_ISA_use, Allowed, false);
883     setAttributeItem(THUMB_ISA_use, Allowed, false);
884     setAttributeItem(WMMX_arch, AllowWMMXv2, false);
885     break;
886 
887   default:
888     report_fatal_error("Unknown Arch: " + Twine(ARM::getArchName(Arch)));
889     break;
890   }
891 }
892 
893 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
894   FPU = Value;
895 }
896 
897 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
898   switch (FPU) {
899   case ARM::FK_VFP:
900   case ARM::FK_VFPV2:
901     setAttributeItem(ARMBuildAttrs::FP_arch,
902                      ARMBuildAttrs::AllowFPv2,
903                      /* OverwriteExisting= */ false);
904     break;
905 
906   case ARM::FK_VFPV3:
907     setAttributeItem(ARMBuildAttrs::FP_arch,
908                      ARMBuildAttrs::AllowFPv3A,
909                      /* OverwriteExisting= */ false);
910     break;
911 
912   case ARM::FK_VFPV3_FP16:
913     setAttributeItem(ARMBuildAttrs::FP_arch,
914                      ARMBuildAttrs::AllowFPv3A,
915                      /* OverwriteExisting= */ false);
916     setAttributeItem(ARMBuildAttrs::FP_HP_extension,
917                      ARMBuildAttrs::AllowHPFP,
918                      /* OverwriteExisting= */ false);
919     break;
920 
921   case ARM::FK_VFPV3_D16:
922     setAttributeItem(ARMBuildAttrs::FP_arch,
923                      ARMBuildAttrs::AllowFPv3B,
924                      /* OverwriteExisting= */ false);
925     break;
926 
927   case ARM::FK_VFPV3_D16_FP16:
928     setAttributeItem(ARMBuildAttrs::FP_arch,
929                      ARMBuildAttrs::AllowFPv3B,
930                      /* OverwriteExisting= */ false);
931     setAttributeItem(ARMBuildAttrs::FP_HP_extension,
932                      ARMBuildAttrs::AllowHPFP,
933                      /* OverwriteExisting= */ false);
934     break;
935 
936   case ARM::FK_VFPV3XD:
937     setAttributeItem(ARMBuildAttrs::FP_arch,
938                      ARMBuildAttrs::AllowFPv3B,
939                      /* OverwriteExisting= */ false);
940     break;
941   case ARM::FK_VFPV3XD_FP16:
942     setAttributeItem(ARMBuildAttrs::FP_arch,
943                      ARMBuildAttrs::AllowFPv3B,
944                      /* OverwriteExisting= */ false);
945     setAttributeItem(ARMBuildAttrs::FP_HP_extension,
946                      ARMBuildAttrs::AllowHPFP,
947                      /* OverwriteExisting= */ false);
948     break;
949 
950   case ARM::FK_VFPV4:
951     setAttributeItem(ARMBuildAttrs::FP_arch,
952                      ARMBuildAttrs::AllowFPv4A,
953                      /* OverwriteExisting= */ false);
954     break;
955 
956   // ABI_HardFP_use is handled in ARMAsmPrinter, so _SP_D16 is treated the same
957   // as _D16 here.
958   case ARM::FK_FPV4_SP_D16:
959   case ARM::FK_VFPV4_D16:
960     setAttributeItem(ARMBuildAttrs::FP_arch,
961                      ARMBuildAttrs::AllowFPv4B,
962                      /* OverwriteExisting= */ false);
963     break;
964 
965   case ARM::FK_FP_ARMV8:
966     setAttributeItem(ARMBuildAttrs::FP_arch,
967                      ARMBuildAttrs::AllowFPARMv8A,
968                      /* OverwriteExisting= */ false);
969     break;
970 
971   // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
972   // uses the FP_ARMV8_D16 build attribute.
973   case ARM::FK_FPV5_SP_D16:
974   case ARM::FK_FPV5_D16:
975     setAttributeItem(ARMBuildAttrs::FP_arch,
976                      ARMBuildAttrs::AllowFPARMv8B,
977                      /* OverwriteExisting= */ false);
978     break;
979 
980   case ARM::FK_NEON:
981     setAttributeItem(ARMBuildAttrs::FP_arch,
982                      ARMBuildAttrs::AllowFPv3A,
983                      /* OverwriteExisting= */ false);
984     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
985                      ARMBuildAttrs::AllowNeon,
986                      /* OverwriteExisting= */ false);
987     break;
988 
989   case ARM::FK_NEON_FP16:
990     setAttributeItem(ARMBuildAttrs::FP_arch,
991                      ARMBuildAttrs::AllowFPv3A,
992                      /* OverwriteExisting= */ false);
993     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
994                      ARMBuildAttrs::AllowNeon,
995                      /* OverwriteExisting= */ false);
996     setAttributeItem(ARMBuildAttrs::FP_HP_extension,
997                      ARMBuildAttrs::AllowHPFP,
998                      /* OverwriteExisting= */ false);
999     break;
1000 
1001   case ARM::FK_NEON_VFPV4:
1002     setAttributeItem(ARMBuildAttrs::FP_arch,
1003                      ARMBuildAttrs::AllowFPv4A,
1004                      /* OverwriteExisting= */ false);
1005     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
1006                      ARMBuildAttrs::AllowNeon2,
1007                      /* OverwriteExisting= */ false);
1008     break;
1009 
1010   case ARM::FK_NEON_FP_ARMV8:
1011   case ARM::FK_CRYPTO_NEON_FP_ARMV8:
1012     setAttributeItem(ARMBuildAttrs::FP_arch,
1013                      ARMBuildAttrs::AllowFPARMv8A,
1014                      /* OverwriteExisting= */ false);
1015     // 'Advanced_SIMD_arch' must be emitted not here, but within
1016     // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
1017     break;
1018 
1019   case ARM::FK_SOFTVFP:
1020   case ARM::FK_NONE:
1021     break;
1022 
1023   default:
1024     report_fatal_error("Unknown FPU: " + Twine(FPU));
1025     break;
1026   }
1027 }
1028 
1029 size_t ARMTargetELFStreamer::calculateContentSize() const {
1030   size_t Result = 0;
1031   for (size_t i = 0; i < Contents.size(); ++i) {
1032     AttributeItem item = Contents[i];
1033     switch (item.Type) {
1034     case AttributeItem::HiddenAttribute:
1035       break;
1036     case AttributeItem::NumericAttribute:
1037       Result += getULEB128Size(item.Tag);
1038       Result += getULEB128Size(item.IntValue);
1039       break;
1040     case AttributeItem::TextAttribute:
1041       Result += getULEB128Size(item.Tag);
1042       Result += item.StringValue.size() + 1; // string + '\0'
1043       break;
1044     case AttributeItem::NumericAndTextAttributes:
1045       Result += getULEB128Size(item.Tag);
1046       Result += getULEB128Size(item.IntValue);
1047       Result += item.StringValue.size() + 1; // string + '\0';
1048       break;
1049     }
1050   }
1051   return Result;
1052 }
1053 
1054 void ARMTargetELFStreamer::finishAttributeSection() {
1055   // <format-version>
1056   // [ <section-length> "vendor-name"
1057   // [ <file-tag> <size> <attribute>*
1058   //   | <section-tag> <size> <section-number>* 0 <attribute>*
1059   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
1060   //   ]+
1061   // ]*
1062 
1063   if (FPU != ARM::FK_INVALID)
1064     emitFPUDefaultAttributes();
1065 
1066   if (Arch != ARM::ArchKind::INVALID)
1067     emitArchDefaultAttributes();
1068 
1069   if (Contents.empty())
1070     return;
1071 
1072   llvm::sort(Contents, AttributeItem::LessTag);
1073 
1074   ARMELFStreamer &Streamer = getStreamer();
1075 
1076   // Switch to .ARM.attributes section
1077   if (AttributeSection) {
1078     Streamer.SwitchSection(AttributeSection);
1079   } else {
1080     AttributeSection = Streamer.getContext().getELFSection(
1081         ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
1082     Streamer.SwitchSection(AttributeSection);
1083 
1084     // Format version
1085     Streamer.emitInt8(0x41);
1086   }
1087 
1088   // Vendor size + Vendor name + '\0'
1089   const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
1090 
1091   // Tag + Tag Size
1092   const size_t TagHeaderSize = 1 + 4;
1093 
1094   const size_t ContentsSize = calculateContentSize();
1095 
1096   Streamer.emitInt32(VendorHeaderSize + TagHeaderSize + ContentsSize);
1097   Streamer.emitBytes(CurrentVendor);
1098   Streamer.emitInt8(0); // '\0'
1099 
1100   Streamer.emitInt8(ARMBuildAttrs::File);
1101   Streamer.emitInt32(TagHeaderSize + ContentsSize);
1102 
1103   // Size should have been accounted for already, now
1104   // emit each field as its type (ULEB or String)
1105   for (size_t i = 0; i < Contents.size(); ++i) {
1106     AttributeItem item = Contents[i];
1107     Streamer.emitULEB128IntValue(item.Tag);
1108     switch (item.Type) {
1109     default: llvm_unreachable("Invalid attribute type");
1110     case AttributeItem::NumericAttribute:
1111       Streamer.emitULEB128IntValue(item.IntValue);
1112       break;
1113     case AttributeItem::TextAttribute:
1114       Streamer.emitBytes(item.StringValue);
1115       Streamer.emitInt8(0); // '\0'
1116       break;
1117     case AttributeItem::NumericAndTextAttributes:
1118       Streamer.emitULEB128IntValue(item.IntValue);
1119       Streamer.emitBytes(item.StringValue);
1120       Streamer.emitInt8(0); // '\0'
1121       break;
1122     }
1123   }
1124 
1125   Contents.clear();
1126   FPU = ARM::FK_INVALID;
1127 }
1128 
1129 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
1130   ARMELFStreamer &Streamer = getStreamer();
1131   if (!Streamer.IsThumb)
1132     return;
1133 
1134   Streamer.getAssembler().registerSymbol(*Symbol);
1135   unsigned Type = cast<MCSymbolELF>(Symbol)->getType();
1136   if (Type == ELF::STT_FUNC || Type == ELF::STT_GNU_IFUNC)
1137     Streamer.emitThumbFunc(Symbol);
1138 }
1139 
1140 void
1141 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
1142   getStreamer().EmitFixup(S, FK_Data_4);
1143 }
1144 
1145 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
1146   if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
1147     const MCSymbol &Sym = SRE->getSymbol();
1148     if (!Sym.isDefined()) {
1149       getStreamer().emitAssignment(Symbol, Value);
1150       return;
1151     }
1152   }
1153 
1154   getStreamer().emitThumbFunc(Symbol);
1155   getStreamer().emitAssignment(Symbol, Value);
1156 }
1157 
1158 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1159   getStreamer().emitInst(Inst, Suffix);
1160 }
1161 
1162 void ARMTargetELFStreamer::reset() { AttributeSection = nullptr; }
1163 
1164 void ARMELFStreamer::finishImpl() {
1165   MCTargetStreamer &TS = *getTargetStreamer();
1166   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1167   ATS.finishAttributeSection();
1168 
1169   MCELFStreamer::finishImpl();
1170 }
1171 
1172 void ARMELFStreamer::reset() {
1173   MCTargetStreamer &TS = *getTargetStreamer();
1174   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1175   ATS.reset();
1176   MappingSymbolCounter = 0;
1177   MCELFStreamer::reset();
1178   LastMappingSymbols.clear();
1179   LastEMSInfo.reset();
1180   // MCELFStreamer clear's the assembler's e_flags. However, for
1181   // arm we manually set the ABI version on streamer creation, so
1182   // do the same here
1183   getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1184 }
1185 
1186 inline void ARMELFStreamer::SwitchToEHSection(StringRef Prefix,
1187                                               unsigned Type,
1188                                               unsigned Flags,
1189                                               SectionKind Kind,
1190                                               const MCSymbol &Fn) {
1191   const MCSectionELF &FnSection =
1192     static_cast<const MCSectionELF &>(Fn.getSection());
1193 
1194   // Create the name for new section
1195   StringRef FnSecName(FnSection.getName());
1196   SmallString<128> EHSecName(Prefix);
1197   if (FnSecName != ".text") {
1198     EHSecName += FnSecName;
1199   }
1200 
1201   // Get .ARM.extab or .ARM.exidx section
1202   const MCSymbolELF *Group = FnSection.getGroup();
1203   if (Group)
1204     Flags |= ELF::SHF_GROUP;
1205   MCSectionELF *EHSection = getContext().getELFSection(
1206       EHSecName, Type, Flags, 0, Group, FnSection.getUniqueID(),
1207       static_cast<const MCSymbolELF *>(FnSection.getBeginSymbol()));
1208 
1209   assert(EHSection && "Failed to get the required EH section");
1210 
1211   // Switch to .ARM.extab or .ARM.exidx section
1212   SwitchSection(EHSection);
1213   emitCodeAlignment(4);
1214 }
1215 
1216 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1217   SwitchToEHSection(".ARM.extab", ELF::SHT_PROGBITS, ELF::SHF_ALLOC,
1218                     SectionKind::getData(), FnStart);
1219 }
1220 
1221 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1222   SwitchToEHSection(".ARM.exidx", ELF::SHT_ARM_EXIDX,
1223                     ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1224                     SectionKind::getData(), FnStart);
1225 }
1226 
1227 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1228   MCDataFragment *Frag = getOrCreateDataFragment();
1229   Frag->getFixups().push_back(MCFixup::create(Frag->getContents().size(), Expr,
1230                                               Kind));
1231 }
1232 
1233 void ARMELFStreamer::EHReset() {
1234   ExTab = nullptr;
1235   FnStart = nullptr;
1236   Personality = nullptr;
1237   PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1238   FPReg = ARM::SP;
1239   FPOffset = 0;
1240   SPOffset = 0;
1241   PendingOffset = 0;
1242   UsedFP = false;
1243   CantUnwind = false;
1244 
1245   Opcodes.clear();
1246   UnwindOpAsm.Reset();
1247 }
1248 
1249 void ARMELFStreamer::emitFnStart() {
1250   assert(FnStart == nullptr);
1251   FnStart = getContext().createTempSymbol();
1252   emitLabel(FnStart);
1253 }
1254 
1255 void ARMELFStreamer::emitFnEnd() {
1256   assert(FnStart && ".fnstart must precedes .fnend");
1257 
1258   // Emit unwind opcodes if there is no .handlerdata directive
1259   if (!ExTab && !CantUnwind)
1260     FlushUnwindOpcodes(true);
1261 
1262   // Emit the exception index table entry
1263   SwitchToExIdxSection(*FnStart);
1264 
1265   // The EHABI requires a dependency preserving R_ARM_NONE relocation to the
1266   // personality routine to protect it from an arbitrary platform's static
1267   // linker garbage collection. We disable this for Android where the unwinder
1268   // is either dynamically linked or directly references the personality
1269   // routine.
1270   if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX && !IsAndroid)
1271     EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1272 
1273   const MCSymbolRefExpr *FnStartRef =
1274     MCSymbolRefExpr::create(FnStart,
1275                             MCSymbolRefExpr::VK_ARM_PREL31,
1276                             getContext());
1277 
1278   emitValue(FnStartRef, 4);
1279 
1280   if (CantUnwind) {
1281     emitInt32(ARM::EHABI::EXIDX_CANTUNWIND);
1282   } else if (ExTab) {
1283     // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1284     const MCSymbolRefExpr *ExTabEntryRef =
1285       MCSymbolRefExpr::create(ExTab,
1286                               MCSymbolRefExpr::VK_ARM_PREL31,
1287                               getContext());
1288     emitValue(ExTabEntryRef, 4);
1289   } else {
1290     // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1291     // the second word of exception index table entry.  The size of the unwind
1292     // opcodes should always be 4 bytes.
1293     assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1294            "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1295     assert(Opcodes.size() == 4u &&
1296            "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1297     uint64_t Intval = Opcodes[0] |
1298                       Opcodes[1] << 8 |
1299                       Opcodes[2] << 16 |
1300                       Opcodes[3] << 24;
1301     emitIntValue(Intval, Opcodes.size());
1302   }
1303 
1304   // Switch to the section containing FnStart
1305   SwitchSection(&FnStart->getSection());
1306 
1307   // Clean exception handling frame information
1308   EHReset();
1309 }
1310 
1311 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1312 
1313 // Add the R_ARM_NONE fixup at the same position
1314 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1315   const MCSymbol *PersonalitySym = getContext().getOrCreateSymbol(Name);
1316 
1317   const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::create(
1318       PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1319 
1320   visitUsedExpr(*PersonalityRef);
1321   MCDataFragment *DF = getOrCreateDataFragment();
1322   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
1323                                             PersonalityRef,
1324                                             MCFixup::getKindForSize(4, false)));
1325 }
1326 
1327 void ARMELFStreamer::FlushPendingOffset() {
1328   if (PendingOffset != 0) {
1329     UnwindOpAsm.EmitSPOffset(-PendingOffset);
1330     PendingOffset = 0;
1331   }
1332 }
1333 
1334 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1335   // Emit the unwind opcode to restore $sp.
1336   if (UsedFP) {
1337     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1338     int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1339     UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1340     UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1341   } else {
1342     FlushPendingOffset();
1343   }
1344 
1345   // Finalize the unwind opcode sequence
1346   UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1347 
1348   // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1349   // section.  Thus, we don't have to create an entry in the .ARM.extab
1350   // section.
1351   if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1352     return;
1353 
1354   // Switch to .ARM.extab section.
1355   SwitchToExTabSection(*FnStart);
1356 
1357   // Create .ARM.extab label for offset in .ARM.exidx
1358   assert(!ExTab);
1359   ExTab = getContext().createTempSymbol();
1360   emitLabel(ExTab);
1361 
1362   // Emit personality
1363   if (Personality) {
1364     const MCSymbolRefExpr *PersonalityRef =
1365       MCSymbolRefExpr::create(Personality,
1366                               MCSymbolRefExpr::VK_ARM_PREL31,
1367                               getContext());
1368 
1369     emitValue(PersonalityRef, 4);
1370   }
1371 
1372   // Emit unwind opcodes
1373   assert((Opcodes.size() % 4) == 0 &&
1374          "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1375   for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1376     uint64_t Intval = Opcodes[I] |
1377                       Opcodes[I + 1] << 8 |
1378                       Opcodes[I + 2] << 16 |
1379                       Opcodes[I + 3] << 24;
1380     emitInt32(Intval);
1381   }
1382 
1383   // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1384   // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1385   // after the unwind opcodes.  The handler data consists of several 32-bit
1386   // words, and should be terminated by zero.
1387   //
1388   // In case that the .handlerdata directive is not specified by the
1389   // programmer, we should emit zero to terminate the handler data.
1390   if (NoHandlerData && !Personality)
1391     emitInt32(0);
1392 }
1393 
1394 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1395 
1396 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1397   Personality = Per;
1398   UnwindOpAsm.setPersonality(Per);
1399 }
1400 
1401 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1402   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1403   PersonalityIndex = Index;
1404 }
1405 
1406 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1407                                int64_t Offset) {
1408   assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1409          "the operand of .setfp directive should be either $sp or $fp");
1410 
1411   UsedFP = true;
1412   FPReg = NewFPReg;
1413 
1414   if (NewSPReg == ARM::SP)
1415     FPOffset = SPOffset + Offset;
1416   else
1417     FPOffset += Offset;
1418 }
1419 
1420 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1421   assert((Reg != ARM::SP && Reg != ARM::PC) &&
1422          "the operand of .movsp cannot be either sp or pc");
1423   assert(FPReg == ARM::SP && "current FP must be SP");
1424 
1425   FlushPendingOffset();
1426 
1427   FPReg = Reg;
1428   FPOffset = SPOffset + Offset;
1429 
1430   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1431   UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1432 }
1433 
1434 void ARMELFStreamer::emitPad(int64_t Offset) {
1435   // Track the change of the $sp offset
1436   SPOffset -= Offset;
1437 
1438   // To squash multiple .pad directives, we should delay the unwind opcode
1439   // until the .save, .vsave, .handlerdata, or .fnend directives.
1440   PendingOffset -= Offset;
1441 }
1442 
1443 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1444                                  bool IsVector) {
1445   // Collect the registers in the register list
1446   unsigned Count = 0;
1447   uint32_t Mask = 0;
1448   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1449   for (size_t i = 0; i < RegList.size(); ++i) {
1450     unsigned Reg = MRI->getEncodingValue(RegList[i]);
1451     assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1452     unsigned Bit = (1u << Reg);
1453     if ((Mask & Bit) == 0) {
1454       Mask |= Bit;
1455       ++Count;
1456     }
1457   }
1458 
1459   // Track the change the $sp offset: For the .save directive, the
1460   // corresponding push instruction will decrease the $sp by (4 * Count).
1461   // For the .vsave directive, the corresponding vpush instruction will
1462   // decrease $sp by (8 * Count).
1463   SPOffset -= Count * (IsVector ? 8 : 4);
1464 
1465   // Emit the opcode
1466   FlushPendingOffset();
1467   if (IsVector)
1468     UnwindOpAsm.EmitVFPRegSave(Mask);
1469   else
1470     UnwindOpAsm.EmitRegSave(Mask);
1471 }
1472 
1473 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1474                                    const SmallVectorImpl<uint8_t> &Opcodes) {
1475   FlushPendingOffset();
1476   SPOffset = SPOffset - Offset;
1477   UnwindOpAsm.EmitRaw(Opcodes);
1478 }
1479 
1480 namespace llvm {
1481 
1482 MCTargetStreamer *createARMTargetAsmStreamer(MCStreamer &S,
1483                                              formatted_raw_ostream &OS,
1484                                              MCInstPrinter *InstPrint,
1485                                              bool isVerboseAsm) {
1486   return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1487 }
1488 
1489 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1490   return new ARMTargetStreamer(S);
1491 }
1492 
1493 MCTargetStreamer *createARMObjectTargetStreamer(MCStreamer &S,
1494                                                 const MCSubtargetInfo &STI) {
1495   const Triple &TT = STI.getTargetTriple();
1496   if (TT.isOSBinFormatELF())
1497     return new ARMTargetELFStreamer(S);
1498   return new ARMTargetStreamer(S);
1499 }
1500 
1501 MCELFStreamer *createARMELFStreamer(MCContext &Context,
1502                                     std::unique_ptr<MCAsmBackend> TAB,
1503                                     std::unique_ptr<MCObjectWriter> OW,
1504                                     std::unique_ptr<MCCodeEmitter> Emitter,
1505                                     bool RelaxAll, bool IsThumb,
1506                                     bool IsAndroid) {
1507   ARMELFStreamer *S =
1508       new ARMELFStreamer(Context, std::move(TAB), std::move(OW),
1509                          std::move(Emitter), IsThumb, IsAndroid);
1510   // FIXME: This should eventually end up somewhere else where more
1511   // intelligent flag decisions can be made. For now we are just maintaining
1512   // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1513   S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1514 
1515   if (RelaxAll)
1516     S->getAssembler().setRelaxAll(true);
1517   return S;
1518 }
1519 
1520 } // end namespace llvm
1521