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