MCObjectStreamer.cpp 14 KB

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