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