MCObjectStreamer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/MC/MCObjectStreamer.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/MC/MCAsmBackend.h"
  11. #include "llvm/MC/MCAsmInfo.h"
  12. #include "llvm/MC/MCAssembler.h"
  13. #include "llvm/MC/MCCodeEmitter.h"
  14. #include "llvm/MC/MCCodeView.h"
  15. #include "llvm/MC/MCContext.h"
  16. #include "llvm/MC/MCDwarf.h"
  17. #include "llvm/MC/MCExpr.h"
  18. #include "llvm/MC/MCObjectFileInfo.h"
  19. #include "llvm/MC/MCObjectWriter.h"
  20. #include "llvm/MC/MCSection.h"
  21. #include "llvm/MC/MCSymbol.h"
  22. #include "llvm/MC/MCValue.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/SourceMgr.h"
  25. using namespace llvm;
  26. MCObjectStreamer::MCObjectStreamer(MCContext &Context,
  27. std::unique_ptr<MCAsmBackend> TAB,
  28. std::unique_ptr<MCObjectWriter> OW,
  29. std::unique_ptr<MCCodeEmitter> Emitter)
  30. : MCStreamer(Context),
  31. Assembler(std::make_unique<MCAssembler>(
  32. Context, std::move(TAB), std::move(Emitter), std::move(OW))),
  33. EmitEHFrame(true), EmitDebugFrame(false) {
  34. if (Assembler->getBackendPtr())
  35. setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
  36. }
  37. MCObjectStreamer::~MCObjectStreamer() {}
  38. // AssemblerPtr is used for evaluation of expressions and causes
  39. // difference between asm and object outputs. Return nullptr to in
  40. // inline asm mode to limit divergence to assembly inputs.
  41. MCAssembler *MCObjectStreamer::getAssemblerPtr() {
  42. if (getUseAssemblerInfoForParsing())
  43. return Assembler.get();
  44. return nullptr;
  45. }
  46. void MCObjectStreamer::addPendingLabel(MCSymbol* S) {
  47. MCSection *CurSection = getCurrentSectionOnly();
  48. if (CurSection) {
  49. // Register labels that have not yet been assigned to a Section.
  50. if (!PendingLabels.empty()) {
  51. for (MCSymbol* Sym : PendingLabels)
  52. CurSection->addPendingLabel(Sym);
  53. PendingLabels.clear();
  54. }
  55. // Add this label to the current Section / Subsection.
  56. CurSection->addPendingLabel(S, CurSubsectionIdx);
  57. // Add this Section to the list of PendingLabelSections.
  58. PendingLabelSections.insert(CurSection);
  59. } else
  60. // There is no Section / Subsection for this label yet.
  61. PendingLabels.push_back(S);
  62. }
  63. void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
  64. MCSection *CurSection = getCurrentSectionOnly();
  65. if (!CurSection) {
  66. assert(PendingLabels.empty());
  67. return;
  68. }
  69. // Register labels that have not yet been assigned to a Section.
  70. if (!PendingLabels.empty()) {
  71. for (MCSymbol* Sym : PendingLabels)
  72. CurSection->addPendingLabel(Sym, CurSubsectionIdx);
  73. PendingLabels.clear();
  74. }
  75. // Associate a fragment with this label, either the supplied fragment
  76. // or an empty data fragment.
  77. if (F)
  78. CurSection->flushPendingLabels(F, FOffset, CurSubsectionIdx);
  79. else
  80. CurSection->flushPendingLabels(nullptr, 0, CurSubsectionIdx);
  81. }
  82. void MCObjectStreamer::flushPendingLabels() {
  83. // Register labels that have not yet been assigned to a Section.
  84. if (!PendingLabels.empty()) {
  85. MCSection *CurSection = getCurrentSectionOnly();
  86. assert(CurSection);
  87. for (MCSymbol* Sym : PendingLabels)
  88. CurSection->addPendingLabel(Sym, CurSubsectionIdx);
  89. PendingLabels.clear();
  90. }
  91. // Assign an empty data fragment to all remaining pending labels.
  92. for (MCSection* Section : PendingLabelSections)
  93. Section->flushPendingLabels();
  94. }
  95. // When fixup's offset is a forward declared label, e.g.:
  96. //
  97. // .reloc 1f, R_MIPS_JALR, foo
  98. // 1: nop
  99. //
  100. // postpone adding it to Fixups vector until the label is defined and its offset
  101. // is known.
  102. void MCObjectStreamer::resolvePendingFixups() {
  103. for (PendingMCFixup &PendingFixup : PendingFixups) {
  104. if (!PendingFixup.Sym || PendingFixup.Sym->isUndefined ()) {
  105. getContext().reportError(PendingFixup.Fixup.getLoc(),
  106. "unresolved relocation offset");
  107. continue;
  108. }
  109. flushPendingLabels(PendingFixup.DF, PendingFixup.DF->getContents().size());
  110. PendingFixup.Fixup.setOffset(PendingFixup.Sym->getOffset() +
  111. PendingFixup.Fixup.getOffset());
  112. // If the location symbol to relocate is in MCEncodedFragmentWithFixups,
  113. // put the Fixup into location symbol's fragment. Otherwise
  114. // put into PendingFixup.DF
  115. MCFragment *SymFragment = PendingFixup.Sym->getFragment();
  116. switch (SymFragment->getKind()) {
  117. case MCFragment::FT_Relaxable:
  118. case MCFragment::FT_Dwarf:
  119. case MCFragment::FT_PseudoProbe:
  120. cast<MCEncodedFragmentWithFixups<8, 1>>(SymFragment)
  121. ->getFixups()
  122. .push_back(PendingFixup.Fixup);
  123. break;
  124. case MCFragment::FT_Data:
  125. case MCFragment::FT_CVDefRange:
  126. cast<MCEncodedFragmentWithFixups<32, 4>>(SymFragment)
  127. ->getFixups()
  128. .push_back(PendingFixup.Fixup);
  129. break;
  130. default:
  131. PendingFixup.DF->getFixups().push_back(PendingFixup.Fixup);
  132. break;
  133. }
  134. }
  135. PendingFixups.clear();
  136. }
  137. // As a compile-time optimization, avoid allocating and evaluating an MCExpr
  138. // tree for (Hi - Lo) when Hi and Lo are offsets into the same fragment.
  139. static Optional<uint64_t> absoluteSymbolDiff(const MCSymbol *Hi,
  140. const MCSymbol *Lo) {
  141. assert(Hi && Lo);
  142. if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
  143. Hi->isVariable() || Lo->isVariable())
  144. return None;
  145. return Hi->getOffset() - Lo->getOffset();
  146. }
  147. void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
  148. const MCSymbol *Lo,
  149. unsigned Size) {
  150. if (!getAssembler().getContext().getTargetTriple().isRISCV())
  151. if (Optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo))
  152. return emitIntValue(*Diff, Size);
  153. MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
  154. }
  155. void MCObjectStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
  156. const MCSymbol *Lo) {
  157. if (!getAssembler().getContext().getTargetTriple().isRISCV())
  158. if (Optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo))
  159. return emitULEB128IntValue(*Diff);
  160. MCStreamer::emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
  161. }
  162. void MCObjectStreamer::reset() {
  163. if (Assembler)
  164. Assembler->reset();
  165. CurInsertionPoint = MCSection::iterator();
  166. EmitEHFrame = true;
  167. EmitDebugFrame = false;
  168. PendingLabels.clear();
  169. PendingLabelSections.clear();
  170. MCStreamer::reset();
  171. }
  172. void MCObjectStreamer::emitFrames(MCAsmBackend *MAB) {
  173. if (!getNumFrameInfos())
  174. return;
  175. if (EmitEHFrame)
  176. MCDwarfFrameEmitter::Emit(*this, MAB, true);
  177. if (EmitDebugFrame)
  178. MCDwarfFrameEmitter::Emit(*this, MAB, false);
  179. }
  180. MCFragment *MCObjectStreamer::getCurrentFragment() const {
  181. assert(getCurrentSectionOnly() && "No current section!");
  182. if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
  183. return &*std::prev(CurInsertionPoint);
  184. return nullptr;
  185. }
  186. static bool canReuseDataFragment(const MCDataFragment &F,
  187. const MCAssembler &Assembler,
  188. const MCSubtargetInfo *STI) {
  189. if (!F.hasInstructions())
  190. return true;
  191. // When bundling is enabled, we don't want to add data to a fragment that
  192. // already has instructions (see MCELFStreamer::emitInstToData for details)
  193. if (Assembler.isBundlingEnabled())
  194. return Assembler.getRelaxAll();
  195. // If the subtarget is changed mid fragment we start a new fragment to record
  196. // the new STI.
  197. return !STI || F.getSubtargetInfo() == STI;
  198. }
  199. MCDataFragment *
  200. MCObjectStreamer::getOrCreateDataFragment(const MCSubtargetInfo *STI) {
  201. MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
  202. if (!F || !canReuseDataFragment(*F, *Assembler, STI)) {
  203. F = new MCDataFragment();
  204. insert(F);
  205. }
  206. return F;
  207. }
  208. void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
  209. Assembler->registerSymbol(Sym);
  210. }
  211. void MCObjectStreamer::emitCFISections(bool EH, bool Debug) {
  212. MCStreamer::emitCFISections(EH, Debug);
  213. EmitEHFrame = EH;
  214. EmitDebugFrame = Debug;
  215. }
  216. void MCObjectStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
  217. SMLoc Loc) {
  218. MCStreamer::emitValueImpl(Value, Size, Loc);
  219. MCDataFragment *DF = getOrCreateDataFragment();
  220. flushPendingLabels(DF, DF->getContents().size());
  221. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  222. // Avoid fixups when possible.
  223. int64_t AbsValue;
  224. if (Value->evaluateAsAbsolute(AbsValue, getAssemblerPtr())) {
  225. if (!isUIntN(8 * Size, AbsValue) && !isIntN(8 * Size, AbsValue)) {
  226. getContext().reportError(
  227. Loc, "value evaluated as " + Twine(AbsValue) + " is out of range.");
  228. return;
  229. }
  230. emitIntValue(AbsValue, Size);
  231. return;
  232. }
  233. DF->getFixups().push_back(
  234. MCFixup::create(DF->getContents().size(), Value,
  235. MCFixup::getKindForSize(Size, false), Loc));
  236. DF->getContents().resize(DF->getContents().size() + Size, 0);
  237. }
  238. MCSymbol *MCObjectStreamer::emitCFILabel() {
  239. MCSymbol *Label = getContext().createTempSymbol("cfi");
  240. emitLabel(Label);
  241. return Label;
  242. }
  243. void MCObjectStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
  244. // We need to create a local symbol to avoid relocations.
  245. Frame.Begin = getContext().createTempSymbol();
  246. emitLabel(Frame.Begin);
  247. }
  248. void MCObjectStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
  249. Frame.End = getContext().createTempSymbol();
  250. emitLabel(Frame.End);
  251. }
  252. void MCObjectStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
  253. MCStreamer::emitLabel(Symbol, Loc);
  254. getAssembler().registerSymbol(*Symbol);
  255. // If there is a current fragment, mark the symbol as pointing into it.
  256. // Otherwise queue the label and set its fragment pointer when we emit the
  257. // next fragment.
  258. auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
  259. if (F && !(getAssembler().isBundlingEnabled() &&
  260. getAssembler().getRelaxAll())) {
  261. Symbol->setFragment(F);
  262. Symbol->setOffset(F->getContents().size());
  263. } else {
  264. // Assign all pending labels to offset 0 within the dummy "pending"
  265. // fragment. (They will all be reassigned to a real fragment in
  266. // flushPendingLabels())
  267. Symbol->setOffset(0);
  268. addPendingLabel(Symbol);
  269. }
  270. emitPendingAssignments(Symbol);
  271. }
  272. void MCObjectStreamer::emitPendingAssignments(MCSymbol *Symbol) {
  273. auto Assignments = pendingAssignments.find(Symbol);
  274. if (Assignments != pendingAssignments.end()) {
  275. for (const PendingAssignment &A : Assignments->second)
  276. emitAssignment(A.Symbol, A.Value);
  277. pendingAssignments.erase(Assignments);
  278. }
  279. }
  280. // Emit a label at a previously emitted fragment/offset position. This must be
  281. // within the currently-active section.
  282. void MCObjectStreamer::emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc,
  283. MCFragment *F, uint64_t Offset) {
  284. assert(F->getParent() == getCurrentSectionOnly());
  285. MCStreamer::emitLabel(Symbol, Loc);
  286. getAssembler().registerSymbol(*Symbol);
  287. auto *DF = dyn_cast_or_null<MCDataFragment>(F);
  288. Symbol->setOffset(Offset);
  289. if (DF) {
  290. Symbol->setFragment(F);
  291. } else {
  292. assert(isa<MCDummyFragment>(F) &&
  293. "F must either be an MCDataFragment or the pending MCDummyFragment");
  294. assert(Offset == 0);
  295. addPendingLabel(Symbol);
  296. }
  297. }
  298. void MCObjectStreamer::emitULEB128Value(const MCExpr *Value) {
  299. int64_t IntValue;
  300. if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) {
  301. emitULEB128IntValue(IntValue);
  302. return;
  303. }
  304. insert(new MCLEBFragment(*Value, false));
  305. }
  306. void MCObjectStreamer::emitSLEB128Value(const MCExpr *Value) {
  307. int64_t IntValue;
  308. if (Value->evaluateAsAbsolute(IntValue, getAssemblerPtr())) {
  309. emitSLEB128IntValue(IntValue);
  310. return;
  311. }
  312. insert(new MCLEBFragment(*Value, true));
  313. }
  314. void MCObjectStreamer::emitWeakReference(MCSymbol *Alias,
  315. const MCSymbol *Symbol) {
  316. report_fatal_error("This file format doesn't support weak aliases.");
  317. }
  318. void MCObjectStreamer::changeSection(MCSection *Section,
  319. const MCExpr *Subsection) {
  320. changeSectionImpl(Section, Subsection);
  321. }
  322. bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
  323. const MCExpr *Subsection) {
  324. assert(Section && "Cannot switch to a null section!");
  325. getContext().clearDwarfLocSeen();
  326. bool Created = getAssembler().registerSection(*Section);
  327. int64_t IntSubsection = 0;
  328. if (Subsection &&
  329. !Subsection->evaluateAsAbsolute(IntSubsection, getAssemblerPtr()))
  330. report_fatal_error("Cannot evaluate subsection number");
  331. if (IntSubsection < 0 || IntSubsection > 8192)
  332. report_fatal_error("Subsection number out of range");
  333. CurSubsectionIdx = unsigned(IntSubsection);
  334. CurInsertionPoint =
  335. Section->getSubsectionInsertionPoint(CurSubsectionIdx);
  336. return Created;
  337. }
  338. void MCObjectStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  339. getAssembler().registerSymbol(*Symbol);
  340. MCStreamer::emitAssignment(Symbol, Value);
  341. emitPendingAssignments(Symbol);
  342. }
  343. void MCObjectStreamer::emitConditionalAssignment(MCSymbol *Symbol,
  344. const MCExpr *Value) {
  345. const MCSymbol *Target = &cast<MCSymbolRefExpr>(*Value).getSymbol();
  346. // If the symbol already exists, emit the assignment. Otherwise, emit it
  347. // later only if the symbol is also emitted.
  348. if (Target->isRegistered())
  349. emitAssignment(Symbol, Value);
  350. else
  351. pendingAssignments[Target].push_back({Symbol, Value});
  352. }
  353. bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
  354. return Sec.hasInstructions();
  355. }
  356. void MCObjectStreamer::emitInstruction(const MCInst &Inst,
  357. const MCSubtargetInfo &STI) {
  358. const MCSection &Sec = *getCurrentSectionOnly();
  359. if (Sec.isVirtualSection()) {
  360. getContext().reportError(Inst.getLoc(), Twine(Sec.getVirtualSectionKind()) +
  361. " section '" + Sec.getName() +
  362. "' cannot have instructions");
  363. return;
  364. }
  365. getAssembler().getBackend().emitInstructionBegin(*this, Inst, STI);
  366. emitInstructionImpl(Inst, STI);
  367. getAssembler().getBackend().emitInstructionEnd(*this, Inst);
  368. }
  369. void MCObjectStreamer::emitInstructionImpl(const MCInst &Inst,
  370. const MCSubtargetInfo &STI) {
  371. MCStreamer::emitInstruction(Inst, STI);
  372. MCSection *Sec = getCurrentSectionOnly();
  373. Sec->setHasInstructions(true);
  374. // Now that a machine instruction has been assembled into this section, make
  375. // a line entry for any .loc directive that has been seen.
  376. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  377. // If this instruction doesn't need relaxation, just emit it as data.
  378. MCAssembler &Assembler = getAssembler();
  379. MCAsmBackend &Backend = Assembler.getBackend();
  380. if (!(Backend.mayNeedRelaxation(Inst, STI) ||
  381. Backend.allowEnhancedRelaxation())) {
  382. emitInstToData(Inst, STI);
  383. return;
  384. }
  385. // Otherwise, relax and emit it as data if either:
  386. // - The RelaxAll flag was passed
  387. // - Bundling is enabled and this instruction is inside a bundle-locked
  388. // group. We want to emit all such instructions into the same data
  389. // fragment.
  390. if (Assembler.getRelaxAll() ||
  391. (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
  392. MCInst Relaxed = Inst;
  393. while (Backend.mayNeedRelaxation(Relaxed, STI))
  394. Backend.relaxInstruction(Relaxed, STI);
  395. emitInstToData(Relaxed, STI);
  396. return;
  397. }
  398. // Otherwise emit to a separate fragment.
  399. emitInstToFragment(Inst, STI);
  400. }
  401. void MCObjectStreamer::emitInstToFragment(const MCInst &Inst,
  402. const MCSubtargetInfo &STI) {
  403. if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
  404. llvm_unreachable("All instructions should have already been relaxed");
  405. // Always create a new, separate fragment here, because its size can change
  406. // during relaxation.
  407. MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
  408. insert(IF);
  409. SmallString<128> Code;
  410. raw_svector_ostream VecOS(Code);
  411. getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
  412. STI);
  413. IF->getContents().append(Code.begin(), Code.end());
  414. }
  415. #ifndef NDEBUG
  416. static const char *const BundlingNotImplementedMsg =
  417. "Aligned bundling is not implemented for this object format";
  418. #endif
  419. void MCObjectStreamer::emitBundleAlignMode(unsigned AlignPow2) {
  420. llvm_unreachable(BundlingNotImplementedMsg);
  421. }
  422. void MCObjectStreamer::emitBundleLock(bool AlignToEnd) {
  423. llvm_unreachable(BundlingNotImplementedMsg);
  424. }
  425. void MCObjectStreamer::emitBundleUnlock() {
  426. llvm_unreachable(BundlingNotImplementedMsg);
  427. }
  428. void MCObjectStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
  429. unsigned Column, unsigned Flags,
  430. unsigned Isa,
  431. unsigned Discriminator,
  432. StringRef FileName) {
  433. // In case we see two .loc directives in a row, make sure the
  434. // first one gets a line entry.
  435. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  436. this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
  437. Discriminator, FileName);
  438. }
  439. static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
  440. const MCSymbol *B) {
  441. MCContext &Context = OS.getContext();
  442. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  443. const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
  444. const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
  445. const MCExpr *AddrDelta =
  446. MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
  447. return AddrDelta;
  448. }
  449. static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
  450. MCDwarfLineTableParams Params,
  451. int64_t LineDelta, const MCSymbol *Label,
  452. int PointerSize) {
  453. // emit the sequence to set the address
  454. OS.emitIntValue(dwarf::DW_LNS_extended_op, 1);
  455. OS.emitULEB128IntValue(PointerSize + 1);
  456. OS.emitIntValue(dwarf::DW_LNE_set_address, 1);
  457. OS.emitSymbolValue(Label, PointerSize);
  458. // emit the sequence for the LineDelta (from 1) and a zero address delta.
  459. MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
  460. }
  461. void MCObjectStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
  462. const MCSymbol *LastLabel,
  463. const MCSymbol *Label,
  464. unsigned PointerSize) {
  465. if (!LastLabel) {
  466. emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
  467. Label, PointerSize);
  468. return;
  469. }
  470. const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
  471. int64_t Res;
  472. if (AddrDelta->evaluateAsAbsolute(Res, getAssemblerPtr())) {
  473. MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta,
  474. Res);
  475. return;
  476. }
  477. insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
  478. }
  479. void MCObjectStreamer::emitDwarfLineEndEntry(MCSection *Section,
  480. MCSymbol *LastLabel) {
  481. // Emit a DW_LNE_end_sequence for the end of the section.
  482. // Use the section end label to compute the address delta and use INT64_MAX
  483. // as the line delta which is the signal that this is actually a
  484. // DW_LNE_end_sequence.
  485. MCSymbol *SectionEnd = endSection(Section);
  486. // Switch back the dwarf line section, in case endSection had to switch the
  487. // section.
  488. MCContext &Ctx = getContext();
  489. SwitchSection(Ctx.getObjectFileInfo()->getDwarfLineSection());
  490. const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
  491. emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd,
  492. AsmInfo->getCodePointerSize());
  493. }
  494. void MCObjectStreamer::emitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
  495. const MCSymbol *Label) {
  496. const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
  497. int64_t Res;
  498. if (AddrDelta->evaluateAsAbsolute(Res, getAssemblerPtr())) {
  499. MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
  500. return;
  501. }
  502. insert(new MCDwarfCallFrameFragment(*AddrDelta));
  503. }
  504. void MCObjectStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
  505. unsigned Line, unsigned Column,
  506. bool PrologueEnd, bool IsStmt,
  507. StringRef FileName, SMLoc Loc) {
  508. // Validate the directive.
  509. if (!checkCVLocSection(FunctionId, FileNo, Loc))
  510. return;
  511. // Emit a label at the current position and record it in the CodeViewContext.
  512. MCSymbol *LineSym = getContext().createTempSymbol();
  513. emitLabel(LineSym);
  514. getContext().getCVContext().recordCVLoc(getContext(), LineSym, FunctionId,
  515. FileNo, Line, Column, PrologueEnd,
  516. IsStmt);
  517. }
  518. void MCObjectStreamer::emitCVLinetableDirective(unsigned FunctionId,
  519. const MCSymbol *Begin,
  520. const MCSymbol *End) {
  521. getContext().getCVContext().emitLineTableForFunction(*this, FunctionId, Begin,
  522. End);
  523. this->MCStreamer::emitCVLinetableDirective(FunctionId, Begin, End);
  524. }
  525. void MCObjectStreamer::emitCVInlineLinetableDirective(
  526. unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum,
  527. const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) {
  528. getContext().getCVContext().emitInlineLineTableForFunction(
  529. *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym,
  530. FnEndSym);
  531. this->MCStreamer::emitCVInlineLinetableDirective(
  532. PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
  533. }
  534. void MCObjectStreamer::emitCVDefRangeDirective(
  535. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  536. StringRef FixedSizePortion) {
  537. MCFragment *Frag =
  538. getContext().getCVContext().emitDefRange(*this, Ranges, FixedSizePortion);
  539. // Attach labels that were pending before we created the defrange fragment to
  540. // the beginning of the new fragment.
  541. flushPendingLabels(Frag, 0);
  542. this->MCStreamer::emitCVDefRangeDirective(Ranges, FixedSizePortion);
  543. }
  544. void MCObjectStreamer::emitCVStringTableDirective() {
  545. getContext().getCVContext().emitStringTable(*this);
  546. }
  547. void MCObjectStreamer::emitCVFileChecksumsDirective() {
  548. getContext().getCVContext().emitFileChecksums(*this);
  549. }
  550. void MCObjectStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
  551. getContext().getCVContext().emitFileChecksumOffset(*this, FileNo);
  552. }
  553. void MCObjectStreamer::emitBytes(StringRef Data) {
  554. MCDwarfLineEntry::make(this, getCurrentSectionOnly());
  555. MCDataFragment *DF = getOrCreateDataFragment();
  556. flushPendingLabels(DF, DF->getContents().size());
  557. DF->getContents().append(Data.begin(), Data.end());
  558. }
  559. void MCObjectStreamer::emitValueToAlignment(unsigned ByteAlignment,
  560. int64_t Value,
  561. unsigned ValueSize,
  562. unsigned MaxBytesToEmit) {
  563. if (MaxBytesToEmit == 0)
  564. MaxBytesToEmit = ByteAlignment;
  565. insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
  566. // Update the maximum alignment on the current section if necessary.
  567. MCSection *CurSec = getCurrentSectionOnly();
  568. if (ByteAlignment > CurSec->getAlignment())
  569. CurSec->setAlignment(Align(ByteAlignment));
  570. }
  571. void MCObjectStreamer::emitCodeAlignment(unsigned ByteAlignment,
  572. const MCSubtargetInfo *STI,
  573. unsigned MaxBytesToEmit) {
  574. emitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
  575. cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true, STI);
  576. }
  577. void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
  578. unsigned char Value,
  579. SMLoc Loc) {
  580. insert(new MCOrgFragment(*Offset, Value, Loc));
  581. }
  582. // Associate DTPRel32 fixup with data and resize data area
  583. void MCObjectStreamer::emitDTPRel32Value(const MCExpr *Value) {
  584. MCDataFragment *DF = getOrCreateDataFragment();
  585. flushPendingLabels(DF, DF->getContents().size());
  586. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  587. Value, FK_DTPRel_4));
  588. DF->getContents().resize(DF->getContents().size() + 4, 0);
  589. }
  590. // Associate DTPRel64 fixup with data and resize data area
  591. void MCObjectStreamer::emitDTPRel64Value(const MCExpr *Value) {
  592. MCDataFragment *DF = getOrCreateDataFragment();
  593. flushPendingLabels(DF, DF->getContents().size());
  594. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  595. Value, FK_DTPRel_8));
  596. DF->getContents().resize(DF->getContents().size() + 8, 0);
  597. }
  598. // Associate TPRel32 fixup with data and resize data area
  599. void MCObjectStreamer::emitTPRel32Value(const MCExpr *Value) {
  600. MCDataFragment *DF = getOrCreateDataFragment();
  601. flushPendingLabels(DF, DF->getContents().size());
  602. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  603. Value, FK_TPRel_4));
  604. DF->getContents().resize(DF->getContents().size() + 4, 0);
  605. }
  606. // Associate TPRel64 fixup with data and resize data area
  607. void MCObjectStreamer::emitTPRel64Value(const MCExpr *Value) {
  608. MCDataFragment *DF = getOrCreateDataFragment();
  609. flushPendingLabels(DF, DF->getContents().size());
  610. DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
  611. Value, FK_TPRel_8));
  612. DF->getContents().resize(DF->getContents().size() + 8, 0);
  613. }
  614. // Associate GPRel32 fixup with data and resize data area
  615. void MCObjectStreamer::emitGPRel32Value(const MCExpr *Value) {
  616. MCDataFragment *DF = getOrCreateDataFragment();
  617. flushPendingLabels(DF, DF->getContents().size());
  618. DF->getFixups().push_back(
  619. MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4));
  620. DF->getContents().resize(DF->getContents().size() + 4, 0);
  621. }
  622. // Associate GPRel64 fixup with data and resize data area
  623. void MCObjectStreamer::emitGPRel64Value(const MCExpr *Value) {
  624. MCDataFragment *DF = getOrCreateDataFragment();
  625. flushPendingLabels(DF, DF->getContents().size());
  626. DF->getFixups().push_back(
  627. MCFixup::create(DF->getContents().size(), Value, FK_GPRel_4));
  628. DF->getContents().resize(DF->getContents().size() + 8, 0);
  629. }
  630. static Optional<std::pair<bool, std::string>>
  631. getOffsetAndDataFragment(const MCSymbol &Symbol, uint32_t &RelocOffset,
  632. MCDataFragment *&DF) {
  633. if (Symbol.isVariable()) {
  634. const MCExpr *SymbolExpr = Symbol.getVariableValue();
  635. MCValue OffsetVal;
  636. if(!SymbolExpr->evaluateAsRelocatable(OffsetVal, nullptr, nullptr))
  637. return std::make_pair(false,
  638. std::string("symbol in .reloc offset is not "
  639. "relocatable"));
  640. if (OffsetVal.isAbsolute()) {
  641. RelocOffset = OffsetVal.getConstant();
  642. MCFragment *Fragment = Symbol.getFragment();
  643. // FIXME Support symbols with no DF. For example:
  644. // .reloc .data, ENUM_VALUE, <some expr>
  645. if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
  646. return std::make_pair(false,
  647. std::string("symbol in offset has no data "
  648. "fragment"));
  649. DF = cast<MCDataFragment>(Fragment);
  650. return None;
  651. }
  652. if (OffsetVal.getSymB())
  653. return std::make_pair(false,
  654. std::string(".reloc symbol offset is not "
  655. "representable"));
  656. const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA());
  657. if (!SRE.getSymbol().isDefined())
  658. return std::make_pair(false,
  659. std::string("symbol used in the .reloc offset is "
  660. "not defined"));
  661. if (SRE.getSymbol().isVariable())
  662. return std::make_pair(false,
  663. std::string("symbol used in the .reloc offset is "
  664. "variable"));
  665. MCFragment *Fragment = SRE.getSymbol().getFragment();
  666. // FIXME Support symbols with no DF. For example:
  667. // .reloc .data, ENUM_VALUE, <some expr>
  668. if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
  669. return std::make_pair(false,
  670. std::string("symbol in offset has no data "
  671. "fragment"));
  672. RelocOffset = SRE.getSymbol().getOffset() + OffsetVal.getConstant();
  673. DF = cast<MCDataFragment>(Fragment);
  674. } else {
  675. RelocOffset = Symbol.getOffset();
  676. MCFragment *Fragment = Symbol.getFragment();
  677. // FIXME Support symbols with no DF. For example:
  678. // .reloc .data, ENUM_VALUE, <some expr>
  679. if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
  680. return std::make_pair(false,
  681. std::string("symbol in offset has no data "
  682. "fragment"));
  683. DF = cast<MCDataFragment>(Fragment);
  684. }
  685. return None;
  686. }
  687. Optional<std::pair<bool, std::string>>
  688. MCObjectStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
  689. const MCExpr *Expr, SMLoc Loc,
  690. const MCSubtargetInfo &STI) {
  691. Optional<MCFixupKind> MaybeKind = Assembler->getBackend().getFixupKind(Name);
  692. if (!MaybeKind.hasValue())
  693. return std::make_pair(true, std::string("unknown relocation name"));
  694. MCFixupKind Kind = *MaybeKind;
  695. if (Expr == nullptr)
  696. Expr =
  697. MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
  698. MCDataFragment *DF = getOrCreateDataFragment(&STI);
  699. flushPendingLabels(DF, DF->getContents().size());
  700. MCValue OffsetVal;
  701. if (!Offset.evaluateAsRelocatable(OffsetVal, nullptr, nullptr))
  702. return std::make_pair(false,
  703. std::string(".reloc offset is not relocatable"));
  704. if (OffsetVal.isAbsolute()) {
  705. if (OffsetVal.getConstant() < 0)
  706. return std::make_pair(false, std::string(".reloc offset is negative"));
  707. DF->getFixups().push_back(
  708. MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc));
  709. return None;
  710. }
  711. if (OffsetVal.getSymB())
  712. return std::make_pair(false,
  713. std::string(".reloc offset is not representable"));
  714. const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*OffsetVal.getSymA());
  715. const MCSymbol &Symbol = SRE.getSymbol();
  716. if (Symbol.isDefined()) {
  717. uint32_t SymbolOffset = 0;
  718. Optional<std::pair<bool, std::string>> Error;
  719. Error = getOffsetAndDataFragment(Symbol, SymbolOffset, DF);
  720. if (Error != None)
  721. return Error;
  722. DF->getFixups().push_back(
  723. MCFixup::create(SymbolOffset + OffsetVal.getConstant(),
  724. Expr, Kind, Loc));
  725. return None;
  726. }
  727. PendingFixups.emplace_back(
  728. &SRE.getSymbol(), DF,
  729. MCFixup::create(OffsetVal.getConstant(), Expr, Kind, Loc));
  730. return None;
  731. }
  732. void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
  733. SMLoc Loc) {
  734. MCDataFragment *DF = getOrCreateDataFragment();
  735. flushPendingLabels(DF, DF->getContents().size());
  736. assert(getCurrentSectionOnly() && "need a section");
  737. insert(new MCFillFragment(FillValue, 1, NumBytes, Loc));
  738. }
  739. void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
  740. int64_t Expr, SMLoc Loc) {
  741. int64_t IntNumValues;
  742. // Do additional checking now if we can resolve the value.
  743. if (NumValues.evaluateAsAbsolute(IntNumValues, getAssemblerPtr())) {
  744. if (IntNumValues < 0) {
  745. getContext().getSourceManager()->PrintMessage(
  746. Loc, SourceMgr::DK_Warning,
  747. "'.fill' directive with negative repeat count has no effect");
  748. return;
  749. }
  750. // Emit now if we can for better errors.
  751. int64_t NonZeroSize = Size > 4 ? 4 : Size;
  752. Expr &= ~0ULL >> (64 - NonZeroSize * 8);
  753. for (uint64_t i = 0, e = IntNumValues; i != e; ++i) {
  754. emitIntValue(Expr, NonZeroSize);
  755. if (NonZeroSize < Size)
  756. emitIntValue(0, Size - NonZeroSize);
  757. }
  758. return;
  759. }
  760. // Otherwise emit as fragment.
  761. MCDataFragment *DF = getOrCreateDataFragment();
  762. flushPendingLabels(DF, DF->getContents().size());
  763. assert(getCurrentSectionOnly() && "need a section");
  764. insert(new MCFillFragment(Expr, Size, NumValues, Loc));
  765. }
  766. void MCObjectStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLength,
  767. SMLoc Loc, const MCSubtargetInfo &STI) {
  768. // Emit an NOP fragment.
  769. MCDataFragment *DF = getOrCreateDataFragment();
  770. flushPendingLabels(DF, DF->getContents().size());
  771. assert(getCurrentSectionOnly() && "need a section");
  772. insert(new MCNopsFragment(NumBytes, ControlledNopLength, Loc, STI));
  773. }
  774. void MCObjectStreamer::emitFileDirective(StringRef Filename) {
  775. getAssembler().addFileName(Filename);
  776. }
  777. void MCObjectStreamer::emitFileDirective(StringRef Filename,
  778. StringRef CompilerVerion,
  779. StringRef TimeStamp,
  780. StringRef Description) {
  781. getAssembler().addFileName(Filename);
  782. // TODO: add additional info to integrated assembler.
  783. }
  784. void MCObjectStreamer::emitAddrsig() {
  785. getAssembler().getWriter().emitAddrsigSection();
  786. }
  787. void MCObjectStreamer::emitAddrsigSym(const MCSymbol *Sym) {
  788. getAssembler().registerSymbol(*Sym);
  789. getAssembler().getWriter().addAddrsigSymbol(Sym);
  790. }
  791. void MCObjectStreamer::finishImpl() {
  792. getContext().RemapDebugPaths();
  793. // If we are generating dwarf for assembly source files dump out the sections.
  794. if (getContext().getGenDwarfForAssembly())
  795. MCGenDwarfInfo::Emit(this);
  796. // Dump out the dwarf file & directory tables and line tables.
  797. MCDwarfLineTable::emit(this, getAssembler().getDWARFLinetableParams());
  798. // Emit pseudo probes for the current module.
  799. MCPseudoProbeTable::emit(this);
  800. // Update any remaining pending labels with empty data fragments.
  801. flushPendingLabels();
  802. resolvePendingFixups();
  803. getAssembler().Finish();
  804. }