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