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))),
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.empty())
43     return;
44   if (!F) {
45     F = new MCDataFragment();
46     MCSection *CurSection = getCurrentSectionOnly();
47     CurSection->getFragmentList().insert(CurInsertionPoint, F);
48     F->setParent(CurSection);
49   }
50   for (MCSymbol *Sym : PendingLabels) {
51     Sym->setFragment(F);
52     Sym->setOffset(FOffset);
53   }
54   PendingLabels.clear();
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       Hi->isVariable() || Lo->isVariable()) {
63     MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
64     return;
65   }
66 
67   EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
68 }
69 
70 void MCObjectStreamer::reset() {
71   if (Assembler)
72     Assembler->reset();
73   CurInsertionPoint = MCSection::iterator();
74   EmitEHFrame = true;
75   EmitDebugFrame = false;
76   PendingLabels.clear();
77   MCStreamer::reset();
78 }
79 
80 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
81   if (!getNumFrameInfos())
82     return;
83 
84   if (EmitEHFrame)
85     MCDwarfFrameEmitter::Emit(*this, MAB, true);
86 
87   if (EmitDebugFrame)
88     MCDwarfFrameEmitter::Emit(*this, MAB, false);
89 }
90 
91 MCFragment *MCObjectStreamer::getCurrentFragment() const {
92   assert(getCurrentSectionOnly() && "No current section!");
93 
94   if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
95     return &*std::prev(CurInsertionPoint);
96 
97   return nullptr;
98 }
99 
100 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
101   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
102   // When bundling is enabled, we don't want to add data to a fragment that
103   // already has instructions (see MCELFStreamer::EmitInstToData for details)
104   if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
105              F->hasInstructions())) {
106     F = new MCDataFragment();
107     insert(F);
108   }
109   return F;
110 }
111 
112 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
113   Assembler->registerSymbol(Sym);
114 }
115 
116 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
117   MCStreamer::EmitCFISections(EH, Debug);
118   EmitEHFrame = EH;
119   EmitDebugFrame = Debug;
120 }
121 
122 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
123                                      SMLoc Loc) {
124   MCStreamer::EmitValueImpl(Value, Size, Loc);
125   MCDataFragment *DF = getOrCreateDataFragment();
126   flushPendingLabels(DF, DF->getContents().size());
127 
128   MCCVLineEntry::Make(this);
129   MCDwarfLineEntry::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 
159   // If there is a current fragment, mark the symbol as pointing into it.
160   // Otherwise queue the label and set its fragment pointer when we emit the
161   // next fragment.
162   auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
163   if (F && !(getAssembler().isBundlingEnabled() &&
164              getAssembler().getRelaxAll())) {
165     Symbol->setFragment(F);
166     Symbol->setOffset(F->getContents().size());
167   } else {
168     PendingLabels.push_back(Symbol);
169   }
170 }
171 
172 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
173   int64_t IntValue;
174   if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
175     EmitULEB128IntValue(IntValue);
176     return;
177   }
178   insert(new MCLEBFragment(*Value, false));
179 }
180 
181 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
182   int64_t IntValue;
183   if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
184     EmitSLEB128IntValue(IntValue);
185     return;
186   }
187   insert(new MCLEBFragment(*Value, true));
188 }
189 
190 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
191                                          const MCSymbol *Symbol) {
192   report_fatal_error("This file format doesn't support weak aliases.");
193 }
194 
195 void MCObjectStreamer::ChangeSection(MCSection *Section,
196                                      const MCExpr *Subsection) {
197   changeSectionImpl(Section, Subsection);
198 }
199 
200 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
201                                          const MCExpr *Subsection) {
202   assert(Section && "Cannot switch to a null section!");
203   flushPendingLabels(nullptr);
204 
205   bool Created = getAssembler().registerSection(*Section);
206 
207   int64_t IntSubsection = 0;
208   if (Subsection &&
209       !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
210     report_fatal_error("Cannot evaluate subsection number");
211   if (IntSubsection < 0 || IntSubsection > 8192)
212     report_fatal_error("Subsection number out of range");
213   CurInsertionPoint =
214       Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
215   return Created;
216 }
217 
218 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
219   getAssembler().registerSymbol(*Symbol);
220   MCStreamer::EmitAssignment(Symbol, Value);
221 }
222 
223 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
224   return Sec.hasInstructions();
225 }
226 
227 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
228                                        const MCSubtargetInfo &STI) {
229   MCStreamer::EmitInstruction(Inst, STI);
230 
231   MCSection *Sec = getCurrentSectionOnly();
232   Sec->setHasInstructions(true);
233 
234   // Now that a machine instruction has been assembled into this section, make
235   // a line entry for any .loc directive that has been seen.
236   MCCVLineEntry::Make(this);
237   MCDwarfLineEntry::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   IF->getContents().append(Code.begin(), Code.end());
280 }
281 
282 #ifndef NDEBUG
283 static const char *const BundlingNotImplementedMsg =
284   "Aligned bundling is not implemented for this object format";
285 #endif
286 
287 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
288   llvm_unreachable(BundlingNotImplementedMsg);
289 }
290 
291 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
292   llvm_unreachable(BundlingNotImplementedMsg);
293 }
294 
295 void MCObjectStreamer::EmitBundleUnlock() {
296   llvm_unreachable(BundlingNotImplementedMsg);
297 }
298 
299 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
300                                              unsigned Column, unsigned Flags,
301                                              unsigned Isa,
302                                              unsigned Discriminator,
303                                              StringRef FileName) {
304   // In case we see two .loc directives in a row, make sure the
305   // first one gets a line entry.
306   MCDwarfLineEntry::Make(this, getCurrentSection().first);
307 
308   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
309                                           Isa, Discriminator, FileName);
310 }
311 
312 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
313                                      const MCSymbol *B) {
314   MCContext &Context = OS.getContext();
315   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
316   const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
317   const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
318   const MCExpr *AddrDelta =
319       MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
320   return AddrDelta;
321 }
322 
323 static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
324                                  MCDwarfLineTableParams Params,
325                                  int64_t LineDelta, const MCSymbol *Label,
326                                  int PointerSize) {
327   // emit the sequence to set the address
328   OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
329   OS.EmitULEB128IntValue(PointerSize + 1);
330   OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
331   OS.EmitSymbolValue(Label, PointerSize);
332 
333   // emit the sequence for the LineDelta (from 1) and a zero address delta.
334   MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
335 }
336 
337 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
338                                                 const MCSymbol *LastLabel,
339                                                 const MCSymbol *Label,
340                                                 unsigned PointerSize) {
341   if (!LastLabel) {
342     emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
343                          Label, PointerSize);
344     return;
345   }
346   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
347   int64_t Res;
348   if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
349     MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta,
350                           Res);
351     return;
352   }
353   insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
354 }
355 
356 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
357                                                  const MCSymbol *Label) {
358   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
359   int64_t Res;
360   if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
361     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
362     return;
363   }
364   insert(new MCDwarfCallFrameFragment(*AddrDelta));
365 }
366 
367 void MCObjectStreamer::EmitCVLocDirective(unsigned FunctionId, unsigned FileNo,
368                                           unsigned Line, unsigned Column,
369                                           bool PrologueEnd, bool IsStmt,
370                                           StringRef FileName) {
371   // In case we see two .cv_loc directives in a row, make sure the
372   // first one gets a line entry.
373   MCCVLineEntry::Make(this);
374 
375   this->MCStreamer::EmitCVLocDirective(FunctionId, FileNo, Line, Column,
376                                        PrologueEnd, IsStmt, FileName);
377 }
378 
379 void MCObjectStreamer::EmitCVLinetableDirective(unsigned FunctionId,
380                                                 const MCSymbol *Begin,
381                                                 const MCSymbol *End) {
382   getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin,
383                                                        End);
384   this->MCStreamer::EmitCVLinetableDirective(FunctionId, Begin, End);
385 }
386 
387 void MCObjectStreamer::EmitCVInlineLinetableDirective(
388     unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum,
389     const MCSymbol *FnStartSym, const MCSymbol *FnEndSym,
390     ArrayRef<unsigned> SecondaryFunctionIds) {
391   getContext().getCVContext().emitInlineLineTableForFunction(
392       *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym,
393       FnEndSym, SecondaryFunctionIds);
394   this->MCStreamer::EmitCVInlineLinetableDirective(
395       PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym,
396       SecondaryFunctionIds);
397 }
398 
399 void MCObjectStreamer::EmitCVDefRangeDirective(
400     ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
401     StringRef FixedSizePortion) {
402   getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion);
403   this->MCStreamer::EmitCVDefRangeDirective(Ranges, FixedSizePortion);
404 }
405 
406 void MCObjectStreamer::EmitCVStringTableDirective() {
407   getContext().getCVContext().emitStringTable(*this);
408 }
409 void MCObjectStreamer::EmitCVFileChecksumsDirective() {
410   getContext().getCVContext().emitFileChecksums(*this);
411 }
412 
413 
414 void MCObjectStreamer::EmitBytes(StringRef Data) {
415   MCCVLineEntry::Make(this);
416   MCDwarfLineEntry::Make(this, getCurrentSection().first);
417   MCDataFragment *DF = getOrCreateDataFragment();
418   flushPendingLabels(DF, DF->getContents().size());
419   DF->getContents().append(Data.begin(), Data.end());
420 }
421 
422 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
423                                             int64_t Value,
424                                             unsigned ValueSize,
425                                             unsigned MaxBytesToEmit) {
426   if (MaxBytesToEmit == 0)
427     MaxBytesToEmit = ByteAlignment;
428   insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
429 
430   // Update the maximum alignment on the current section if necessary.
431   MCSection *CurSec = getCurrentSection().first;
432   if (ByteAlignment > CurSec->getAlignment())
433     CurSec->setAlignment(ByteAlignment);
434 }
435 
436 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
437                                          unsigned MaxBytesToEmit) {
438   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
439   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
440 }
441 
442 void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
443                                          unsigned char Value) {
444   insert(new MCOrgFragment(*Offset, Value));
445 }
446 
447 // Associate GPRel32 fixup with data and resize data area
448 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
449   MCDataFragment *DF = getOrCreateDataFragment();
450   flushPendingLabels(DF, DF->getContents().size());
451 
452   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
453                                             Value, FK_GPRel_4));
454   DF->getContents().resize(DF->getContents().size() + 4, 0);
455 }
456 
457 // Associate GPRel32 fixup with data and resize data area
458 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
459   MCDataFragment *DF = getOrCreateDataFragment();
460   flushPendingLabels(DF, DF->getContents().size());
461 
462   DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
463                                             Value, FK_GPRel_4));
464   DF->getContents().resize(DF->getContents().size() + 8, 0);
465 }
466 
467 bool MCObjectStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
468                                           const MCExpr *Expr, SMLoc Loc) {
469   int64_t OffsetValue;
470   if (!Offset.evaluateAsAbsolute(OffsetValue))
471     llvm_unreachable("Offset is not absolute");
472 
473   if (OffsetValue < 0)
474     llvm_unreachable("Offset is negative");
475 
476   MCDataFragment *DF = getOrCreateDataFragment();
477   flushPendingLabels(DF, DF->getContents().size());
478 
479   Optional<MCFixupKind> MaybeKind = Assembler->getBackend().getFixupKind(Name);
480   if (!MaybeKind.hasValue())
481     return true;
482 
483   MCFixupKind Kind = *MaybeKind;
484 
485   if (Expr == nullptr)
486     Expr =
487         MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
488   DF->getFixups().push_back(MCFixup::create(OffsetValue, Expr, Kind, Loc));
489   return false;
490 }
491 
492 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
493   const MCSection *Sec = getCurrentSection().first;
494   (void)Sec;
495   assert(Sec && "need a section");
496   insert(new MCFillFragment(FillValue, NumBytes));
497 }
498 
499 void MCObjectStreamer::FinishImpl() {
500   // If we are generating dwarf for assembly source files dump out the sections.
501   if (getContext().getGenDwarfForAssembly())
502     MCGenDwarfInfo::Emit(this);
503 
504   // Dump out the dwarf file & directory tables and line tables.
505   MCDwarfLineTable::Emit(this, getAssembler().getDWARFLinetableParams());
506 
507   flushPendingLabels(nullptr);
508   getAssembler().Finish();
509 }
510