]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/MC/MCELFStreamer.cpp
Vendor import of llvm trunk r178860:
[FreeBSD/FreeBSD.git] / lib / MC / MCELFStreamer.cpp
1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
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 ELF .o object files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/MC/MCELFStreamer.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCELF.h"
20 #include "llvm/MC/MCELFSymbolFlags.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCObjectStreamer.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32
33 using namespace llvm;
34
35
36 inline void MCELFStreamer::SetSection(StringRef Section, unsigned Type,
37                                       unsigned Flags, SectionKind Kind) {
38   SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
39 }
40
41 inline void MCELFStreamer::SetSectionData() {
42   SetSection(".data",
43              ELF::SHT_PROGBITS,
44              ELF::SHF_WRITE | ELF::SHF_ALLOC,
45              SectionKind::getDataRel());
46   EmitCodeAlignment(4, 0);
47 }
48
49 inline void MCELFStreamer::SetSectionText() {
50   SetSection(".text",
51              ELF::SHT_PROGBITS,
52              ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
53              SectionKind::getText());
54   EmitCodeAlignment(4, 0);
55 }
56
57 inline void MCELFStreamer::SetSectionBss() {
58   SetSection(".bss",
59              ELF::SHT_NOBITS,
60              ELF::SHF_WRITE | ELF::SHF_ALLOC,
61              SectionKind::getBSS());
62   EmitCodeAlignment(4, 0);
63 }
64
65 MCELFStreamer::~MCELFStreamer() {
66 }
67
68 void MCELFStreamer::InitToTextSection() {
69   SetSectionText();
70 }
71
72 void MCELFStreamer::InitSections() {
73   // This emulates the same behavior of GNU as. This makes it easier
74   // to compare the output as the major sections are in the same order.
75   SetSectionText();
76   SetSectionData();
77   SetSectionBss();
78   SetSectionText();
79 }
80
81 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
82   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
83
84   MCObjectStreamer::EmitLabel(Symbol);
85
86   const MCSectionELF &Section =
87     static_cast<const MCSectionELF&>(Symbol->getSection());
88   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
89   if (Section.getFlags() & ELF::SHF_TLS)
90     MCELF::SetType(SD, ELF::STT_TLS);
91 }
92
93 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
94   EmitLabel(Symbol);
95 }
96
97 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
98   switch (Flag) {
99   case MCAF_SyntaxUnified: return; // no-op here.
100   case MCAF_Code16: return; // Change parsing mode; no-op here.
101   case MCAF_Code32: return; // Change parsing mode; no-op here.
102   case MCAF_Code64: return; // Change parsing mode; no-op here.
103   case MCAF_SubsectionsViaSymbols:
104     getAssembler().setSubsectionsViaSymbols(true);
105     return;
106   }
107
108   llvm_unreachable("invalid assembler flag!");
109 }
110
111 void MCELFStreamer::ChangeSection(const MCSection *Section) {
112   MCSectionData *CurSection = getCurrentSectionData();
113   if (CurSection && CurSection->isBundleLocked())
114     report_fatal_error("Unterminated .bundle_lock when changing a section");
115   const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
116   if (Grp)
117     getAssembler().getOrCreateSymbolData(*Grp);
118   this->MCObjectStreamer::ChangeSection(Section);
119 }
120
121 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
122   getAssembler().getOrCreateSymbolData(*Symbol);
123   MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
124   AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
125   const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
126   Alias->setVariableValue(Value);
127 }
128
129 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
130                                           MCSymbolAttr Attribute) {
131   // Indirect symbols are handled differently, to match how 'as' handles
132   // them. This makes writing matching .o files easier.
133   if (Attribute == MCSA_IndirectSymbol) {
134     // Note that we intentionally cannot use the symbol data here; this is
135     // important for matching the string table that 'as' generates.
136     IndirectSymbolData ISD;
137     ISD.Symbol = Symbol;
138     ISD.SectionData = getCurrentSectionData();
139     getAssembler().getIndirectSymbols().push_back(ISD);
140     return;
141   }
142
143   // Adding a symbol attribute always introduces the symbol, note that an
144   // important side effect of calling getOrCreateSymbolData here is to register
145   // the symbol with the assembler.
146   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
147
148   // The implementation of symbol attributes is designed to match 'as', but it
149   // leaves much to desired. It doesn't really make sense to arbitrarily add and
150   // remove flags, but 'as' allows this (in particular, see .desc).
151   //
152   // In the future it might be worth trying to make these operations more well
153   // defined.
154   switch (Attribute) {
155   case MCSA_LazyReference:
156   case MCSA_Reference:
157   case MCSA_SymbolResolver:
158   case MCSA_PrivateExtern:
159   case MCSA_WeakDefinition:
160   case MCSA_WeakDefAutoPrivate:
161   case MCSA_Invalid:
162   case MCSA_IndirectSymbol:
163     llvm_unreachable("Invalid symbol attribute for ELF!");
164
165   case MCSA_NoDeadStrip:
166   case MCSA_ELF_TypeGnuUniqueObject:
167     // Ignore for now.
168     break;
169
170   case MCSA_Global:
171     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
172     SD.setExternal(true);
173     BindingExplicitlySet.insert(Symbol);
174     break;
175
176   case MCSA_WeakReference:
177   case MCSA_Weak:
178     MCELF::SetBinding(SD, ELF::STB_WEAK);
179     SD.setExternal(true);
180     BindingExplicitlySet.insert(Symbol);
181     break;
182
183   case MCSA_Local:
184     MCELF::SetBinding(SD, ELF::STB_LOCAL);
185     SD.setExternal(false);
186     BindingExplicitlySet.insert(Symbol);
187     break;
188
189   case MCSA_ELF_TypeFunction:
190     MCELF::SetType(SD, ELF::STT_FUNC);
191     break;
192
193   case MCSA_ELF_TypeIndFunction:
194     MCELF::SetType(SD, ELF::STT_GNU_IFUNC);
195     break;
196
197   case MCSA_ELF_TypeObject:
198     MCELF::SetType(SD, ELF::STT_OBJECT);
199     break;
200
201   case MCSA_ELF_TypeTLS:
202     MCELF::SetType(SD, ELF::STT_TLS);
203     break;
204
205   case MCSA_ELF_TypeCommon:
206     MCELF::SetType(SD, ELF::STT_COMMON);
207     break;
208
209   case MCSA_ELF_TypeNoType:
210     MCELF::SetType(SD, ELF::STT_NOTYPE);
211     break;
212
213   case MCSA_Protected:
214     MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
215     break;
216
217   case MCSA_Hidden:
218     MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
219     break;
220
221   case MCSA_Internal:
222     MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
223     break;
224   }
225 }
226
227 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
228                                        unsigned ByteAlignment) {
229   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
230
231   if (!BindingExplicitlySet.count(Symbol)) {
232     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
233     SD.setExternal(true);
234   }
235
236   MCELF::SetType(SD, ELF::STT_OBJECT);
237
238   if (MCELF::GetBinding(SD) == ELF_STB_Local) {
239     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
240                                                          ELF::SHT_NOBITS,
241                                                          ELF::SHF_WRITE |
242                                                          ELF::SHF_ALLOC,
243                                                          SectionKind::getBSS());
244     Symbol->setSection(*Section);
245
246     struct LocalCommon L = {&SD, Size, ByteAlignment};
247     LocalCommons.push_back(L);
248   } else {
249     SD.setCommon(Size, ByteAlignment);
250   }
251
252   SD.setSize(MCConstantExpr::Create(Size, getContext()));
253 }
254
255 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
256   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
257   SD.setSize(Value);
258 }
259
260 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
261                                           unsigned ByteAlignment) {
262   // FIXME: Should this be caught and done earlier?
263   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
264   MCELF::SetBinding(SD, ELF::STB_LOCAL);
265   SD.setExternal(false);
266   BindingExplicitlySet.insert(Symbol);
267   EmitCommonSymbol(Symbol, Size, ByteAlignment);
268 }
269
270 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
271                                   unsigned AddrSpace) {
272   if (getCurrentSectionData()->isBundleLocked())
273     report_fatal_error("Emitting values inside a locked bundle is forbidden");
274   fixSymbolsInTLSFixups(Value);
275   MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
276 }
277
278 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
279                                          int64_t Value,
280                                          unsigned ValueSize,
281                                          unsigned MaxBytesToEmit) {
282   if (getCurrentSectionData()->isBundleLocked())
283     report_fatal_error("Emitting values inside a locked bundle is forbidden");
284   MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
285                                          ValueSize, MaxBytesToEmit);
286 }
287
288
289 // Add a symbol for the file name of this module. This is the second
290 // entry in the module's symbol table (the first being the null symbol).
291 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
292   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
293   Symbol->setSection(*getCurrentSection());
294   Symbol->setAbsolute();
295
296   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
297
298   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
299 }
300
301 void  MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
302   switch (expr->getKind()) {
303   case MCExpr::Target:
304     cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
305     break;
306   case MCExpr::Constant:
307     break;
308
309   case MCExpr::Binary: {
310     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
311     fixSymbolsInTLSFixups(be->getLHS());
312     fixSymbolsInTLSFixups(be->getRHS());
313     break;
314   }
315
316   case MCExpr::SymbolRef: {
317     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
318     switch (symRef.getKind()) {
319     default:
320       return;
321     case MCSymbolRefExpr::VK_GOTTPOFF:
322     case MCSymbolRefExpr::VK_INDNTPOFF:
323     case MCSymbolRefExpr::VK_NTPOFF:
324     case MCSymbolRefExpr::VK_GOTNTPOFF:
325     case MCSymbolRefExpr::VK_TLSGD:
326     case MCSymbolRefExpr::VK_TLSLD:
327     case MCSymbolRefExpr::VK_TLSLDM:
328     case MCSymbolRefExpr::VK_TPOFF:
329     case MCSymbolRefExpr::VK_DTPOFF:
330     case MCSymbolRefExpr::VK_ARM_TLSGD:
331     case MCSymbolRefExpr::VK_ARM_TPOFF:
332     case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
333     case MCSymbolRefExpr::VK_Mips_TLSGD:
334     case MCSymbolRefExpr::VK_Mips_GOTTPREL:
335     case MCSymbolRefExpr::VK_Mips_TPREL_HI:
336     case MCSymbolRefExpr::VK_Mips_TPREL_LO:
337     case MCSymbolRefExpr::VK_PPC_TPREL16_HA:
338     case MCSymbolRefExpr::VK_PPC_TPREL16_LO:
339     case MCSymbolRefExpr::VK_PPC_DTPREL16_HA:
340     case MCSymbolRefExpr::VK_PPC_DTPREL16_LO:
341     case MCSymbolRefExpr::VK_PPC_GOT_TPREL16_HA:
342     case MCSymbolRefExpr::VK_PPC_GOT_TPREL16_LO:
343     case MCSymbolRefExpr::VK_PPC_TLS:
344     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD16_HA:
345     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD16_LO:
346     case MCSymbolRefExpr::VK_PPC_TLSGD:
347     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD16_HA:
348     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD16_LO:
349     case MCSymbolRefExpr::VK_PPC_TLSLD:
350       break;
351     }
352     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
353     MCELF::SetType(SD, ELF::STT_TLS);
354     break;
355   }
356
357   case MCExpr::Unary:
358     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
359     break;
360   }
361 }
362
363 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
364   this->MCObjectStreamer::EmitInstToFragment(Inst);
365   MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
366
367   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
368     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
369 }
370
371 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
372   MCAssembler &Assembler = getAssembler();
373   SmallVector<MCFixup, 4> Fixups;
374   SmallString<256> Code;
375   raw_svector_ostream VecOS(Code);
376   Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
377   VecOS.flush();
378
379   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
380     fixSymbolsInTLSFixups(Fixups[i].getValue());
381
382   // There are several possibilities here:
383   //
384   // If bundling is disabled, append the encoded instruction to the current data
385   // fragment (or create a new such fragment if the current fragment is not a
386   // data fragment).
387   //
388   // If bundling is enabled:
389   // - If we're not in a bundle-locked group, emit the instruction into a
390   //   fragment of its own. If there are no fixups registered for the
391   //   instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
392   //   MCDataFragment.
393   // - If we're in a bundle-locked group, append the instruction to the current
394   //   data fragment because we want all the instructions in a group to get into
395   //   the same fragment. Be careful not to do that for the first instruction in
396   //   the group, though.
397   MCDataFragment *DF;
398
399   if (Assembler.isBundlingEnabled()) {
400     MCSectionData *SD = getCurrentSectionData();
401     if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
402       // If we are bundle-locked, we re-use the current fragment.
403       // The bundle-locking directive ensures this is a new data fragment.
404       DF = cast<MCDataFragment>(getCurrentFragment());
405     else if (!SD->isBundleLocked() && Fixups.size() == 0) {
406       // Optimize memory usage by emitting the instruction to a
407       // MCCompactEncodedInstFragment when not in a bundle-locked group and
408       // there are no fixups registered.
409       MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment(SD);
410       CEIF->getContents().append(Code.begin(), Code.end());
411       return;
412     } else {
413       DF = new MCDataFragment(SD);
414       if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
415         // If this is a new fragment created for a bundle-locked group, and the
416         // group was marked as "align_to_end", set a flag in the fragment.
417         DF->setAlignToBundleEnd(true);
418       }
419     }
420
421     // We're now emitting an instruction in a bundle group, so this flag has
422     // to be turned off.
423     SD->setBundleGroupBeforeFirstInst(false);
424   } else {
425     DF = getOrCreateDataFragment();
426   }
427
428   // Add the fixups and data.
429   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
430     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
431     DF->getFixups().push_back(Fixups[i]);
432   }
433   DF->setHasInstructions(true);
434   DF->getContents().append(Code.begin(), Code.end());
435 }
436
437 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
438   assert(AlignPow2 <= 30 && "Invalid bundle alignment");
439   MCAssembler &Assembler = getAssembler();
440   if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
441     Assembler.setBundleAlignSize(1 << AlignPow2);
442   else
443     report_fatal_error(".bundle_align_mode should be only set once per file");
444 }
445
446 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
447   MCSectionData *SD = getCurrentSectionData();
448
449   // Sanity checks
450   //
451   if (!getAssembler().isBundlingEnabled())
452     report_fatal_error(".bundle_lock forbidden when bundling is disabled");
453   else if (SD->isBundleLocked())
454     report_fatal_error("Nesting of .bundle_lock is forbidden");
455
456   SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
457                                       MCSectionData::BundleLocked);
458   SD->setBundleGroupBeforeFirstInst(true);
459 }
460
461 void MCELFStreamer::EmitBundleUnlock() {
462   MCSectionData *SD = getCurrentSectionData();
463
464   // Sanity checks
465   if (!getAssembler().isBundlingEnabled())
466     report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
467   else if (!SD->isBundleLocked())
468     report_fatal_error(".bundle_unlock without matching lock");
469   else if (SD->isBundleGroupBeforeFirstInst())
470     report_fatal_error("Empty bundle-locked group is forbidden");
471
472   SD->setBundleLockState(MCSectionData::NotBundleLocked);
473 }
474
475 void MCELFStreamer::FinishImpl() {
476   EmitFrames(true);
477
478   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
479                                                 e = LocalCommons.end();
480        i != e; ++i) {
481     MCSymbolData *SD = i->SD;
482     uint64_t Size = i->Size;
483     unsigned ByteAlignment = i->ByteAlignment;
484     const MCSymbol &Symbol = SD->getSymbol();
485     const MCSection &Section = Symbol.getSection();
486
487     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
488     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
489
490     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
491     SD->setFragment(F);
492
493     // Update the maximum alignment of the section if necessary.
494     if (ByteAlignment > SectData.getAlignment())
495       SectData.setAlignment(ByteAlignment);
496   }
497
498   this->MCObjectStreamer::FinishImpl();
499 }
500 void MCELFStreamer::EmitTCEntry(const MCSymbol &S) {
501   // Creates a R_PPC64_TOC relocation
502   MCObjectStreamer::EmitSymbolValue(&S, 8);
503 }
504
505 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
506                                     raw_ostream &OS, MCCodeEmitter *CE,
507                                     bool RelaxAll, bool NoExecStack) {
508   MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
509   if (RelaxAll)
510     S->getAssembler().setRelaxAll(true);
511   if (NoExecStack)
512     S->getAssembler().setNoExecStack(true);
513   return S;
514 }
515
516 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
517   llvm_unreachable("Generic ELF doesn't support this directive");
518 }
519
520 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(MCSymbol *Symbol) {
521   return getAssembler().getOrCreateSymbolData(*Symbol);
522 }
523
524 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
525   llvm_unreachable("ELF doesn't support this directive");
526 }
527
528 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
529   llvm_unreachable("ELF doesn't support this directive");
530 }
531
532 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
533   llvm_unreachable("ELF doesn't support this directive");
534 }
535
536 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
537   llvm_unreachable("ELF doesn't support this directive");
538 }
539
540 void MCELFStreamer::EndCOFFSymbolDef() {
541   llvm_unreachable("ELF doesn't support this directive");
542 }
543
544 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
545                                  uint64_t Size, unsigned ByteAlignment) {
546   llvm_unreachable("ELF doesn't support this directive");
547 }
548
549 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
550                                    uint64_t Size, unsigned ByteAlignment) {
551   llvm_unreachable("ELF doesn't support this directive");
552 }