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