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