LLVM API Documentation

MCObjectStreamer.cpp
Go to the documentation of this file.
00001 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/MC/MCObjectStreamer.h"
00011 #include "llvm/ADT/STLExtras.h"
00012 #include "llvm/MC/MCAsmBackend.h"
00013 #include "llvm/MC/MCAsmInfo.h"
00014 #include "llvm/MC/MCAssembler.h"
00015 #include "llvm/MC/MCCodeEmitter.h"
00016 #include "llvm/MC/MCContext.h"
00017 #include "llvm/MC/MCDwarf.h"
00018 #include "llvm/MC/MCExpr.h"
00019 #include "llvm/MC/MCObjectWriter.h"
00020 #include "llvm/MC/MCSection.h"
00021 #include "llvm/MC/MCSymbol.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 using namespace llvm;
00024 
00025 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
00026                                    raw_ostream &OS, MCCodeEmitter *Emitter_)
00027     : MCStreamer(Context),
00028       Assembler(new MCAssembler(Context, TAB, *Emitter_,
00029                                 *TAB.createObjectWriter(OS), OS)),
00030       CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
00031 
00032 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
00033                                    raw_ostream &OS, MCCodeEmitter *Emitter_,
00034                                    MCAssembler *_Assembler)
00035     : MCStreamer(Context), Assembler(_Assembler), CurSectionData(nullptr),
00036       EmitEHFrame(true), EmitDebugFrame(false) {}
00037 
00038 MCObjectStreamer::~MCObjectStreamer() {
00039   delete &Assembler->getBackend();
00040   delete &Assembler->getEmitter();
00041   delete &Assembler->getWriter();
00042   delete Assembler;
00043 }
00044 
00045 void MCObjectStreamer::reset() {
00046   if (Assembler)
00047     Assembler->reset();
00048   CurSectionData = nullptr;
00049   CurInsertionPoint = MCSectionData::iterator();
00050   EmitEHFrame = true;
00051   EmitDebugFrame = false;
00052   MCStreamer::reset();
00053 }
00054 
00055 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
00056   if (!getNumFrameInfos())
00057     return;
00058 
00059   if (EmitEHFrame)
00060     MCDwarfFrameEmitter::Emit(*this, MAB, true);
00061 
00062   if (EmitDebugFrame)
00063     MCDwarfFrameEmitter::Emit(*this, MAB, false);
00064 }
00065 
00066 MCFragment *MCObjectStreamer::getCurrentFragment() const {
00067   assert(getCurrentSectionData() && "No current section!");
00068 
00069   if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
00070     return std::prev(CurInsertionPoint);
00071 
00072   return nullptr;
00073 }
00074 
00075 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
00076   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
00077   // When bundling is enabled, we don't want to add data to a fragment that
00078   // already has instructions (see MCELFStreamer::EmitInstToData for details)
00079   if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
00080     F = new MCDataFragment();
00081     insert(F);
00082   }
00083   return F;
00084 }
00085 
00086 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
00087   Assembler->getOrCreateSymbolData(Sym);
00088 }
00089 
00090 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
00091   MCStreamer::EmitCFISections(EH, Debug);
00092   EmitEHFrame = EH;
00093   EmitDebugFrame = Debug;
00094 }
00095 
00096 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
00097                                      const SMLoc &Loc) {
00098   MCStreamer::EmitValueImpl(Value, Size, Loc);
00099   MCDataFragment *DF = getOrCreateDataFragment();
00100 
00101   MCLineEntry::Make(this, getCurrentSection().first);
00102 
00103   // Avoid fixups when possible.
00104   int64_t AbsValue;
00105   if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
00106     EmitIntValue(AbsValue, Size);
00107     return;
00108   }
00109   DF->getFixups().push_back(
00110       MCFixup::Create(DF->getContents().size(), Value,
00111                       MCFixup::getKindForSize(Size, false), Loc));
00112   DF->getContents().resize(DF->getContents().size() + Size, 0);
00113 }
00114 
00115 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
00116   // We need to create a local symbol to avoid relocations.
00117   Frame.Begin = getContext().CreateTempSymbol();
00118   EmitLabel(Frame.Begin);
00119 }
00120 
00121 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
00122   Frame.End = getContext().CreateTempSymbol();
00123   EmitLabel(Frame.End);
00124 }
00125 
00126 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
00127   MCStreamer::EmitLabel(Symbol);
00128 
00129   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
00130 
00131   // FIXME: This is wasteful, we don't necessarily need to create a data
00132   // fragment. Instead, we should mark the symbol as pointing into the data
00133   // fragment if it exists, otherwise we should just queue the label and set its
00134   // fragment pointer when we emit the next fragment.
00135   MCDataFragment *F = getOrCreateDataFragment();
00136   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
00137   SD.setFragment(F);
00138   SD.setOffset(F->getContents().size());
00139 }
00140 
00141 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
00142   int64_t IntValue;
00143   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
00144     EmitULEB128IntValue(IntValue);
00145     return;
00146   }
00147   insert(new MCLEBFragment(*Value, false));
00148 }
00149 
00150 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
00151   int64_t IntValue;
00152   if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
00153     EmitSLEB128IntValue(IntValue);
00154     return;
00155   }
00156   insert(new MCLEBFragment(*Value, true));
00157 }
00158 
00159 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
00160                                          const MCSymbol *Symbol) {
00161   report_fatal_error("This file format doesn't support weak aliases.");
00162 }
00163 
00164 void MCObjectStreamer::ChangeSection(const MCSection *Section,
00165                                      const MCExpr *Subsection) {
00166   assert(Section && "Cannot switch to a null section!");
00167 
00168   CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
00169 
00170   int64_t IntSubsection = 0;
00171   if (Subsection &&
00172       !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
00173     report_fatal_error("Cannot evaluate subsection number");
00174   if (IntSubsection < 0 || IntSubsection > 8192)
00175     report_fatal_error("Subsection number out of range");
00176   CurInsertionPoint =
00177     CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
00178 }
00179 
00180 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
00181   getAssembler().getOrCreateSymbolData(*Symbol);
00182   MCStreamer::EmitAssignment(Symbol, Value);
00183 }
00184 
00185 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
00186                                        const MCSubtargetInfo &STI) {
00187   MCStreamer::EmitInstruction(Inst, STI);
00188 
00189   MCSectionData *SD = getCurrentSectionData();
00190   SD->setHasInstructions(true);
00191 
00192   // Now that a machine instruction has been assembled into this section, make
00193   // a line entry for any .loc directive that has been seen.
00194   MCLineEntry::Make(this, getCurrentSection().first);
00195 
00196   // If this instruction doesn't need relaxation, just emit it as data.
00197   MCAssembler &Assembler = getAssembler();
00198   if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
00199     EmitInstToData(Inst, STI);
00200     return;
00201   }
00202 
00203   // Otherwise, relax and emit it as data if either:
00204   // - The RelaxAll flag was passed
00205   // - Bundling is enabled and this instruction is inside a bundle-locked
00206   //   group. We want to emit all such instructions into the same data
00207   //   fragment.
00208   if (Assembler.getRelaxAll() ||
00209       (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
00210     MCInst Relaxed;
00211     getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
00212     while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
00213       getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
00214     EmitInstToData(Relaxed, STI);
00215     return;
00216   }
00217 
00218   // Otherwise emit to a separate fragment.
00219   EmitInstToFragment(Inst, STI);
00220 }
00221 
00222 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
00223                                           const MCSubtargetInfo &STI) {
00224   // Always create a new, separate fragment here, because its size can change
00225   // during relaxation.
00226   MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
00227   insert(IF);
00228 
00229   SmallString<128> Code;
00230   raw_svector_ostream VecOS(Code);
00231   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
00232                                                 STI);
00233   VecOS.flush();
00234   IF->getContents().append(Code.begin(), Code.end());
00235 }
00236 
00237 #ifndef NDEBUG
00238 static const char *const BundlingNotImplementedMsg =
00239   "Aligned bundling is not implemented for this object format";
00240 #endif
00241 
00242 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
00243   llvm_unreachable(BundlingNotImplementedMsg);
00244 }
00245 
00246 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
00247   llvm_unreachable(BundlingNotImplementedMsg);
00248 }
00249 
00250 void MCObjectStreamer::EmitBundleUnlock() {
00251   llvm_unreachable(BundlingNotImplementedMsg);
00252 }
00253 
00254 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
00255                                              unsigned Column, unsigned Flags,
00256                                              unsigned Isa,
00257                                              unsigned Discriminator,
00258                                              StringRef FileName) {
00259   // In case we see two .loc directives in a row, make sure the
00260   // first one gets a line entry.
00261   MCLineEntry::Make(this, getCurrentSection().first);
00262 
00263   this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
00264                                           Isa, Discriminator, FileName);
00265 }
00266 
00267 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
00268                                      const MCSymbol *B) {
00269   MCContext &Context = OS.getContext();
00270   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
00271   const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
00272   const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
00273   const MCExpr *AddrDelta =
00274       MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
00275   return AddrDelta;
00276 }
00277 
00278 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
00279                                  const MCSymbol *Label, int PointerSize) {
00280   // emit the sequence to set the address
00281   OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
00282   OS.EmitULEB128IntValue(PointerSize + 1);
00283   OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
00284   OS.EmitSymbolValue(Label, PointerSize);
00285 
00286   // emit the sequence for the LineDelta (from 1) and a zero address delta.
00287   MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
00288 }
00289 
00290 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
00291                                                 const MCSymbol *LastLabel,
00292                                                 const MCSymbol *Label,
00293                                                 unsigned PointerSize) {
00294   if (!LastLabel) {
00295     emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
00296     return;
00297   }
00298   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
00299   int64_t Res;
00300   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
00301     MCDwarfLineAddr::Emit(this, LineDelta, Res);
00302     return;
00303   }
00304   insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
00305 }
00306 
00307 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
00308                                                  const MCSymbol *Label) {
00309   const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
00310   int64_t Res;
00311   if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
00312     MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
00313     return;
00314   }
00315   insert(new MCDwarfCallFrameFragment(*AddrDelta));
00316 }
00317 
00318 void MCObjectStreamer::EmitBytes(StringRef Data) {
00319   MCLineEntry::Make(this, getCurrentSection().first);
00320   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
00321 }
00322 
00323 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
00324                                             int64_t Value,
00325                                             unsigned ValueSize,
00326                                             unsigned MaxBytesToEmit) {
00327   if (MaxBytesToEmit == 0)
00328     MaxBytesToEmit = ByteAlignment;
00329   insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
00330 
00331   // Update the maximum alignment on the current section if necessary.
00332   if (ByteAlignment > getCurrentSectionData()->getAlignment())
00333     getCurrentSectionData()->setAlignment(ByteAlignment);
00334 }
00335 
00336 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
00337                                          unsigned MaxBytesToEmit) {
00338   EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
00339   cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
00340 }
00341 
00342 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
00343                                          unsigned char Value) {
00344   int64_t Res;
00345   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
00346     insert(new MCOrgFragment(*Offset, Value));
00347     return false;
00348   }
00349 
00350   MCSymbol *CurrentPos = getContext().CreateTempSymbol();
00351   EmitLabel(CurrentPos);
00352   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
00353   const MCExpr *Ref =
00354     MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
00355   const MCExpr *Delta =
00356     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
00357 
00358   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
00359     return true;
00360   EmitFill(Res, Value);
00361   return false;
00362 }
00363 
00364 // Associate GPRel32 fixup with data and resize data area
00365 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
00366   MCDataFragment *DF = getOrCreateDataFragment();
00367 
00368   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
00369                                             Value, FK_GPRel_4));
00370   DF->getContents().resize(DF->getContents().size() + 4, 0);
00371 }
00372 
00373 // Associate GPRel32 fixup with data and resize data area
00374 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
00375   MCDataFragment *DF = getOrCreateDataFragment();
00376 
00377   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(), 
00378                                             Value, FK_GPRel_4));
00379   DF->getContents().resize(DF->getContents().size() + 8, 0);
00380 }
00381 
00382 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
00383   // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
00384   //        problems evaluating expressions across multiple fragments.
00385   getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
00386 }
00387 
00388 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
00389   unsigned ItemSize = getCurrentSection().first->isVirtualSection() ? 0 : 1;
00390   insert(new MCFillFragment(0, ItemSize, NumBytes));
00391 }
00392 
00393 void MCObjectStreamer::FinishImpl() {
00394   // If we are generating dwarf for assembly source files dump out the sections.
00395   if (getContext().getGenDwarfForAssembly())
00396     MCGenDwarfInfo::Emit(this);
00397 
00398   // Dump out the dwarf file & directory tables and line tables.
00399   MCDwarfLineTable::Emit(this);
00400 
00401   getAssembler().Finish();
00402 }