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