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