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