Pass a MCSection to getCurrentSectionData.
[oota-llvm.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/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmLayout.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCCodeEmitter.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELF.h"
24 #include "llvm/MC/MCELFSymbolFlags.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCObjectFileInfo.h"
28 #include "llvm/MC/MCObjectStreamer.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 using namespace llvm;
40
41 bool MCELFStreamer::isBundleLocked() const {
42   return getCurrentSectionData()->getSection().isBundleLocked();
43 }
44
45 MCELFStreamer::~MCELFStreamer() {
46 }
47
48 void MCELFStreamer::mergeFragment(MCDataFragment *DF,
49                                   MCEncodedFragmentWithFixups *EF) {
50   MCAssembler &Assembler = getAssembler();
51
52   if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
53     uint64_t FSize = EF->getContents().size();
54
55     if (FSize > Assembler.getBundleAlignSize())
56       report_fatal_error("Fragment can't be larger than a bundle size");
57
58     uint64_t RequiredBundlePadding = computeBundlePadding(
59         Assembler, EF, DF->getContents().size(), FSize);
60
61     if (RequiredBundlePadding > UINT8_MAX)
62       report_fatal_error("Padding cannot exceed 255 bytes");
63
64     if (RequiredBundlePadding > 0) {
65       SmallString<256> Code;
66       raw_svector_ostream VecOS(Code);
67       MCObjectWriter *OW = Assembler.getBackend().createObjectWriter(VecOS);
68
69       EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
70
71       Assembler.writeFragmentPadding(*EF, FSize, OW);
72       VecOS.flush();
73       delete OW;
74
75       DF->getContents().append(Code.begin(), Code.end());
76     }
77   }
78
79   flushPendingLabels(DF, DF->getContents().size());
80
81   for (unsigned i = 0, e = EF->getFixups().size(); i != e; ++i) {
82     EF->getFixups()[i].setOffset(EF->getFixups()[i].getOffset() +
83                                  DF->getContents().size());
84     DF->getFixups().push_back(EF->getFixups()[i]);
85   }
86   DF->setHasInstructions(true);
87   DF->getContents().append(EF->getContents().begin(), EF->getContents().end());
88 }
89
90 void MCELFStreamer::InitSections(bool NoExecStack) {
91   // This emulates the same behavior of GNU as. This makes it easier
92   // to compare the output as the major sections are in the same order.
93   MCContext &Ctx = getContext();
94   SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
95   EmitCodeAlignment(4);
96
97   SwitchSection(Ctx.getObjectFileInfo()->getDataSection());
98   EmitCodeAlignment(4);
99
100   SwitchSection(Ctx.getObjectFileInfo()->getBSSSection());
101   EmitCodeAlignment(4);
102
103   SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
104
105   if (NoExecStack)
106     SwitchSection(Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx));
107 }
108
109 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
110   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
111
112   MCObjectStreamer::EmitLabel(Symbol);
113
114   const MCSectionELF &Section =
115     static_cast<const MCSectionELF&>(Symbol->getSection());
116   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
117   if (Section.getFlags() & ELF::SHF_TLS)
118     MCELF::SetType(SD, ELF::STT_TLS);
119 }
120
121 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
122   // Let the target do whatever target specific stuff it needs to do.
123   getAssembler().getBackend().handleAssemblerFlag(Flag);
124   // Do any generic stuff we need to do.
125   switch (Flag) {
126   case MCAF_SyntaxUnified: return; // no-op here.
127   case MCAF_Code16: return; // Change parsing mode; no-op here.
128   case MCAF_Code32: return; // Change parsing mode; no-op here.
129   case MCAF_Code64: return; // Change parsing mode; no-op here.
130   case MCAF_SubsectionsViaSymbols:
131     getAssembler().setSubsectionsViaSymbols(true);
132     return;
133   }
134
135   llvm_unreachable("invalid assembler flag!");
136 }
137
138 // If bundle aligment is used and there are any instructions in the section, it
139 // needs to be aligned to at least the bundle size.
140 static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
141                                            MCSection *Section) {
142   if (Section && Assembler.isBundlingEnabled() && Section->hasInstructions() &&
143       Section->getAlignment() < Assembler.getBundleAlignSize())
144     Section->setAlignment(Assembler.getBundleAlignSize());
145 }
146
147 void MCELFStreamer::ChangeSection(MCSection *Section,
148                                   const MCExpr *Subsection) {
149   MCSectionData *CurSectionData = getCurrentSectionData();
150   MCSection *CurSection =
151       CurSectionData ? &CurSectionData->getSection() : nullptr;
152   if (CurSection && isBundleLocked())
153     report_fatal_error("Unterminated .bundle_lock when changing a section");
154
155   MCAssembler &Asm = getAssembler();
156   // Ensure the previous section gets aligned if necessary.
157   setSectionAlignmentForBundling(Asm, CurSection);
158   auto *SectionELF = static_cast<const MCSectionELF *>(Section);
159   const MCSymbol *Grp = SectionELF->getGroup();
160   if (Grp)
161     Asm.getOrCreateSymbolData(*Grp);
162
163   this->MCObjectStreamer::ChangeSection(Section, Subsection);
164   MCSymbol *SectionSymbol = getContext().getOrCreateSectionSymbol(*SectionELF);
165   if (SectionSymbol->isUndefined()) {
166     EmitLabel(SectionSymbol);
167     MCELF::SetType(Asm.getSymbolData(*SectionSymbol), ELF::STT_SECTION);
168   }
169 }
170
171 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
172   getAssembler().getOrCreateSymbolData(*Symbol);
173   const MCExpr *Value = MCSymbolRefExpr::Create(
174       Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
175   Alias->setVariableValue(Value);
176 }
177
178 // When GNU as encounters more than one .type declaration for an object it seems
179 // to use a mechanism similar to the one below to decide which type is actually
180 // used in the object file.  The greater of T1 and T2 is selected based on the
181 // following ordering:
182 //  STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
183 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
184 // provided type).
185 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
186   for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
187                         ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
188     if (T1 == Type)
189       return T2;
190     if (T2 == Type)
191       return T1;
192   }
193
194   return T2;
195 }
196
197 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
198                                         MCSymbolAttr Attribute) {
199   // Indirect symbols are handled differently, to match how 'as' handles
200   // them. This makes writing matching .o files easier.
201   if (Attribute == MCSA_IndirectSymbol) {
202     // Note that we intentionally cannot use the symbol data here; this is
203     // important for matching the string table that 'as' generates.
204     IndirectSymbolData ISD;
205     ISD.Symbol = Symbol;
206     ISD.Section = &getCurrentSectionData()->getSection();
207     getAssembler().getIndirectSymbols().push_back(ISD);
208     return true;
209   }
210
211   // Adding a symbol attribute always introduces the symbol, note that an
212   // important side effect of calling getOrCreateSymbolData here is to register
213   // the symbol with the assembler.
214   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
215
216   // The implementation of symbol attributes is designed to match 'as', but it
217   // leaves much to desired. It doesn't really make sense to arbitrarily add and
218   // remove flags, but 'as' allows this (in particular, see .desc).
219   //
220   // In the future it might be worth trying to make these operations more well
221   // defined.
222   switch (Attribute) {
223   case MCSA_LazyReference:
224   case MCSA_Reference:
225   case MCSA_SymbolResolver:
226   case MCSA_PrivateExtern:
227   case MCSA_WeakDefinition:
228   case MCSA_WeakDefAutoPrivate:
229   case MCSA_Invalid:
230   case MCSA_IndirectSymbol:
231     return false;
232
233   case MCSA_NoDeadStrip:
234     // Ignore for now.
235     break;
236
237   case MCSA_ELF_TypeGnuUniqueObject:
238     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD), ELF::STT_OBJECT));
239     MCELF::SetBinding(SD, ELF::STB_GNU_UNIQUE);
240     SD.setExternal(true);
241     BindingExplicitlySet.insert(Symbol);
242     break;
243
244   case MCSA_Global:
245     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
246     SD.setExternal(true);
247     BindingExplicitlySet.insert(Symbol);
248     break;
249
250   case MCSA_WeakReference:
251   case MCSA_Weak:
252     MCELF::SetBinding(SD, ELF::STB_WEAK);
253     SD.setExternal(true);
254     BindingExplicitlySet.insert(Symbol);
255     break;
256
257   case MCSA_Local:
258     MCELF::SetBinding(SD, ELF::STB_LOCAL);
259     SD.setExternal(false);
260     BindingExplicitlySet.insert(Symbol);
261     break;
262
263   case MCSA_ELF_TypeFunction:
264     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
265                                           ELF::STT_FUNC));
266     break;
267
268   case MCSA_ELF_TypeIndFunction:
269     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
270                                           ELF::STT_GNU_IFUNC));
271     break;
272
273   case MCSA_ELF_TypeObject:
274     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
275                                           ELF::STT_OBJECT));
276     break;
277
278   case MCSA_ELF_TypeTLS:
279     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
280                                           ELF::STT_TLS));
281     break;
282
283   case MCSA_ELF_TypeCommon:
284     // TODO: Emit these as a common symbol.
285     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
286                                           ELF::STT_OBJECT));
287     break;
288
289   case MCSA_ELF_TypeNoType:
290     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
291                                           ELF::STT_NOTYPE));
292     break;
293
294   case MCSA_Protected:
295     MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
296     break;
297
298   case MCSA_Hidden:
299     MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
300     break;
301
302   case MCSA_Internal:
303     MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
304     break;
305   }
306
307   return true;
308 }
309
310 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
311                                        unsigned ByteAlignment) {
312   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
313
314   if (!BindingExplicitlySet.count(Symbol)) {
315     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
316     SD.setExternal(true);
317   }
318
319   MCELF::SetType(SD, ELF::STT_OBJECT);
320
321   if (MCELF::GetBinding(SD) == ELF_STB_Local) {
322     MCSection *Section = getAssembler().getContext().getELFSection(
323         ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
324
325     AssignSection(Symbol, Section);
326
327     struct LocalCommon L = {Symbol, Size, ByteAlignment};
328     LocalCommons.push_back(L);
329   } else {
330     SD.setCommon(Size, ByteAlignment);
331   }
332
333   SD.setSize(MCConstantExpr::Create(Size, getContext()));
334 }
335
336 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
337   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
338   SD.setSize(Value);
339 }
340
341 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
342                                           unsigned ByteAlignment) {
343   // FIXME: Should this be caught and done earlier?
344   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
345   MCELF::SetBinding(SD, ELF::STB_LOCAL);
346   SD.setExternal(false);
347   BindingExplicitlySet.insert(Symbol);
348   EmitCommonSymbol(Symbol, Size, ByteAlignment);
349 }
350
351 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
352                                   const SMLoc &Loc) {
353   if (isBundleLocked())
354     report_fatal_error("Emitting values inside a locked bundle is forbidden");
355   fixSymbolsInTLSFixups(Value);
356   MCObjectStreamer::EmitValueImpl(Value, Size, Loc);
357 }
358
359 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
360                                          int64_t Value,
361                                          unsigned ValueSize,
362                                          unsigned MaxBytesToEmit) {
363   if (isBundleLocked())
364     report_fatal_error("Emitting values inside a locked bundle is forbidden");
365   MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
366                                          ValueSize, MaxBytesToEmit);
367 }
368
369 // Add a symbol for the file name of this module. They start after the
370 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
371 // with the same name may appear.
372 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
373   getAssembler().addFileName(Filename);
374 }
375
376 void MCELFStreamer::EmitIdent(StringRef IdentString) {
377   MCSection *Comment = getAssembler().getContext().getELFSection(
378       ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
379   PushSection();
380   SwitchSection(Comment);
381   if (!SeenIdent) {
382     EmitIntValue(0, 1);
383     SeenIdent = true;
384   }
385   EmitBytes(IdentString);
386   EmitIntValue(0, 1);
387   PopSection();
388 }
389
390 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
391   switch (expr->getKind()) {
392   case MCExpr::Target:
393     cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
394     break;
395   case MCExpr::Constant:
396     break;
397
398   case MCExpr::Binary: {
399     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
400     fixSymbolsInTLSFixups(be->getLHS());
401     fixSymbolsInTLSFixups(be->getRHS());
402     break;
403   }
404
405   case MCExpr::SymbolRef: {
406     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
407     switch (symRef.getKind()) {
408     default:
409       return;
410     case MCSymbolRefExpr::VK_GOTTPOFF:
411     case MCSymbolRefExpr::VK_INDNTPOFF:
412     case MCSymbolRefExpr::VK_NTPOFF:
413     case MCSymbolRefExpr::VK_GOTNTPOFF:
414     case MCSymbolRefExpr::VK_TLSGD:
415     case MCSymbolRefExpr::VK_TLSLD:
416     case MCSymbolRefExpr::VK_TLSLDM:
417     case MCSymbolRefExpr::VK_TPOFF:
418     case MCSymbolRefExpr::VK_DTPOFF:
419     case MCSymbolRefExpr::VK_Mips_TLSGD:
420     case MCSymbolRefExpr::VK_Mips_GOTTPREL:
421     case MCSymbolRefExpr::VK_Mips_TPREL_HI:
422     case MCSymbolRefExpr::VK_Mips_TPREL_LO:
423     case MCSymbolRefExpr::VK_PPC_DTPMOD:
424     case MCSymbolRefExpr::VK_PPC_TPREL:
425     case MCSymbolRefExpr::VK_PPC_TPREL_LO:
426     case MCSymbolRefExpr::VK_PPC_TPREL_HI:
427     case MCSymbolRefExpr::VK_PPC_TPREL_HA:
428     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
429     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
430     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
431     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
432     case MCSymbolRefExpr::VK_PPC_DTPREL:
433     case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
434     case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
435     case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
436     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
437     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
438     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
439     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
440     case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
441     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
442     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
443     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
444     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
445     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
446     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
447     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
448     case MCSymbolRefExpr::VK_PPC_TLS:
449     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
450     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
451     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
452     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
453     case MCSymbolRefExpr::VK_PPC_TLSGD:
454     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
455     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
456     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
457     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
458     case MCSymbolRefExpr::VK_PPC_TLSLD:
459       break;
460     }
461     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
462     MCELF::SetType(SD, ELF::STT_TLS);
463     break;
464   }
465
466   case MCExpr::Unary:
467     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
468     break;
469   }
470 }
471
472 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst,
473                                        const MCSubtargetInfo &STI) {
474   this->MCObjectStreamer::EmitInstToFragment(Inst, STI);
475   MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
476
477   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
478     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
479 }
480
481 void MCELFStreamer::EmitInstToData(const MCInst &Inst,
482                                    const MCSubtargetInfo &STI) {
483   MCAssembler &Assembler = getAssembler();
484   SmallVector<MCFixup, 4> Fixups;
485   SmallString<256> Code;
486   raw_svector_ostream VecOS(Code);
487   Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
488   VecOS.flush();
489
490   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
491     fixSymbolsInTLSFixups(Fixups[i].getValue());
492
493   // There are several possibilities here:
494   //
495   // If bundling is disabled, append the encoded instruction to the current data
496   // fragment (or create a new such fragment if the current fragment is not a
497   // data fragment).
498   //
499   // If bundling is enabled:
500   // - If we're not in a bundle-locked group, emit the instruction into a
501   //   fragment of its own. If there are no fixups registered for the
502   //   instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
503   //   MCDataFragment.
504   // - If we're in a bundle-locked group, append the instruction to the current
505   //   data fragment because we want all the instructions in a group to get into
506   //   the same fragment. Be careful not to do that for the first instruction in
507   //   the group, though.
508   MCDataFragment *DF;
509
510   if (Assembler.isBundlingEnabled()) {
511     MCSectionData *SD = getCurrentSectionData();
512     MCSection &Sec = SD->getSection();
513     if (Assembler.getRelaxAll() && isBundleLocked())
514       // If the -mc-relax-all flag is used and we are bundle-locked, we re-use
515       // the current bundle group.
516       DF = BundleGroups.back();
517     else if (Assembler.getRelaxAll() && !isBundleLocked())
518       // When not in a bundle-locked group and the -mc-relax-all flag is used,
519       // we create a new temporary fragment which will be later merged into
520       // the current fragment.
521       DF = new MCDataFragment();
522     else if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst())
523       // If we are bundle-locked, we re-use the current fragment.
524       // The bundle-locking directive ensures this is a new data fragment.
525       DF = cast<MCDataFragment>(getCurrentFragment());
526     else if (!isBundleLocked() && Fixups.size() == 0) {
527       // Optimize memory usage by emitting the instruction to a
528       // MCCompactEncodedInstFragment when not in a bundle-locked group and
529       // there are no fixups registered.
530       MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
531       insert(CEIF);
532       CEIF->getContents().append(Code.begin(), Code.end());
533       return;
534     } else {
535       DF = new MCDataFragment();
536       insert(DF);
537     }
538     if (Sec.getBundleLockState() == MCSection::BundleLockedAlignToEnd) {
539       // If this fragment is for a group marked "align_to_end", set a flag
540       // in the fragment. This can happen after the fragment has already been
541       // created if there are nested bundle_align groups and an inner one
542       // is the one marked align_to_end.
543       DF->setAlignToBundleEnd(true);
544     }
545
546     // We're now emitting an instruction in a bundle group, so this flag has
547     // to be turned off.
548     Sec.setBundleGroupBeforeFirstInst(false);
549   } else {
550     DF = getOrCreateDataFragment();
551   }
552
553   // Add the fixups and data.
554   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
555     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
556     DF->getFixups().push_back(Fixups[i]);
557   }
558   DF->setHasInstructions(true);
559   DF->getContents().append(Code.begin(), Code.end());
560
561   if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
562     if (!isBundleLocked()) {
563       mergeFragment(getOrCreateDataFragment(), DF);
564       delete DF;
565     }
566   }
567 }
568
569 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
570   assert(AlignPow2 <= 30 && "Invalid bundle alignment");
571   MCAssembler &Assembler = getAssembler();
572   if (AlignPow2 > 0 && (Assembler.getBundleAlignSize() == 0 ||
573                         Assembler.getBundleAlignSize() == 1U << AlignPow2))
574     Assembler.setBundleAlignSize(1U << AlignPow2);
575   else
576     report_fatal_error(".bundle_align_mode cannot be changed once set");
577 }
578
579 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
580   MCSectionData *SD = getCurrentSectionData();
581   MCSection &Sec = SD->getSection();
582
583   // Sanity checks
584   //
585   if (!getAssembler().isBundlingEnabled())
586     report_fatal_error(".bundle_lock forbidden when bundling is disabled");
587
588   if (!isBundleLocked())
589     Sec.setBundleGroupBeforeFirstInst(true);
590
591   if (getAssembler().getRelaxAll() && !isBundleLocked()) {
592     // TODO: drop the lock state and set directly in the fragment
593     MCDataFragment *DF = new MCDataFragment();
594     BundleGroups.push_back(DF);
595   }
596
597   Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
598                                     : MCSection::BundleLocked);
599 }
600
601 void MCELFStreamer::EmitBundleUnlock() {
602   MCSectionData *SD = getCurrentSectionData();
603   MCSection &Sec = SD->getSection();
604
605   // Sanity checks
606   if (!getAssembler().isBundlingEnabled())
607     report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
608   else if (!isBundleLocked())
609     report_fatal_error(".bundle_unlock without matching lock");
610   else if (Sec.isBundleGroupBeforeFirstInst())
611     report_fatal_error("Empty bundle-locked group is forbidden");
612
613   // When the -mc-relax-all flag is used, we emit instructions to fragments
614   // stored on a stack. When the bundle unlock is emited, we pop a fragment 
615   // from the stack a merge it to the one below.
616   if (getAssembler().getRelaxAll()) {
617     assert(!BundleGroups.empty() && "There are no bundle groups");
618     MCDataFragment *DF = BundleGroups.back();
619
620     // FIXME: Use BundleGroups to track the lock state instead.
621     Sec.setBundleLockState(MCSection::NotBundleLocked);
622
623     // FIXME: Use more separate fragments for nested groups.
624     if (!isBundleLocked()) {
625       mergeFragment(getOrCreateDataFragment(), DF);
626       BundleGroups.pop_back();
627       delete DF;
628     }
629
630     if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
631       getOrCreateDataFragment()->setAlignToBundleEnd(false);
632   } else
633     Sec.setBundleLockState(MCSection::NotBundleLocked);
634 }
635
636 void MCELFStreamer::Flush() {
637   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
638                                                 e = LocalCommons.end();
639        i != e; ++i) {
640     const MCSymbol &Symbol = *i->Symbol;
641     uint64_t Size = i->Size;
642     unsigned ByteAlignment = i->ByteAlignment;
643     MCSection &Section = Symbol.getSection();
644
645     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
646     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment,
647                         &SectData.getSection());
648
649     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData.getSection());
650     Symbol.getData().setFragment(F);
651
652     // Update the maximum alignment of the section if necessary.
653     if (ByteAlignment > Section.getAlignment())
654       Section.setAlignment(ByteAlignment);
655   }
656
657   LocalCommons.clear();
658 }
659
660 void MCELFStreamer::FinishImpl() {
661   // Ensure the last section gets aligned if necessary.
662   MCSectionData *CurSectionData = getCurrentSectionData();
663   MCSection *CurSection =
664       CurSectionData ? &CurSectionData->getSection() : nullptr;
665   setSectionAlignmentForBundling(getAssembler(), CurSection);
666
667   EmitFrames(nullptr);
668
669   Flush();
670
671   this->MCObjectStreamer::FinishImpl();
672 }
673
674 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
675                                     raw_pwrite_stream &OS, MCCodeEmitter *CE,
676                                     bool RelaxAll) {
677   MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
678   if (RelaxAll)
679     S->getAssembler().setRelaxAll(true);
680   return S;
681 }
682
683 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
684   llvm_unreachable("Generic ELF doesn't support this directive");
685 }
686
687 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
688   llvm_unreachable("ELF doesn't support this directive");
689 }
690
691 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
692   llvm_unreachable("ELF doesn't support this directive");
693 }
694
695 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
696   llvm_unreachable("ELF doesn't support this directive");
697 }
698
699 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
700   llvm_unreachable("ELF doesn't support this directive");
701 }
702
703 void MCELFStreamer::EndCOFFSymbolDef() {
704   llvm_unreachable("ELF doesn't support this directive");
705 }
706
707 void MCELFStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
708                                  uint64_t Size, unsigned ByteAlignment) {
709   llvm_unreachable("ELF doesn't support this directive");
710 }
711
712 void MCELFStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
713                                    uint64_t Size, unsigned ByteAlignment) {
714   llvm_unreachable("ELF doesn't support this directive");
715 }