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