b3a9ca7f3a70267b0127212a396acec59d83c376
[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 getCurrentSectionOnly()->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   MCSection *CurSection = getCurrentSectionOnly();
150   if (CurSection && isBundleLocked())
151     report_fatal_error("Unterminated .bundle_lock when changing a section");
152
153   MCAssembler &Asm = getAssembler();
154   // Ensure the previous section gets aligned if necessary.
155   setSectionAlignmentForBundling(Asm, CurSection);
156   auto *SectionELF = static_cast<const MCSectionELF *>(Section);
157   const MCSymbol *Grp = SectionELF->getGroup();
158   if (Grp)
159     Asm.getOrCreateSymbolData(*Grp);
160
161   this->MCObjectStreamer::ChangeSection(Section, Subsection);
162   MCContext &Ctx = getContext();
163   MCSymbol *Begin = Section->getBeginSymbol();
164   if (!Begin) {
165     Begin = Ctx.getOrCreateSectionSymbol(*SectionELF);
166     Section->setBeginSymbol(Begin);
167   }
168   if (Begin->isUndefined())
169     MCELF::SetType(Asm.getOrCreateSymbolData(*Begin), ELF::STT_SECTION);
170 }
171
172 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
173   getAssembler().getOrCreateSymbolData(*Symbol);
174   const MCExpr *Value = MCSymbolRefExpr::Create(
175       Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
176   Alias->setVariableValue(Value);
177 }
178
179 // When GNU as encounters more than one .type declaration for an object it seems
180 // to use a mechanism similar to the one below to decide which type is actually
181 // used in the object file.  The greater of T1 and T2 is selected based on the
182 // following ordering:
183 //  STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
184 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
185 // provided type).
186 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
187   for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
188                         ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
189     if (T1 == Type)
190       return T2;
191     if (T2 == Type)
192       return T1;
193   }
194
195   return T2;
196 }
197
198 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
199                                         MCSymbolAttr Attribute) {
200   // Indirect symbols are handled differently, to match how 'as' handles
201   // them. This makes writing matching .o files easier.
202   if (Attribute == MCSA_IndirectSymbol) {
203     // Note that we intentionally cannot use the symbol data here; this is
204     // important for matching the string table that 'as' generates.
205     IndirectSymbolData ISD;
206     ISD.Symbol = Symbol;
207     ISD.Section = getCurrentSectionOnly();
208     getAssembler().getIndirectSymbols().push_back(ISD);
209     return true;
210   }
211
212   // Adding a symbol attribute always introduces the symbol, note that an
213   // important side effect of calling getOrCreateSymbolData here is to register
214   // the symbol with the assembler.
215   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
216
217   // The implementation of symbol attributes is designed to match 'as', but it
218   // leaves much to desired. It doesn't really make sense to arbitrarily add and
219   // remove flags, but 'as' allows this (in particular, see .desc).
220   //
221   // In the future it might be worth trying to make these operations more well
222   // defined.
223   switch (Attribute) {
224   case MCSA_LazyReference:
225   case MCSA_Reference:
226   case MCSA_SymbolResolver:
227   case MCSA_PrivateExtern:
228   case MCSA_WeakDefinition:
229   case MCSA_WeakDefAutoPrivate:
230   case MCSA_Invalid:
231   case MCSA_IndirectSymbol:
232     return false;
233
234   case MCSA_NoDeadStrip:
235     // Ignore for now.
236     break;
237
238   case MCSA_ELF_TypeGnuUniqueObject:
239     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD), ELF::STT_OBJECT));
240     MCELF::SetBinding(SD, ELF::STB_GNU_UNIQUE);
241     SD.setExternal(true);
242     BindingExplicitlySet.insert(Symbol);
243     break;
244
245   case MCSA_Global:
246     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
247     SD.setExternal(true);
248     BindingExplicitlySet.insert(Symbol);
249     break;
250
251   case MCSA_WeakReference:
252   case MCSA_Weak:
253     MCELF::SetBinding(SD, ELF::STB_WEAK);
254     SD.setExternal(true);
255     BindingExplicitlySet.insert(Symbol);
256     break;
257
258   case MCSA_Local:
259     MCELF::SetBinding(SD, ELF::STB_LOCAL);
260     SD.setExternal(false);
261     BindingExplicitlySet.insert(Symbol);
262     break;
263
264   case MCSA_ELF_TypeFunction:
265     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
266                                           ELF::STT_FUNC));
267     break;
268
269   case MCSA_ELF_TypeIndFunction:
270     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
271                                           ELF::STT_GNU_IFUNC));
272     break;
273
274   case MCSA_ELF_TypeObject:
275     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
276                                           ELF::STT_OBJECT));
277     break;
278
279   case MCSA_ELF_TypeTLS:
280     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
281                                           ELF::STT_TLS));
282     break;
283
284   case MCSA_ELF_TypeCommon:
285     // TODO: Emit these as a common symbol.
286     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
287                                           ELF::STT_OBJECT));
288     break;
289
290   case MCSA_ELF_TypeNoType:
291     MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
292                                           ELF::STT_NOTYPE));
293     break;
294
295   case MCSA_Protected:
296     MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
297     break;
298
299   case MCSA_Hidden:
300     MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
301     break;
302
303   case MCSA_Internal:
304     MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
305     break;
306   }
307
308   return true;
309 }
310
311 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
312                                        unsigned ByteAlignment) {
313   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
314
315   if (!BindingExplicitlySet.count(Symbol)) {
316     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
317     SD.setExternal(true);
318   }
319
320   MCELF::SetType(SD, ELF::STT_OBJECT);
321
322   if (MCELF::GetBinding(SD) == ELF_STB_Local) {
323     MCSection *Section = getAssembler().getContext().getELFSection(
324         ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
325
326     AssignSection(Symbol, Section);
327
328     struct LocalCommon L = {Symbol, Size, ByteAlignment};
329     LocalCommons.push_back(L);
330   } else {
331     SD.setCommon(Size, ByteAlignment);
332   }
333
334   SD.setSize(MCConstantExpr::Create(Size, getContext()));
335 }
336
337 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
338   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
339   SD.setSize(Value);
340 }
341
342 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
343                                           unsigned ByteAlignment) {
344   // FIXME: Should this be caught and done earlier?
345   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
346   MCELF::SetBinding(SD, ELF::STB_LOCAL);
347   SD.setExternal(false);
348   BindingExplicitlySet.insert(Symbol);
349   EmitCommonSymbol(Symbol, Size, ByteAlignment);
350 }
351
352 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
353                                   const SMLoc &Loc) {
354   if (isBundleLocked())
355     report_fatal_error("Emitting values inside a locked bundle is forbidden");
356   fixSymbolsInTLSFixups(Value);
357   MCObjectStreamer::EmitValueImpl(Value, Size, Loc);
358 }
359
360 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
361                                          int64_t Value,
362                                          unsigned ValueSize,
363                                          unsigned MaxBytesToEmit) {
364   if (isBundleLocked())
365     report_fatal_error("Emitting values inside a locked bundle is forbidden");
366   MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
367                                          ValueSize, MaxBytesToEmit);
368 }
369
370 // Add a symbol for the file name of this module. They start after the
371 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
372 // with the same name may appear.
373 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
374   getAssembler().addFileName(Filename);
375 }
376
377 void MCELFStreamer::EmitIdent(StringRef IdentString) {
378   MCSection *Comment = getAssembler().getContext().getELFSection(
379       ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
380   PushSection();
381   SwitchSection(Comment);
382   if (!SeenIdent) {
383     EmitIntValue(0, 1);
384     SeenIdent = true;
385   }
386   EmitBytes(IdentString);
387   EmitIntValue(0, 1);
388   PopSection();
389 }
390
391 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
392   switch (expr->getKind()) {
393   case MCExpr::Target:
394     cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
395     break;
396   case MCExpr::Constant:
397     break;
398
399   case MCExpr::Binary: {
400     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
401     fixSymbolsInTLSFixups(be->getLHS());
402     fixSymbolsInTLSFixups(be->getRHS());
403     break;
404   }
405
406   case MCExpr::SymbolRef: {
407     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
408     switch (symRef.getKind()) {
409     default:
410       return;
411     case MCSymbolRefExpr::VK_GOTTPOFF:
412     case MCSymbolRefExpr::VK_INDNTPOFF:
413     case MCSymbolRefExpr::VK_NTPOFF:
414     case MCSymbolRefExpr::VK_GOTNTPOFF:
415     case MCSymbolRefExpr::VK_TLSGD:
416     case MCSymbolRefExpr::VK_TLSLD:
417     case MCSymbolRefExpr::VK_TLSLDM:
418     case MCSymbolRefExpr::VK_TPOFF:
419     case MCSymbolRefExpr::VK_DTPOFF:
420     case MCSymbolRefExpr::VK_Mips_TLSGD:
421     case MCSymbolRefExpr::VK_Mips_GOTTPREL:
422     case MCSymbolRefExpr::VK_Mips_TPREL_HI:
423     case MCSymbolRefExpr::VK_Mips_TPREL_LO:
424     case MCSymbolRefExpr::VK_PPC_DTPMOD:
425     case MCSymbolRefExpr::VK_PPC_TPREL:
426     case MCSymbolRefExpr::VK_PPC_TPREL_LO:
427     case MCSymbolRefExpr::VK_PPC_TPREL_HI:
428     case MCSymbolRefExpr::VK_PPC_TPREL_HA:
429     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
430     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
431     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
432     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
433     case MCSymbolRefExpr::VK_PPC_DTPREL:
434     case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
435     case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
436     case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
437     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
438     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
439     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
440     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
441     case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
442     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
443     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
444     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
445     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
446     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
447     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
448     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
449     case MCSymbolRefExpr::VK_PPC_TLS:
450     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
451     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
452     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
453     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
454     case MCSymbolRefExpr::VK_PPC_TLSGD:
455     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
456     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
457     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
458     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
459     case MCSymbolRefExpr::VK_PPC_TLSLD:
460       break;
461     }
462     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
463     MCELF::SetType(SD, ELF::STT_TLS);
464     break;
465   }
466
467   case MCExpr::Unary:
468     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
469     break;
470   }
471 }
472
473 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst,
474                                        const MCSubtargetInfo &STI) {
475   this->MCObjectStreamer::EmitInstToFragment(Inst, STI);
476   MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
477
478   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
479     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
480 }
481
482 void MCELFStreamer::EmitInstToData(const MCInst &Inst,
483                                    const MCSubtargetInfo &STI) {
484   MCAssembler &Assembler = getAssembler();
485   SmallVector<MCFixup, 4> Fixups;
486   SmallString<256> Code;
487   raw_svector_ostream VecOS(Code);
488   Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
489   VecOS.flush();
490
491   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
492     fixSymbolsInTLSFixups(Fixups[i].getValue());
493
494   // There are several possibilities here:
495   //
496   // If bundling is disabled, append the encoded instruction to the current data
497   // fragment (or create a new such fragment if the current fragment is not a
498   // data fragment).
499   //
500   // If bundling is enabled:
501   // - If we're not in a bundle-locked group, emit the instruction into a
502   //   fragment of its own. If there are no fixups registered for the
503   //   instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
504   //   MCDataFragment.
505   // - If we're in a bundle-locked group, append the instruction to the current
506   //   data fragment because we want all the instructions in a group to get into
507   //   the same fragment. Be careful not to do that for the first instruction in
508   //   the group, though.
509   MCDataFragment *DF;
510
511   if (Assembler.isBundlingEnabled()) {
512     MCSection &Sec = *getCurrentSectionOnly();
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   MCSection &Sec = *getCurrentSectionOnly();
581
582   // Sanity checks
583   //
584   if (!getAssembler().isBundlingEnabled())
585     report_fatal_error(".bundle_lock forbidden when bundling is disabled");
586
587   if (!isBundleLocked())
588     Sec.setBundleGroupBeforeFirstInst(true);
589
590   if (getAssembler().getRelaxAll() && !isBundleLocked()) {
591     // TODO: drop the lock state and set directly in the fragment
592     MCDataFragment *DF = new MCDataFragment();
593     BundleGroups.push_back(DF);
594   }
595
596   Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
597                                     : MCSection::BundleLocked);
598 }
599
600 void MCELFStreamer::EmitBundleUnlock() {
601   MCSection &Sec = *getCurrentSectionOnly();
602
603   // Sanity checks
604   if (!getAssembler().isBundlingEnabled())
605     report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
606   else if (!isBundleLocked())
607     report_fatal_error(".bundle_unlock without matching lock");
608   else if (Sec.isBundleGroupBeforeFirstInst())
609     report_fatal_error("Empty bundle-locked group is forbidden");
610
611   // When the -mc-relax-all flag is used, we emit instructions to fragments
612   // stored on a stack. When the bundle unlock is emited, we pop a fragment 
613   // from the stack a merge it to the one below.
614   if (getAssembler().getRelaxAll()) {
615     assert(!BundleGroups.empty() && "There are no bundle groups");
616     MCDataFragment *DF = BundleGroups.back();
617
618     // FIXME: Use BundleGroups to track the lock state instead.
619     Sec.setBundleLockState(MCSection::NotBundleLocked);
620
621     // FIXME: Use more separate fragments for nested groups.
622     if (!isBundleLocked()) {
623       mergeFragment(getOrCreateDataFragment(), DF);
624       BundleGroups.pop_back();
625       delete DF;
626     }
627
628     if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
629       getOrCreateDataFragment()->setAlignToBundleEnd(false);
630   } else
631     Sec.setBundleLockState(MCSection::NotBundleLocked);
632 }
633
634 void MCELFStreamer::Flush() {
635   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
636                                                 e = LocalCommons.end();
637        i != e; ++i) {
638     const MCSymbol &Symbol = *i->Symbol;
639     uint64_t Size = i->Size;
640     unsigned ByteAlignment = i->ByteAlignment;
641     MCSection &Section = Symbol.getSection();
642
643     getAssembler().registerSection(Section);
644     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &Section);
645
646     MCFragment *F = new MCFillFragment(0, 0, Size, &Section);
647     Symbol.getData().setFragment(F);
648
649     // Update the maximum alignment of the section if necessary.
650     if (ByteAlignment > Section.getAlignment())
651       Section.setAlignment(ByteAlignment);
652   }
653
654   LocalCommons.clear();
655 }
656
657 void MCELFStreamer::FinishImpl() {
658   // Ensure the last section gets aligned if necessary.
659   MCSection *CurSection = getCurrentSectionOnly();
660   setSectionAlignmentForBundling(getAssembler(), CurSection);
661
662   EmitFrames(nullptr);
663
664   Flush();
665
666   this->MCObjectStreamer::FinishImpl();
667 }
668
669 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
670                                     raw_pwrite_stream &OS, MCCodeEmitter *CE,
671                                     bool RelaxAll) {
672   MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
673   if (RelaxAll)
674     S->getAssembler().setRelaxAll(true);
675   return S;
676 }
677
678 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
679   llvm_unreachable("Generic ELF doesn't support this directive");
680 }
681
682 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
683   llvm_unreachable("ELF doesn't support this directive");
684 }
685
686 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
687   llvm_unreachable("ELF doesn't support this directive");
688 }
689
690 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
691   llvm_unreachable("ELF doesn't support this directive");
692 }
693
694 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
695   llvm_unreachable("ELF doesn't support this directive");
696 }
697
698 void MCELFStreamer::EndCOFFSymbolDef() {
699   llvm_unreachable("ELF doesn't support this directive");
700 }
701
702 void MCELFStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
703                                  uint64_t Size, unsigned ByteAlignment) {
704   llvm_unreachable("ELF doesn't support this directive");
705 }
706
707 void MCELFStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
708                                    uint64_t Size, unsigned ByteAlignment) {
709   llvm_unreachable("ELF doesn't support this directive");
710 }