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