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