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