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