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