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