MCStreamer.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. //===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
  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/MCStreamer.h"
  9. #include "llvm/ADT/Optional.h"
  10. #include "llvm/ADT/SmallString.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/ADT/Twine.h"
  13. #include "llvm/BinaryFormat/COFF.h"
  14. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  15. #include "llvm/MC/MCAsmBackend.h"
  16. #include "llvm/MC/MCAsmInfo.h"
  17. #include "llvm/MC/MCCodeView.h"
  18. #include "llvm/MC/MCContext.h"
  19. #include "llvm/MC/MCDwarf.h"
  20. #include "llvm/MC/MCExpr.h"
  21. #include "llvm/MC/MCInst.h"
  22. #include "llvm/MC/MCInstPrinter.h"
  23. #include "llvm/MC/MCObjectFileInfo.h"
  24. #include "llvm/MC/MCPseudoProbe.h"
  25. #include "llvm/MC/MCRegister.h"
  26. #include "llvm/MC/MCRegisterInfo.h"
  27. #include "llvm/MC/MCSection.h"
  28. #include "llvm/MC/MCSectionCOFF.h"
  29. #include "llvm/MC/MCSymbol.h"
  30. #include "llvm/MC/MCWin64EH.h"
  31. #include "llvm/MC/MCWinEH.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/LEB128.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <cassert>
  38. #include <cstdint>
  39. #include <cstdlib>
  40. #include <utility>
  41. using namespace llvm;
  42. MCTargetStreamer::MCTargetStreamer(MCStreamer &S) : Streamer(S) {
  43. S.setTargetStreamer(this);
  44. }
  45. // Pin the vtables to this file.
  46. MCTargetStreamer::~MCTargetStreamer() = default;
  47. void MCTargetStreamer::emitLabel(MCSymbol *Symbol) {}
  48. void MCTargetStreamer::finish() {}
  49. void MCTargetStreamer::changeSection(const MCSection *CurSection,
  50. MCSection *Section,
  51. const MCExpr *Subsection,
  52. raw_ostream &OS) {
  53. Section->PrintSwitchToSection(
  54. *Streamer.getContext().getAsmInfo(),
  55. Streamer.getContext().getObjectFileInfo()->getTargetTriple(), OS,
  56. Subsection);
  57. }
  58. void MCTargetStreamer::emitDwarfFileDirective(StringRef Directive) {
  59. Streamer.emitRawText(Directive);
  60. }
  61. void MCTargetStreamer::emitValue(const MCExpr *Value) {
  62. SmallString<128> Str;
  63. raw_svector_ostream OS(Str);
  64. Value->print(OS, Streamer.getContext().getAsmInfo());
  65. Streamer.emitRawText(OS.str());
  66. }
  67. void MCTargetStreamer::emitRawBytes(StringRef Data) {
  68. const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
  69. const char *Directive = MAI->getData8bitsDirective();
  70. for (const unsigned char C : Data.bytes()) {
  71. SmallString<128> Str;
  72. raw_svector_ostream OS(Str);
  73. OS << Directive << (unsigned)C;
  74. Streamer.emitRawText(OS.str());
  75. }
  76. }
  77. void MCTargetStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {}
  78. MCStreamer::MCStreamer(MCContext &Ctx)
  79. : Context(Ctx), CurrentWinFrameInfo(nullptr),
  80. CurrentProcWinFrameInfoStartIndex(0), UseAssemblerInfoForParsing(false) {
  81. SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
  82. }
  83. MCStreamer::~MCStreamer() {}
  84. void MCStreamer::reset() {
  85. DwarfFrameInfos.clear();
  86. CurrentWinFrameInfo = nullptr;
  87. WinFrameInfos.clear();
  88. SymbolOrdering.clear();
  89. SectionStack.clear();
  90. SectionStack.push_back(std::pair<MCSectionSubPair, MCSectionSubPair>());
  91. }
  92. raw_ostream &MCStreamer::GetCommentOS() {
  93. // By default, discard comments.
  94. return nulls();
  95. }
  96. unsigned MCStreamer::getNumFrameInfos() { return DwarfFrameInfos.size(); }
  97. ArrayRef<MCDwarfFrameInfo> MCStreamer::getDwarfFrameInfos() const {
  98. return DwarfFrameInfos;
  99. }
  100. void MCStreamer::emitRawComment(const Twine &T, bool TabPrefix) {}
  101. void MCStreamer::addExplicitComment(const Twine &T) {}
  102. void MCStreamer::emitExplicitComments() {}
  103. void MCStreamer::generateCompactUnwindEncodings(MCAsmBackend *MAB) {
  104. for (auto &FI : DwarfFrameInfos)
  105. FI.CompactUnwindEncoding =
  106. (MAB ? MAB->generateCompactUnwindEncoding(FI.Instructions) : 0);
  107. }
  108. /// EmitIntValue - Special case of EmitValue that avoids the client having to
  109. /// pass in a MCExpr for constant integers.
  110. void MCStreamer::emitIntValue(uint64_t Value, unsigned Size) {
  111. assert(1 <= Size && Size <= 8 && "Invalid size");
  112. assert((isUIntN(8 * Size, Value) || isIntN(8 * Size, Value)) &&
  113. "Invalid size");
  114. const bool IsLittleEndian = Context.getAsmInfo()->isLittleEndian();
  115. uint64_t Swapped = support::endian::byte_swap(
  116. Value, IsLittleEndian ? support::little : support::big);
  117. unsigned Index = IsLittleEndian ? 0 : 8 - Size;
  118. emitBytes(StringRef(reinterpret_cast<char *>(&Swapped) + Index, Size));
  119. }
  120. void MCStreamer::emitIntValue(APInt Value) {
  121. if (Value.getNumWords() == 1) {
  122. emitIntValue(Value.getLimitedValue(), Value.getBitWidth() / 8);
  123. return;
  124. }
  125. const bool IsLittleEndianTarget = Context.getAsmInfo()->isLittleEndian();
  126. const bool ShouldSwap = sys::IsLittleEndianHost != IsLittleEndianTarget;
  127. const APInt Swapped = ShouldSwap ? Value.byteSwap() : Value;
  128. const unsigned Size = Value.getBitWidth() / 8;
  129. SmallString<10> Tmp;
  130. Tmp.resize(Size);
  131. StoreIntToMemory(Swapped, reinterpret_cast<uint8_t *>(Tmp.data()), Size);
  132. emitBytes(Tmp.str());
  133. }
  134. /// EmitULEB128IntValue - Special case of EmitULEB128Value that avoids the
  135. /// client having to pass in a MCExpr for constant integers.
  136. void MCStreamer::emitULEB128IntValue(uint64_t Value, unsigned PadTo) {
  137. SmallString<128> Tmp;
  138. raw_svector_ostream OSE(Tmp);
  139. encodeULEB128(Value, OSE, PadTo);
  140. emitBytes(OSE.str());
  141. }
  142. /// EmitSLEB128IntValue - Special case of EmitSLEB128Value that avoids the
  143. /// client having to pass in a MCExpr for constant integers.
  144. void MCStreamer::emitSLEB128IntValue(int64_t Value) {
  145. SmallString<128> Tmp;
  146. raw_svector_ostream OSE(Tmp);
  147. encodeSLEB128(Value, OSE);
  148. emitBytes(OSE.str());
  149. }
  150. void MCStreamer::emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc) {
  151. emitValueImpl(Value, Size, Loc);
  152. }
  153. void MCStreamer::emitSymbolValue(const MCSymbol *Sym, unsigned Size,
  154. bool IsSectionRelative) {
  155. assert((!IsSectionRelative || Size == 4) &&
  156. "SectionRelative value requires 4-bytes");
  157. if (!IsSectionRelative)
  158. emitValueImpl(MCSymbolRefExpr::create(Sym, getContext()), Size);
  159. else
  160. EmitCOFFSecRel32(Sym, /*Offset=*/0);
  161. }
  162. void MCStreamer::emitDTPRel64Value(const MCExpr *Value) {
  163. report_fatal_error("unsupported directive in streamer");
  164. }
  165. void MCStreamer::emitDTPRel32Value(const MCExpr *Value) {
  166. report_fatal_error("unsupported directive in streamer");
  167. }
  168. void MCStreamer::emitTPRel64Value(const MCExpr *Value) {
  169. report_fatal_error("unsupported directive in streamer");
  170. }
  171. void MCStreamer::emitTPRel32Value(const MCExpr *Value) {
  172. report_fatal_error("unsupported directive in streamer");
  173. }
  174. void MCStreamer::emitGPRel64Value(const MCExpr *Value) {
  175. report_fatal_error("unsupported directive in streamer");
  176. }
  177. void MCStreamer::emitGPRel32Value(const MCExpr *Value) {
  178. report_fatal_error("unsupported directive in streamer");
  179. }
  180. /// Emit NumBytes bytes worth of the value specified by FillValue.
  181. /// This implements directives such as '.space'.
  182. void MCStreamer::emitFill(uint64_t NumBytes, uint8_t FillValue) {
  183. emitFill(*MCConstantExpr::create(NumBytes, getContext()), FillValue);
  184. }
  185. void llvm::MCStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLen,
  186. llvm::SMLoc) {}
  187. /// The implementation in this class just redirects to emitFill.
  188. void MCStreamer::emitZeros(uint64_t NumBytes) { emitFill(NumBytes, 0); }
  189. Expected<unsigned>
  190. MCStreamer::tryEmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
  191. StringRef Filename,
  192. Optional<MD5::MD5Result> Checksum,
  193. Optional<StringRef> Source,
  194. unsigned CUID) {
  195. return getContext().getDwarfFile(Directory, Filename, FileNo, Checksum,
  196. Source, CUID);
  197. }
  198. void MCStreamer::emitDwarfFile0Directive(StringRef Directory,
  199. StringRef Filename,
  200. Optional<MD5::MD5Result> Checksum,
  201. Optional<StringRef> Source,
  202. unsigned CUID) {
  203. getContext().setMCLineTableRootFile(CUID, Directory, Filename, Checksum,
  204. Source);
  205. }
  206. void MCStreamer::emitCFIBKeyFrame() {
  207. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  208. if (!CurFrame)
  209. return;
  210. CurFrame->IsBKeyFrame = true;
  211. }
  212. void MCStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
  213. unsigned Column, unsigned Flags,
  214. unsigned Isa, unsigned Discriminator,
  215. StringRef FileName) {
  216. getContext().setCurrentDwarfLoc(FileNo, Line, Column, Flags, Isa,
  217. Discriminator);
  218. }
  219. MCSymbol *MCStreamer::getDwarfLineTableSymbol(unsigned CUID) {
  220. MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID);
  221. if (!Table.getLabel()) {
  222. StringRef Prefix = Context.getAsmInfo()->getPrivateGlobalPrefix();
  223. Table.setLabel(
  224. Context.getOrCreateSymbol(Prefix + "line_table_start" + Twine(CUID)));
  225. }
  226. return Table.getLabel();
  227. }
  228. bool MCStreamer::hasUnfinishedDwarfFrameInfo() {
  229. return !DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End;
  230. }
  231. MCDwarfFrameInfo *MCStreamer::getCurrentDwarfFrameInfo() {
  232. if (!hasUnfinishedDwarfFrameInfo()) {
  233. getContext().reportError(getStartTokLoc(),
  234. "this directive must appear between "
  235. ".cfi_startproc and .cfi_endproc directives");
  236. return nullptr;
  237. }
  238. return &DwarfFrameInfos.back();
  239. }
  240. bool MCStreamer::EmitCVFileDirective(unsigned FileNo, StringRef Filename,
  241. ArrayRef<uint8_t> Checksum,
  242. unsigned ChecksumKind) {
  243. return getContext().getCVContext().addFile(*this, FileNo, Filename, Checksum,
  244. ChecksumKind);
  245. }
  246. bool MCStreamer::EmitCVFuncIdDirective(unsigned FunctionId) {
  247. return getContext().getCVContext().recordFunctionId(FunctionId);
  248. }
  249. bool MCStreamer::EmitCVInlineSiteIdDirective(unsigned FunctionId,
  250. unsigned IAFunc, unsigned IAFile,
  251. unsigned IALine, unsigned IACol,
  252. SMLoc Loc) {
  253. if (getContext().getCVContext().getCVFunctionInfo(IAFunc) == nullptr) {
  254. getContext().reportError(Loc, "parent function id not introduced by "
  255. ".cv_func_id or .cv_inline_site_id");
  256. return true;
  257. }
  258. return getContext().getCVContext().recordInlinedCallSiteId(
  259. FunctionId, IAFunc, IAFile, IALine, IACol);
  260. }
  261. void MCStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
  262. unsigned Line, unsigned Column,
  263. bool PrologueEnd, bool IsStmt,
  264. StringRef FileName, SMLoc Loc) {}
  265. bool MCStreamer::checkCVLocSection(unsigned FuncId, unsigned FileNo,
  266. SMLoc Loc) {
  267. CodeViewContext &CVC = getContext().getCVContext();
  268. MCCVFunctionInfo *FI = CVC.getCVFunctionInfo(FuncId);
  269. if (!FI) {
  270. getContext().reportError(
  271. Loc, "function id not introduced by .cv_func_id or .cv_inline_site_id");
  272. return false;
  273. }
  274. // Track the section
  275. if (FI->Section == nullptr)
  276. FI->Section = getCurrentSectionOnly();
  277. else if (FI->Section != getCurrentSectionOnly()) {
  278. getContext().reportError(
  279. Loc,
  280. "all .cv_loc directives for a function must be in the same section");
  281. return false;
  282. }
  283. return true;
  284. }
  285. void MCStreamer::emitCVLinetableDirective(unsigned FunctionId,
  286. const MCSymbol *Begin,
  287. const MCSymbol *End) {}
  288. void MCStreamer::emitCVInlineLinetableDirective(unsigned PrimaryFunctionId,
  289. unsigned SourceFileId,
  290. unsigned SourceLineNum,
  291. const MCSymbol *FnStartSym,
  292. const MCSymbol *FnEndSym) {}
  293. /// Only call this on endian-specific types like ulittle16_t and little32_t, or
  294. /// structs composed of them.
  295. template <typename T>
  296. static void copyBytesForDefRange(SmallString<20> &BytePrefix,
  297. codeview::SymbolKind SymKind,
  298. const T &DefRangeHeader) {
  299. BytePrefix.resize(2 + sizeof(T));
  300. codeview::ulittle16_t SymKindLE = codeview::ulittle16_t(SymKind);
  301. memcpy(&BytePrefix[0], &SymKindLE, 2);
  302. memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
  303. }
  304. void MCStreamer::emitCVDefRangeDirective(
  305. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  306. StringRef FixedSizePortion) {}
  307. void MCStreamer::emitCVDefRangeDirective(
  308. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  309. codeview::DefRangeRegisterRelHeader DRHdr) {
  310. SmallString<20> BytePrefix;
  311. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER_REL, DRHdr);
  312. emitCVDefRangeDirective(Ranges, BytePrefix);
  313. }
  314. void MCStreamer::emitCVDefRangeDirective(
  315. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  316. codeview::DefRangeSubfieldRegisterHeader DRHdr) {
  317. SmallString<20> BytePrefix;
  318. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_SUBFIELD_REGISTER,
  319. DRHdr);
  320. emitCVDefRangeDirective(Ranges, BytePrefix);
  321. }
  322. void MCStreamer::emitCVDefRangeDirective(
  323. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  324. codeview::DefRangeRegisterHeader DRHdr) {
  325. SmallString<20> BytePrefix;
  326. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_REGISTER, DRHdr);
  327. emitCVDefRangeDirective(Ranges, BytePrefix);
  328. }
  329. void MCStreamer::emitCVDefRangeDirective(
  330. ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
  331. codeview::DefRangeFramePointerRelHeader DRHdr) {
  332. SmallString<20> BytePrefix;
  333. copyBytesForDefRange(BytePrefix, codeview::S_DEFRANGE_FRAMEPOINTER_REL,
  334. DRHdr);
  335. emitCVDefRangeDirective(Ranges, BytePrefix);
  336. }
  337. void MCStreamer::emitEHSymAttributes(const MCSymbol *Symbol,
  338. MCSymbol *EHSymbol) {
  339. }
  340. void MCStreamer::InitSections(bool NoExecStack) {
  341. SwitchSection(getContext().getObjectFileInfo()->getTextSection());
  342. }
  343. void MCStreamer::AssignFragment(MCSymbol *Symbol, MCFragment *Fragment) {
  344. assert(Fragment);
  345. Symbol->setFragment(Fragment);
  346. // As we emit symbols into a section, track the order so that they can
  347. // be sorted upon later. Zero is reserved to mean 'unemitted'.
  348. SymbolOrdering[Symbol] = 1 + SymbolOrdering.size();
  349. }
  350. void MCStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
  351. Symbol->redefineIfPossible();
  352. if (!Symbol->isUndefined() || Symbol->isVariable())
  353. return getContext().reportError(Loc, "invalid symbol redefinition");
  354. assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
  355. assert(getCurrentSectionOnly() && "Cannot emit before setting section!");
  356. assert(!Symbol->getFragment() && "Unexpected fragment on symbol data!");
  357. assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
  358. Symbol->setFragment(&getCurrentSectionOnly()->getDummyFragment());
  359. MCTargetStreamer *TS = getTargetStreamer();
  360. if (TS)
  361. TS->emitLabel(Symbol);
  362. }
  363. void MCStreamer::emitCFISections(bool EH, bool Debug) {
  364. assert(EH || Debug);
  365. }
  366. void MCStreamer::emitCFIStartProc(bool IsSimple, SMLoc Loc) {
  367. if (hasUnfinishedDwarfFrameInfo())
  368. return getContext().reportError(
  369. Loc, "starting new .cfi frame before finishing the previous one");
  370. MCDwarfFrameInfo Frame;
  371. Frame.IsSimple = IsSimple;
  372. emitCFIStartProcImpl(Frame);
  373. const MCAsmInfo* MAI = Context.getAsmInfo();
  374. if (MAI) {
  375. for (const MCCFIInstruction& Inst : MAI->getInitialFrameState()) {
  376. if (Inst.getOperation() == MCCFIInstruction::OpDefCfa ||
  377. Inst.getOperation() == MCCFIInstruction::OpDefCfaRegister) {
  378. Frame.CurrentCfaRegister = Inst.getRegister();
  379. }
  380. }
  381. }
  382. DwarfFrameInfos.push_back(Frame);
  383. }
  384. void MCStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
  385. }
  386. void MCStreamer::emitCFIEndProc() {
  387. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  388. if (!CurFrame)
  389. return;
  390. emitCFIEndProcImpl(*CurFrame);
  391. }
  392. void MCStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
  393. // Put a dummy non-null value in Frame.End to mark that this frame has been
  394. // closed.
  395. Frame.End = (MCSymbol *)1;
  396. }
  397. MCSymbol *MCStreamer::emitCFILabel() {
  398. // Return a dummy non-null value so that label fields appear filled in when
  399. // generating textual assembly.
  400. return (MCSymbol *)1;
  401. }
  402. void MCStreamer::emitCFIDefCfa(int64_t Register, int64_t Offset) {
  403. MCSymbol *Label = emitCFILabel();
  404. MCCFIInstruction Instruction =
  405. MCCFIInstruction::cfiDefCfa(Label, Register, Offset);
  406. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  407. if (!CurFrame)
  408. return;
  409. CurFrame->Instructions.push_back(Instruction);
  410. CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
  411. }
  412. void MCStreamer::emitCFIDefCfaOffset(int64_t Offset) {
  413. MCSymbol *Label = emitCFILabel();
  414. MCCFIInstruction Instruction =
  415. MCCFIInstruction::cfiDefCfaOffset(Label, Offset);
  416. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  417. if (!CurFrame)
  418. return;
  419. CurFrame->Instructions.push_back(Instruction);
  420. }
  421. void MCStreamer::emitCFIAdjustCfaOffset(int64_t Adjustment) {
  422. MCSymbol *Label = emitCFILabel();
  423. MCCFIInstruction Instruction =
  424. MCCFIInstruction::createAdjustCfaOffset(Label, Adjustment);
  425. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  426. if (!CurFrame)
  427. return;
  428. CurFrame->Instructions.push_back(Instruction);
  429. }
  430. void MCStreamer::emitCFIDefCfaRegister(int64_t Register) {
  431. MCSymbol *Label = emitCFILabel();
  432. MCCFIInstruction Instruction =
  433. MCCFIInstruction::createDefCfaRegister(Label, Register);
  434. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  435. if (!CurFrame)
  436. return;
  437. CurFrame->Instructions.push_back(Instruction);
  438. CurFrame->CurrentCfaRegister = static_cast<unsigned>(Register);
  439. }
  440. void MCStreamer::emitCFIOffset(int64_t Register, int64_t Offset) {
  441. MCSymbol *Label = emitCFILabel();
  442. MCCFIInstruction Instruction =
  443. MCCFIInstruction::createOffset(Label, Register, Offset);
  444. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  445. if (!CurFrame)
  446. return;
  447. CurFrame->Instructions.push_back(Instruction);
  448. }
  449. void MCStreamer::emitCFIRelOffset(int64_t Register, int64_t Offset) {
  450. MCSymbol *Label = emitCFILabel();
  451. MCCFIInstruction Instruction =
  452. MCCFIInstruction::createRelOffset(Label, Register, Offset);
  453. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  454. if (!CurFrame)
  455. return;
  456. CurFrame->Instructions.push_back(Instruction);
  457. }
  458. void MCStreamer::emitCFIPersonality(const MCSymbol *Sym,
  459. unsigned Encoding) {
  460. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  461. if (!CurFrame)
  462. return;
  463. CurFrame->Personality = Sym;
  464. CurFrame->PersonalityEncoding = Encoding;
  465. }
  466. void MCStreamer::emitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
  467. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  468. if (!CurFrame)
  469. return;
  470. CurFrame->Lsda = Sym;
  471. CurFrame->LsdaEncoding = Encoding;
  472. }
  473. void MCStreamer::emitCFIRememberState() {
  474. MCSymbol *Label = emitCFILabel();
  475. MCCFIInstruction Instruction = MCCFIInstruction::createRememberState(Label);
  476. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  477. if (!CurFrame)
  478. return;
  479. CurFrame->Instructions.push_back(Instruction);
  480. }
  481. void MCStreamer::emitCFIRestoreState() {
  482. // FIXME: Error if there is no matching cfi_remember_state.
  483. MCSymbol *Label = emitCFILabel();
  484. MCCFIInstruction Instruction = MCCFIInstruction::createRestoreState(Label);
  485. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  486. if (!CurFrame)
  487. return;
  488. CurFrame->Instructions.push_back(Instruction);
  489. }
  490. void MCStreamer::emitCFISameValue(int64_t Register) {
  491. MCSymbol *Label = emitCFILabel();
  492. MCCFIInstruction Instruction =
  493. MCCFIInstruction::createSameValue(Label, Register);
  494. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  495. if (!CurFrame)
  496. return;
  497. CurFrame->Instructions.push_back(Instruction);
  498. }
  499. void MCStreamer::emitCFIRestore(int64_t Register) {
  500. MCSymbol *Label = emitCFILabel();
  501. MCCFIInstruction Instruction =
  502. MCCFIInstruction::createRestore(Label, Register);
  503. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  504. if (!CurFrame)
  505. return;
  506. CurFrame->Instructions.push_back(Instruction);
  507. }
  508. void MCStreamer::emitCFIEscape(StringRef Values) {
  509. MCSymbol *Label = emitCFILabel();
  510. MCCFIInstruction Instruction = MCCFIInstruction::createEscape(Label, Values);
  511. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  512. if (!CurFrame)
  513. return;
  514. CurFrame->Instructions.push_back(Instruction);
  515. }
  516. void MCStreamer::emitCFIGnuArgsSize(int64_t Size) {
  517. MCSymbol *Label = emitCFILabel();
  518. MCCFIInstruction Instruction =
  519. MCCFIInstruction::createGnuArgsSize(Label, Size);
  520. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  521. if (!CurFrame)
  522. return;
  523. CurFrame->Instructions.push_back(Instruction);
  524. }
  525. void MCStreamer::emitCFISignalFrame() {
  526. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  527. if (!CurFrame)
  528. return;
  529. CurFrame->IsSignalFrame = true;
  530. }
  531. void MCStreamer::emitCFIUndefined(int64_t Register) {
  532. MCSymbol *Label = emitCFILabel();
  533. MCCFIInstruction Instruction =
  534. MCCFIInstruction::createUndefined(Label, Register);
  535. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  536. if (!CurFrame)
  537. return;
  538. CurFrame->Instructions.push_back(Instruction);
  539. }
  540. void MCStreamer::emitCFIRegister(int64_t Register1, int64_t Register2) {
  541. MCSymbol *Label = emitCFILabel();
  542. MCCFIInstruction Instruction =
  543. MCCFIInstruction::createRegister(Label, Register1, Register2);
  544. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  545. if (!CurFrame)
  546. return;
  547. CurFrame->Instructions.push_back(Instruction);
  548. }
  549. void MCStreamer::emitCFIWindowSave() {
  550. MCSymbol *Label = emitCFILabel();
  551. MCCFIInstruction Instruction =
  552. MCCFIInstruction::createWindowSave(Label);
  553. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  554. if (!CurFrame)
  555. return;
  556. CurFrame->Instructions.push_back(Instruction);
  557. }
  558. void MCStreamer::emitCFINegateRAState() {
  559. MCSymbol *Label = emitCFILabel();
  560. MCCFIInstruction Instruction = MCCFIInstruction::createNegateRAState(Label);
  561. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  562. if (!CurFrame)
  563. return;
  564. CurFrame->Instructions.push_back(Instruction);
  565. }
  566. void MCStreamer::emitCFIReturnColumn(int64_t Register) {
  567. MCDwarfFrameInfo *CurFrame = getCurrentDwarfFrameInfo();
  568. if (!CurFrame)
  569. return;
  570. CurFrame->RAReg = Register;
  571. }
  572. WinEH::FrameInfo *MCStreamer::EnsureValidWinFrameInfo(SMLoc Loc) {
  573. const MCAsmInfo *MAI = Context.getAsmInfo();
  574. if (!MAI->usesWindowsCFI()) {
  575. getContext().reportError(
  576. Loc, ".seh_* directives are not supported on this target");
  577. return nullptr;
  578. }
  579. if (!CurrentWinFrameInfo || CurrentWinFrameInfo->End) {
  580. getContext().reportError(
  581. Loc, ".seh_ directive must appear within an active frame");
  582. return nullptr;
  583. }
  584. return CurrentWinFrameInfo;
  585. }
  586. void MCStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol, SMLoc Loc) {
  587. const MCAsmInfo *MAI = Context.getAsmInfo();
  588. if (!MAI->usesWindowsCFI())
  589. return getContext().reportError(
  590. Loc, ".seh_* directives are not supported on this target");
  591. if (CurrentWinFrameInfo && !CurrentWinFrameInfo->End)
  592. getContext().reportError(
  593. Loc, "Starting a function before ending the previous one!");
  594. MCSymbol *StartProc = emitCFILabel();
  595. CurrentProcWinFrameInfoStartIndex = WinFrameInfos.size();
  596. WinFrameInfos.emplace_back(
  597. std::make_unique<WinEH::FrameInfo>(Symbol, StartProc));
  598. CurrentWinFrameInfo = WinFrameInfos.back().get();
  599. CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
  600. }
  601. void MCStreamer::EmitWinCFIEndProc(SMLoc Loc) {
  602. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  603. if (!CurFrame)
  604. return;
  605. if (CurFrame->ChainedParent)
  606. getContext().reportError(Loc, "Not all chained regions terminated!");
  607. MCSymbol *Label = emitCFILabel();
  608. CurFrame->End = Label;
  609. if (!CurFrame->FuncletOrFuncEnd)
  610. CurFrame->FuncletOrFuncEnd = CurFrame->End;
  611. for (size_t I = CurrentProcWinFrameInfoStartIndex, E = WinFrameInfos.size();
  612. I != E; ++I)
  613. EmitWindowsUnwindTables(WinFrameInfos[I].get());
  614. SwitchSection(CurFrame->TextSection);
  615. }
  616. void MCStreamer::EmitWinCFIFuncletOrFuncEnd(SMLoc Loc) {
  617. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  618. if (!CurFrame)
  619. return;
  620. if (CurFrame->ChainedParent)
  621. getContext().reportError(Loc, "Not all chained regions terminated!");
  622. MCSymbol *Label = emitCFILabel();
  623. CurFrame->FuncletOrFuncEnd = Label;
  624. }
  625. void MCStreamer::EmitWinCFIStartChained(SMLoc Loc) {
  626. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  627. if (!CurFrame)
  628. return;
  629. MCSymbol *StartProc = emitCFILabel();
  630. WinFrameInfos.emplace_back(std::make_unique<WinEH::FrameInfo>(
  631. CurFrame->Function, StartProc, CurFrame));
  632. CurrentWinFrameInfo = WinFrameInfos.back().get();
  633. CurrentWinFrameInfo->TextSection = getCurrentSectionOnly();
  634. }
  635. void MCStreamer::EmitWinCFIEndChained(SMLoc Loc) {
  636. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  637. if (!CurFrame)
  638. return;
  639. if (!CurFrame->ChainedParent)
  640. return getContext().reportError(
  641. Loc, "End of a chained region outside a chained region!");
  642. MCSymbol *Label = emitCFILabel();
  643. CurFrame->End = Label;
  644. CurrentWinFrameInfo = const_cast<WinEH::FrameInfo *>(CurFrame->ChainedParent);
  645. }
  646. void MCStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except,
  647. SMLoc Loc) {
  648. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  649. if (!CurFrame)
  650. return;
  651. if (CurFrame->ChainedParent)
  652. return getContext().reportError(
  653. Loc, "Chained unwind areas can't have handlers!");
  654. CurFrame->ExceptionHandler = Sym;
  655. if (!Except && !Unwind)
  656. getContext().reportError(Loc, "Don't know what kind of handler this is!");
  657. if (Unwind)
  658. CurFrame->HandlesUnwind = true;
  659. if (Except)
  660. CurFrame->HandlesExceptions = true;
  661. }
  662. void MCStreamer::EmitWinEHHandlerData(SMLoc Loc) {
  663. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  664. if (!CurFrame)
  665. return;
  666. if (CurFrame->ChainedParent)
  667. getContext().reportError(Loc, "Chained unwind areas can't have handlers!");
  668. }
  669. void MCStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  670. const MCSymbolRefExpr *To, uint64_t Count) {
  671. }
  672. static MCSection *getWinCFISection(MCContext &Context, unsigned *NextWinCFIID,
  673. MCSection *MainCFISec,
  674. const MCSection *TextSec) {
  675. // If this is the main .text section, use the main unwind info section.
  676. if (TextSec == Context.getObjectFileInfo()->getTextSection())
  677. return MainCFISec;
  678. const auto *TextSecCOFF = cast<MCSectionCOFF>(TextSec);
  679. auto *MainCFISecCOFF = cast<MCSectionCOFF>(MainCFISec);
  680. unsigned UniqueID = TextSecCOFF->getOrAssignWinCFISectionID(NextWinCFIID);
  681. // If this section is COMDAT, this unwind section should be COMDAT associative
  682. // with its group.
  683. const MCSymbol *KeySym = nullptr;
  684. if (TextSecCOFF->getCharacteristics() & COFF::IMAGE_SCN_LNK_COMDAT) {
  685. KeySym = TextSecCOFF->getCOMDATSymbol();
  686. // In a GNU environment, we can't use associative comdats. Instead, do what
  687. // GCC does, which is to make plain comdat selectany section named like
  688. // ".[px]data$_Z3foov".
  689. if (!Context.getAsmInfo()->hasCOFFAssociativeComdats()) {
  690. std::string SectionName = (MainCFISecCOFF->getName() + "$" +
  691. TextSecCOFF->getName().split('$').second)
  692. .str();
  693. return Context.getCOFFSection(
  694. SectionName,
  695. MainCFISecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT,
  696. MainCFISecCOFF->getKind(), "", COFF::IMAGE_COMDAT_SELECT_ANY);
  697. }
  698. }
  699. return Context.getAssociativeCOFFSection(MainCFISecCOFF, KeySym, UniqueID);
  700. }
  701. MCSection *MCStreamer::getAssociatedPDataSection(const MCSection *TextSec) {
  702. return getWinCFISection(getContext(), &NextWinCFIID,
  703. getContext().getObjectFileInfo()->getPDataSection(),
  704. TextSec);
  705. }
  706. MCSection *MCStreamer::getAssociatedXDataSection(const MCSection *TextSec) {
  707. return getWinCFISection(getContext(), &NextWinCFIID,
  708. getContext().getObjectFileInfo()->getXDataSection(),
  709. TextSec);
  710. }
  711. void MCStreamer::emitSyntaxDirective() {}
  712. static unsigned encodeSEHRegNum(MCContext &Ctx, MCRegister Reg) {
  713. return Ctx.getRegisterInfo()->getSEHRegNum(Reg);
  714. }
  715. void MCStreamer::EmitWinCFIPushReg(MCRegister Register, SMLoc Loc) {
  716. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  717. if (!CurFrame)
  718. return;
  719. MCSymbol *Label = emitCFILabel();
  720. WinEH::Instruction Inst = Win64EH::Instruction::PushNonVol(
  721. Label, encodeSEHRegNum(Context, Register));
  722. CurFrame->Instructions.push_back(Inst);
  723. }
  724. void MCStreamer::EmitWinCFISetFrame(MCRegister Register, unsigned Offset,
  725. SMLoc Loc) {
  726. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  727. if (!CurFrame)
  728. return;
  729. if (CurFrame->LastFrameInst >= 0)
  730. return getContext().reportError(
  731. Loc, "frame register and offset can be set at most once");
  732. if (Offset & 0x0F)
  733. return getContext().reportError(Loc, "offset is not a multiple of 16");
  734. if (Offset > 240)
  735. return getContext().reportError(
  736. Loc, "frame offset must be less than or equal to 240");
  737. MCSymbol *Label = emitCFILabel();
  738. WinEH::Instruction Inst = Win64EH::Instruction::SetFPReg(
  739. Label, encodeSEHRegNum(getContext(), Register), Offset);
  740. CurFrame->LastFrameInst = CurFrame->Instructions.size();
  741. CurFrame->Instructions.push_back(Inst);
  742. }
  743. void MCStreamer::EmitWinCFIAllocStack(unsigned Size, SMLoc Loc) {
  744. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  745. if (!CurFrame)
  746. return;
  747. if (Size == 0)
  748. return getContext().reportError(Loc,
  749. "stack allocation size must be non-zero");
  750. if (Size & 7)
  751. return getContext().reportError(
  752. Loc, "stack allocation size is not a multiple of 8");
  753. MCSymbol *Label = emitCFILabel();
  754. WinEH::Instruction Inst = Win64EH::Instruction::Alloc(Label, Size);
  755. CurFrame->Instructions.push_back(Inst);
  756. }
  757. void MCStreamer::EmitWinCFISaveReg(MCRegister Register, unsigned Offset,
  758. SMLoc Loc) {
  759. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  760. if (!CurFrame)
  761. return;
  762. if (Offset & 7)
  763. return getContext().reportError(
  764. Loc, "register save offset is not 8 byte aligned");
  765. MCSymbol *Label = emitCFILabel();
  766. WinEH::Instruction Inst = Win64EH::Instruction::SaveNonVol(
  767. Label, encodeSEHRegNum(Context, Register), Offset);
  768. CurFrame->Instructions.push_back(Inst);
  769. }
  770. void MCStreamer::EmitWinCFISaveXMM(MCRegister Register, unsigned Offset,
  771. SMLoc Loc) {
  772. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  773. if (!CurFrame)
  774. return;
  775. if (Offset & 0x0F)
  776. return getContext().reportError(Loc, "offset is not a multiple of 16");
  777. MCSymbol *Label = emitCFILabel();
  778. WinEH::Instruction Inst = Win64EH::Instruction::SaveXMM(
  779. Label, encodeSEHRegNum(Context, Register), Offset);
  780. CurFrame->Instructions.push_back(Inst);
  781. }
  782. void MCStreamer::EmitWinCFIPushFrame(bool Code, SMLoc Loc) {
  783. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  784. if (!CurFrame)
  785. return;
  786. if (!CurFrame->Instructions.empty())
  787. return getContext().reportError(
  788. Loc, "If present, PushMachFrame must be the first UOP");
  789. MCSymbol *Label = emitCFILabel();
  790. WinEH::Instruction Inst = Win64EH::Instruction::PushMachFrame(Label, Code);
  791. CurFrame->Instructions.push_back(Inst);
  792. }
  793. void MCStreamer::EmitWinCFIEndProlog(SMLoc Loc) {
  794. WinEH::FrameInfo *CurFrame = EnsureValidWinFrameInfo(Loc);
  795. if (!CurFrame)
  796. return;
  797. MCSymbol *Label = emitCFILabel();
  798. CurFrame->PrologEnd = Label;
  799. }
  800. void MCStreamer::EmitCOFFSafeSEH(MCSymbol const *Symbol) {}
  801. void MCStreamer::EmitCOFFSymbolIndex(MCSymbol const *Symbol) {}
  802. void MCStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) {}
  803. void MCStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol, uint64_t Offset) {}
  804. void MCStreamer::EmitCOFFImgRel32(MCSymbol const *Symbol, int64_t Offset) {}
  805. /// EmitRawText - If this file is backed by an assembly streamer, this dumps
  806. /// the specified string in the output .s file. This capability is
  807. /// indicated by the hasRawTextSupport() predicate.
  808. void MCStreamer::emitRawTextImpl(StringRef String) {
  809. // This is not llvm_unreachable for the sake of out of tree backend
  810. // developers who may not have assembly streamers and should serve as a
  811. // reminder to not accidentally call EmitRawText in the absence of such.
  812. report_fatal_error("EmitRawText called on an MCStreamer that doesn't support "
  813. "it (target backend is likely missing an AsmStreamer "
  814. "implementation)");
  815. }
  816. void MCStreamer::emitRawText(const Twine &T) {
  817. SmallString<128> Str;
  818. emitRawTextImpl(T.toStringRef(Str));
  819. }
  820. void MCStreamer::EmitWindowsUnwindTables() {
  821. }
  822. void MCStreamer::EmitWindowsUnwindTables(WinEH::FrameInfo *Frame) {
  823. }
  824. void MCStreamer::Finish(SMLoc EndLoc) {
  825. if ((!DwarfFrameInfos.empty() && !DwarfFrameInfos.back().End) ||
  826. (!WinFrameInfos.empty() && !WinFrameInfos.back()->End)) {
  827. getContext().reportError(EndLoc, "Unfinished frame!");
  828. return;
  829. }
  830. MCTargetStreamer *TS = getTargetStreamer();
  831. if (TS)
  832. TS->finish();
  833. finishImpl();
  834. }
  835. void MCStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
  836. visitUsedExpr(*Value);
  837. Symbol->setVariableValue(Value);
  838. MCTargetStreamer *TS = getTargetStreamer();
  839. if (TS)
  840. TS->emitAssignment(Symbol, Value);
  841. }
  842. void MCTargetStreamer::prettyPrintAsm(MCInstPrinter &InstPrinter,
  843. uint64_t Address, const MCInst &Inst,
  844. const MCSubtargetInfo &STI,
  845. raw_ostream &OS) {
  846. InstPrinter.printInst(&Inst, Address, "", STI, OS);
  847. }
  848. void MCStreamer::visitUsedSymbol(const MCSymbol &Sym) {
  849. }
  850. void MCStreamer::visitUsedExpr(const MCExpr &Expr) {
  851. switch (Expr.getKind()) {
  852. case MCExpr::Target:
  853. cast<MCTargetExpr>(Expr).visitUsedExpr(*this);
  854. break;
  855. case MCExpr::Constant:
  856. break;
  857. case MCExpr::Binary: {
  858. const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
  859. visitUsedExpr(*BE.getLHS());
  860. visitUsedExpr(*BE.getRHS());
  861. break;
  862. }
  863. case MCExpr::SymbolRef:
  864. visitUsedSymbol(cast<MCSymbolRefExpr>(Expr).getSymbol());
  865. break;
  866. case MCExpr::Unary:
  867. visitUsedExpr(*cast<MCUnaryExpr>(Expr).getSubExpr());
  868. break;
  869. }
  870. }
  871. void MCStreamer::emitInstruction(const MCInst &Inst, const MCSubtargetInfo &) {
  872. // Scan for values.
  873. for (unsigned i = Inst.getNumOperands(); i--;)
  874. if (Inst.getOperand(i).isExpr())
  875. visitUsedExpr(*Inst.getOperand(i).getExpr());
  876. }
  877. void MCStreamer::emitPseudoProbe(uint64_t Guid, uint64_t Index, uint64_t Type,
  878. uint64_t Attr,
  879. const MCPseudoProbeInlineStack &InlineStack) {
  880. auto &Context = getContext();
  881. // Create a symbol at in the current section for use in the probe.
  882. MCSymbol *ProbeSym = Context.createTempSymbol();
  883. // Set the value of the symbol to use for the MCPseudoProbe.
  884. emitLabel(ProbeSym);
  885. // Create a (local) probe entry with the symbol.
  886. MCPseudoProbe Probe(ProbeSym, Guid, Index, Type, Attr);
  887. // Add the probe entry to this section's entries.
  888. Context.getMCPseudoProbeTable().getProbeSections().addPseudoProbe(
  889. getCurrentSectionOnly(), Probe, InlineStack);
  890. }
  891. void MCStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
  892. unsigned Size) {
  893. // Get the Hi-Lo expression.
  894. const MCExpr *Diff =
  895. MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
  896. MCSymbolRefExpr::create(Lo, Context), Context);
  897. const MCAsmInfo *MAI = Context.getAsmInfo();
  898. if (!MAI->doesSetDirectiveSuppressReloc()) {
  899. emitValue(Diff, Size);
  900. return;
  901. }
  902. // Otherwise, emit with .set (aka assignment).
  903. MCSymbol *SetLabel = Context.createTempSymbol("set");
  904. emitAssignment(SetLabel, Diff);
  905. emitSymbolValue(SetLabel, Size);
  906. }
  907. void MCStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
  908. const MCSymbol *Lo) {
  909. // Get the Hi-Lo expression.
  910. const MCExpr *Diff =
  911. MCBinaryExpr::createSub(MCSymbolRefExpr::create(Hi, Context),
  912. MCSymbolRefExpr::create(Lo, Context), Context);
  913. emitULEB128Value(Diff);
  914. }
  915. void MCStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {}
  916. void MCStreamer::emitThumbFunc(MCSymbol *Func) {}
  917. void MCStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
  918. void MCStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
  919. llvm_unreachable("this directive only supported on COFF targets");
  920. }
  921. void MCStreamer::EndCOFFSymbolDef() {
  922. llvm_unreachable("this directive only supported on COFF targets");
  923. }
  924. void MCStreamer::emitFileDirective(StringRef Filename) {}
  925. void MCStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
  926. llvm_unreachable("this directive only supported on COFF targets");
  927. }
  928. void MCStreamer::EmitCOFFSymbolType(int Type) {
  929. llvm_unreachable("this directive only supported on COFF targets");
  930. }
  931. void MCStreamer::emitXCOFFLocalCommonSymbol(MCSymbol *LabelSym, uint64_t Size,
  932. MCSymbol *CsectSym,
  933. unsigned ByteAlign) {
  934. llvm_unreachable("this directive only supported on XCOFF targets");
  935. }
  936. void MCStreamer::emitXCOFFSymbolLinkageWithVisibility(MCSymbol *Symbol,
  937. MCSymbolAttr Linkage,
  938. MCSymbolAttr Visibility) {
  939. llvm_unreachable("emitXCOFFSymbolLinkageWithVisibility is only supported on "
  940. "XCOFF targets");
  941. }
  942. void MCStreamer::emitXCOFFRenameDirective(const MCSymbol *Name,
  943. StringRef Rename) {
  944. llvm_unreachable("emitXCOFFRenameDirective is only supported on "
  945. "XCOFF targets");
  946. }
  947. void MCStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
  948. void MCStreamer::emitELFSymverDirective(StringRef AliasName,
  949. const MCSymbol *Aliasee) {}
  950. void MCStreamer::emitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  951. unsigned ByteAlignment) {}
  952. void MCStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  953. uint64_t Size, unsigned ByteAlignment) {}
  954. void MCStreamer::changeSection(MCSection *, const MCExpr *) {}
  955. void MCStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
  956. void MCStreamer::emitBytes(StringRef Data) {}
  957. void MCStreamer::emitBinaryData(StringRef Data) { emitBytes(Data); }
  958. void MCStreamer::emitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) {
  959. visitUsedExpr(*Value);
  960. }
  961. void MCStreamer::emitULEB128Value(const MCExpr *Value) {}
  962. void MCStreamer::emitSLEB128Value(const MCExpr *Value) {}
  963. void MCStreamer::emitFill(const MCExpr &NumBytes, uint64_t Value, SMLoc Loc) {}
  964. void MCStreamer::emitFill(const MCExpr &NumValues, int64_t Size, int64_t Expr,
  965. SMLoc Loc) {}
  966. void MCStreamer::emitValueToAlignment(unsigned ByteAlignment, int64_t Value,
  967. unsigned ValueSize,
  968. unsigned MaxBytesToEmit) {}
  969. void MCStreamer::emitCodeAlignment(unsigned ByteAlignment,
  970. unsigned MaxBytesToEmit) {}
  971. void MCStreamer::emitValueToOffset(const MCExpr *Offset, unsigned char Value,
  972. SMLoc Loc) {}
  973. void MCStreamer::emitBundleAlignMode(unsigned AlignPow2) {}
  974. void MCStreamer::emitBundleLock(bool AlignToEnd) {}
  975. void MCStreamer::finishImpl() {}
  976. void MCStreamer::emitBundleUnlock() {}
  977. void MCStreamer::SwitchSection(MCSection *Section, const MCExpr *Subsection) {
  978. assert(Section && "Cannot switch to a null section!");
  979. MCSectionSubPair curSection = SectionStack.back().first;
  980. SectionStack.back().second = curSection;
  981. if (MCSectionSubPair(Section, Subsection) != curSection) {
  982. changeSection(Section, Subsection);
  983. SectionStack.back().first = MCSectionSubPair(Section, Subsection);
  984. assert(!Section->hasEnded() && "Section already ended");
  985. MCSymbol *Sym = Section->getBeginSymbol();
  986. if (Sym && !Sym->isInSection())
  987. emitLabel(Sym);
  988. }
  989. }
  990. MCSymbol *MCStreamer::endSection(MCSection *Section) {
  991. // TODO: keep track of the last subsection so that this symbol appears in the
  992. // correct place.
  993. MCSymbol *Sym = Section->getEndSymbol(Context);
  994. if (Sym->isInSection())
  995. return Sym;
  996. SwitchSection(Section);
  997. emitLabel(Sym);
  998. return Sym;
  999. }
  1000. static VersionTuple
  1001. targetVersionOrMinimumSupportedOSVersion(const Triple &Target,
  1002. VersionTuple TargetVersion) {
  1003. VersionTuple Min = Target.getMinimumSupportedOSVersion();
  1004. return !Min.empty() && Min > TargetVersion ? Min : TargetVersion;
  1005. }
  1006. static MCVersionMinType
  1007. getMachoVersionMinLoadCommandType(const Triple &Target) {
  1008. assert(Target.isOSDarwin() && "expected a darwin OS");
  1009. switch (Target.getOS()) {
  1010. case Triple::MacOSX:
  1011. case Triple::Darwin:
  1012. return MCVM_OSXVersionMin;
  1013. case Triple::IOS:
  1014. assert(!Target.isMacCatalystEnvironment() &&
  1015. "mac Catalyst should use LC_BUILD_VERSION");
  1016. return MCVM_IOSVersionMin;
  1017. case Triple::TvOS:
  1018. return MCVM_TvOSVersionMin;
  1019. case Triple::WatchOS:
  1020. return MCVM_WatchOSVersionMin;
  1021. default:
  1022. break;
  1023. }
  1024. llvm_unreachable("unexpected OS type");
  1025. }
  1026. static VersionTuple getMachoBuildVersionSupportedOS(const Triple &Target) {
  1027. assert(Target.isOSDarwin() && "expected a darwin OS");
  1028. switch (Target.getOS()) {
  1029. case Triple::MacOSX:
  1030. case Triple::Darwin:
  1031. return VersionTuple(10, 14);
  1032. case Triple::IOS:
  1033. // Mac Catalyst always uses the build version load command.
  1034. if (Target.isMacCatalystEnvironment())
  1035. return VersionTuple();
  1036. LLVM_FALLTHROUGH;
  1037. case Triple::TvOS:
  1038. return VersionTuple(12);
  1039. case Triple::WatchOS:
  1040. return VersionTuple(5);
  1041. default:
  1042. break;
  1043. }
  1044. llvm_unreachable("unexpected OS type");
  1045. }
  1046. static MachO::PlatformType
  1047. getMachoBuildVersionPlatformType(const Triple &Target) {
  1048. assert(Target.isOSDarwin() && "expected a darwin OS");
  1049. switch (Target.getOS()) {
  1050. case Triple::MacOSX:
  1051. case Triple::Darwin:
  1052. return MachO::PLATFORM_MACOS;
  1053. case Triple::IOS:
  1054. if (Target.isMacCatalystEnvironment())
  1055. return MachO::PLATFORM_MACCATALYST;
  1056. return Target.isSimulatorEnvironment() ? MachO::PLATFORM_IOSSIMULATOR
  1057. : MachO::PLATFORM_IOS;
  1058. case Triple::TvOS:
  1059. return Target.isSimulatorEnvironment() ? MachO::PLATFORM_TVOSSIMULATOR
  1060. : MachO::PLATFORM_TVOS;
  1061. case Triple::WatchOS:
  1062. return Target.isSimulatorEnvironment() ? MachO::PLATFORM_WATCHOSSIMULATOR
  1063. : MachO::PLATFORM_WATCHOS;
  1064. default:
  1065. break;
  1066. }
  1067. llvm_unreachable("unexpected OS type");
  1068. }
  1069. void MCStreamer::emitVersionForTarget(const Triple &Target,
  1070. const VersionTuple &SDKVersion) {
  1071. if (!Target.isOSBinFormatMachO() || !Target.isOSDarwin())
  1072. return;
  1073. // Do we even know the version?
  1074. if (Target.getOSMajorVersion() == 0)
  1075. return;
  1076. unsigned Major = 0;
  1077. unsigned Minor = 0;
  1078. unsigned Update = 0;
  1079. switch (Target.getOS()) {
  1080. case Triple::MacOSX:
  1081. case Triple::Darwin:
  1082. Target.getMacOSXVersion(Major, Minor, Update);
  1083. break;
  1084. case Triple::IOS:
  1085. case Triple::TvOS:
  1086. Target.getiOSVersion(Major, Minor, Update);
  1087. break;
  1088. case Triple::WatchOS:
  1089. Target.getWatchOSVersion(Major, Minor, Update);
  1090. break;
  1091. default:
  1092. llvm_unreachable("unexpected OS type");
  1093. }
  1094. assert(Major != 0 && "A non-zero major version is expected");
  1095. auto LinkedTargetVersion = targetVersionOrMinimumSupportedOSVersion(
  1096. Target, VersionTuple(Major, Minor, Update));
  1097. auto BuildVersionOSVersion = getMachoBuildVersionSupportedOS(Target);
  1098. if (BuildVersionOSVersion.empty() ||
  1099. LinkedTargetVersion >= BuildVersionOSVersion)
  1100. return emitBuildVersion(getMachoBuildVersionPlatformType(Target),
  1101. LinkedTargetVersion.getMajor(),
  1102. *LinkedTargetVersion.getMinor(),
  1103. *LinkedTargetVersion.getSubminor(), SDKVersion);
  1104. emitVersionMin(getMachoVersionMinLoadCommandType(Target),
  1105. LinkedTargetVersion.getMajor(),
  1106. *LinkedTargetVersion.getMinor(),
  1107. *LinkedTargetVersion.getSubminor(), SDKVersion);
  1108. }