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