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