Don't declare all text sections at the start of the .s
[oota-llvm.git] / lib / MC / MCObjectStreamer.cpp
1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
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 #include "llvm/MC/MCObjectStreamer.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/MC/MCAsmBackend.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCCodeEmitter.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCDwarf.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/TargetRegistry.h"
24 using namespace llvm;
25
26 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
27                                    raw_ostream &OS, MCCodeEmitter *Emitter_)
28     : MCStreamer(Context),
29       Assembler(new MCAssembler(Context, TAB, *Emitter_,
30                                 *TAB.createObjectWriter(OS), OS)),
31       CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
32
33 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
34                                    raw_ostream &OS, MCCodeEmitter *Emitter_,
35                                    MCAssembler *Assembler)
36     : MCStreamer(Context), Assembler(Assembler), CurSectionData(nullptr),
37       EmitEHFrame(true), EmitDebugFrame(false) {}
38
39 MCObjectStreamer::~MCObjectStreamer() {
40   delete &Assembler->getBackend();
41   delete &Assembler->getEmitter();
42   delete &Assembler->getWriter();
43   delete Assembler;
44 }
45
46 void MCObjectStreamer::flushPendingLabels(MCFragment *F) {
47   if (PendingLabels.size()) {
48     if (!F) {
49       F = new MCDataFragment();
50       CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
51       F->setParent(CurSectionData);
52     }
53     for (MCSymbolData *SD : PendingLabels) {
54       SD->setFragment(F);
55       SD->setOffset(0);
56     }
57     PendingLabels.clear();
58   }
59 }
60
61 void MCObjectStreamer::reset() {
62   if (Assembler)
63     Assembler->reset();
64   CurSectionData = nullptr;
65   CurInsertionPoint = MCSectionData::iterator();
66   EmitEHFrame = true;
67   EmitDebugFrame = false;
68   PendingLabels.clear();
69   MCStreamer::reset();
70 }
71
72 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
73   if (!getNumFrameInfos())
74     return;
75
76   if (EmitEHFrame)
77     MCDwarfFrameEmitter::Emit(*this, MAB, true);
78
79   if (EmitDebugFrame)
80     MCDwarfFrameEmitter::Emit(*this, MAB, false);
81 }
82
83 MCFragment *MCObjectStreamer::getCurrentFragment() const {
84   assert(getCurrentSectionData() && "No current section!");
85
86   if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
87     return std::prev(CurInsertionPoint);
88
89   return nullptr;
90 }
91
92 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
93   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
94   // When bundling is enabled, we don't want to add data to a fragment that
95   // already has instructions (see MCELFStreamer::EmitInstToData for details)
96   if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
97     F = new MCDataFragment();
98     insert(F);
99   }
100   return F;
101 }
102
103 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
104   Assembler->getOrCreateSymbolData(Sym);
105 }
106
107 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
108   MCStreamer::EmitCFISections(EH, Debug);
109   EmitEHFrame = EH;
110   EmitDebugFrame = Debug;
111 }
112
113 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
114                                      const SMLoc &Loc) {
115   MCStreamer::EmitValueImpl(Value, Size, Loc);
116   MCDataFragment *DF = getOrCreateDataFragment();
117
118   MCLineEntry::Make(this, getCurrentSection().first);
119
120   // Avoid fixups when possible.
121   int64_t AbsValue;
122   if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
123     EmitIntValue(AbsValue, Size);
124     return;
125   }
126   DF->getFixups().push_back(
127       MCFixup::Create(DF->getContents().size(), Value,
128                       MCFixup::getKindForSize(Size, false), Loc));
129   DF->getContents().resize(DF->getContents().size() + Size, 0);
130 }
131
132 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
133   // We need to create a local symbol to avoid relocations.
134   Frame.Begin = getContext().CreateTempSymbol();
135   EmitLabel(Frame.Begin);
136 }
137
138 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
139   Frame.End = getContext().CreateTempSymbol();
140   EmitLabel(Frame.End);
141 }
142
143 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
144   MCStreamer::EmitLabel(Symbol);
145
146   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
147   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
148
149   // If there is a current fragment, mark the symbol as pointing into it.
150   // Otherwise queue the label and set its fragment pointer when we emit the
151   // next fragment.
152   if (auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment())) {
153     SD.setFragment(F);
154     SD.setOffset(F->getContents().size());
155   } else {
156     PendingLabels.push_back(&SD);
157   }
158 }
159
160 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
161   int64_t IntValue;
162   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
163     EmitULEB128IntValue(IntValue);
164     return;
165   }
166   insert(new MCLEBFragment(*Value, false));
167 }
168
169 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
170   int64_t IntValue;
171   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
172     EmitSLEB128IntValue(IntValue);
173     return;
174   }
175   insert(new MCLEBFragment(*Value, true));
176 }
177
178 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
179                                          const MCSymbol *Symbol) {
180   report_fatal_error("This file format doesn't support weak aliases.");
181 }
182
183 void MCObjectStreamer::ChangeSection(const MCSection *Section,
184                                      const MCExpr *Subsection) {
185   changeSectionImpl(Section, Subsection);
186 }
187
188 bool MCObjectStreamer::changeSectionImpl(const MCSection *Section,
189                                          const MCExpr *Subsection) {
190   assert(Section && "Cannot switch to a null section!");
191   flushPendingLabels(nullptr);
192
193   bool Created;
194   CurSectionData = &getAssembler().getOrCreateSectionData(*Section, &Created);
195
196   int64_t IntSubsection = 0;
197   if (Subsection &&
198       !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
199     report_fatal_error("Cannot evaluate subsection number");
200   if (IntSubsection < 0 || IntSubsection > 8192)
201     report_fatal_error("Subsection number out of range");
202   CurInsertionPoint =
203     CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
204   return Created;
205 }
206
207 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
208   getAssembler().getOrCreateSymbolData(*Symbol);
209   MCStreamer::EmitAssignment(Symbol, Value);
210 }
211
212 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
213                                        const MCSubtargetInfo &STI) {
214   MCStreamer::EmitInstruction(Inst, STI);
215
216   MCSectionData *SD = getCurrentSectionData();
217   SD->setHasInstructions(true);
218
219   // Now that a machine instruction has been assembled into this section, make
220   // a line entry for any .loc directive that has been seen.
221   MCLineEntry::Make(this, getCurrentSection().first);
222
223   // If this instruction doesn't need relaxation, just emit it as data.
224   MCAssembler &Assembler = getAssembler();
225   if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
226     EmitInstToData(Inst, STI);
227     return;
228   }
229
230   // Otherwise, relax and emit it as data if either:
231   // - The RelaxAll flag was passed
232   // - Bundling is enabled and this instruction is inside a bundle-locked
233   //   group. We want to emit all such instructions into the same data
234   //   fragment.
235   if (Assembler.getRelaxAll() ||
236       (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
237     MCInst Relaxed;
238     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
239     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
240       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
241     EmitInstToData(Relaxed, STI);
242     return;
243   }
244
245   // Otherwise emit to a separate fragment.
246   EmitInstToFragment(Inst, STI);
247 }
248
249 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
250                                           const MCSubtargetInfo &STI) {
251   // Always create a new, separate fragment here, because its size can change
252   // during relaxation.
253   MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
254   insert(IF);
255
256   SmallString<128> Code;
257   raw_svector_ostream VecOS(Code);
258   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
259                                                 STI);
260   VecOS.flush();
261   IF->getContents().append(Code.begin(), Code.end());
262 }
263
264 #ifndef NDEBUG
265 static const char *const BundlingNotImplementedMsg =
266   "Aligned bundling is not implemented for this object format";
267 #endif
268
269 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
270   llvm_unreachable(BundlingNotImplementedMsg);
271 }
272
273 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
274   llvm_unreachable(BundlingNotImplementedMsg);
275 }
276
277 void MCObjectStreamer::EmitBundleUnlock() {
278   llvm_unreachable(BundlingNotImplementedMsg);
279 }
280
281 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
282                                              unsigned Column, unsigned Flags,
283                                              unsigned Isa,
284                                              unsigned Discriminator,
285                                              StringRef FileName) {
286   // In case we see two .loc directives in a row, make sure the
287   // first one gets a line entry.
288   MCLineEntry::Make(this, getCurrentSection().first);
289
290   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
291                                           Isa, Discriminator, FileName);
292 }
293
294 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
295                                      const MCSymbol *B) {
296   MCContext &Context = OS.getContext();
297   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
298   const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
299   const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
300   const MCExpr *AddrDelta =
301       MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
302   return AddrDelta;
303 }
304
305 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
306                                  const MCSymbol *Label, int PointerSize) {
307   // emit the sequence to set the address
308   OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
309   OS.EmitULEB128IntValue(PointerSize + 1);
310   OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
311   OS.EmitSymbolValue(Label, PointerSize);
312
313   // emit the sequence for the LineDelta (from 1) and a zero address delta.
314   MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
315 }
316
317 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
318                                                 const MCSymbol *LastLabel,
319                                                 const MCSymbol *Label,
320                                                 unsigned PointerSize) {
321   if (!LastLabel) {
322     emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
323     return;
324   }
325   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
326   int64_t Res;
327   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
328     MCDwarfLineAddr::Emit(this, LineDelta, Res);
329     return;
330   }
331   insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
332 }
333
334 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
335                                                  const MCSymbol *Label) {
336   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
337   int64_t Res;
338   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
339     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
340     return;
341   }
342   insert(new MCDwarfCallFrameFragment(*AddrDelta));
343 }
344
345 void MCObjectStreamer::EmitBytes(StringRef Data) {
346   MCLineEntry::Make(this, getCurrentSection().first);
347   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
348 }
349
350 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
351                                             int64_t Value,
352                                             unsigned ValueSize,
353                                             unsigned MaxBytesToEmit) {
354   if (MaxBytesToEmit == 0)
355     MaxBytesToEmit = ByteAlignment;
356   insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
357
358   // Update the maximum alignment on the current section if necessary.
359   if (ByteAlignment > getCurrentSectionData()->getAlignment())
360     getCurrentSectionData()->setAlignment(ByteAlignment);
361 }
362
363 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
364                                          unsigned MaxBytesToEmit) {
365   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
366   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
367 }
368
369 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
370                                          unsigned char Value) {
371   int64_t Res;
372   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
373     insert(new MCOrgFragment(*Offset, Value));
374     return false;
375   }
376
377   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
378   EmitLabel(CurrentPos);
379   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
380   const MCExpr *Ref =
381     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
382   const MCExpr *Delta =
383     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
384
385   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
386     return true;
387   EmitFill(Res, Value);
388   return false;
389 }
390
391 // Associate GPRel32 fixup with data and resize data area
392 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
393   MCDataFragment *DF = getOrCreateDataFragment();
394
395   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
396                                             Value, FK_GPRel_4));
397   DF->getContents().resize(DF->getContents().size() + 4, 0);
398 }
399
400 // Associate GPRel32 fixup with data and resize data area
401 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
402   MCDataFragment *DF = getOrCreateDataFragment();
403
404   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
405                                             Value, FK_GPRel_4));
406   DF->getContents().resize(DF->getContents().size() + 8, 0);
407 }
408
409 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
410   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
411   //        problems evaluating expressions across multiple fragments.
412   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
413 }
414
415 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
416   const MCSection *Sec = getCurrentSection().first;
417   assert(Sec && "need a section");
418   unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
419   insert(new MCFillFragment(0, ItemSize, NumBytes));
420 }
421
422 void MCObjectStreamer::FinishImpl() {
423   // If we are generating dwarf for assembly source files dump out the sections.
424   if (getContext().getGenDwarfForAssembly())
425     MCGenDwarfInfo::Emit(this);
426
427   // Dump out the dwarf file & directory tables and line tables.
428   MCDwarfLineTable::Emit(this);
429
430   flushPendingLabels(nullptr);
431   getAssembler().Finish();
432 }