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