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