MCContext.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. //===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
  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/MCContext.h"
  9. #include "llvm/ADT/DenseMapInfo.h"
  10. #include "llvm/ADT/SmallString.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringMap.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/Twine.h"
  15. #include "llvm/BinaryFormat/COFF.h"
  16. #include "llvm/BinaryFormat/ELF.h"
  17. #include "llvm/BinaryFormat/Wasm.h"
  18. #include "llvm/BinaryFormat/XCOFF.h"
  19. #include "llvm/MC/MCAsmInfo.h"
  20. #include "llvm/MC/MCCodeView.h"
  21. #include "llvm/MC/MCDwarf.h"
  22. #include "llvm/MC/MCExpr.h"
  23. #include "llvm/MC/MCFragment.h"
  24. #include "llvm/MC/MCInst.h"
  25. #include "llvm/MC/MCLabel.h"
  26. #include "llvm/MC/MCSectionCOFF.h"
  27. #include "llvm/MC/MCSectionDXContainer.h"
  28. #include "llvm/MC/MCSectionELF.h"
  29. #include "llvm/MC/MCSectionGOFF.h"
  30. #include "llvm/MC/MCSectionMachO.h"
  31. #include "llvm/MC/MCSectionSPIRV.h"
  32. #include "llvm/MC/MCSectionWasm.h"
  33. #include "llvm/MC/MCSectionXCOFF.h"
  34. #include "llvm/MC/MCStreamer.h"
  35. #include "llvm/MC/MCSubtargetInfo.h"
  36. #include "llvm/MC/MCSymbol.h"
  37. #include "llvm/MC/MCSymbolCOFF.h"
  38. #include "llvm/MC/MCSymbolELF.h"
  39. #include "llvm/MC/MCSymbolGOFF.h"
  40. #include "llvm/MC/MCSymbolMachO.h"
  41. #include "llvm/MC/MCSymbolWasm.h"
  42. #include "llvm/MC/MCSymbolXCOFF.h"
  43. #include "llvm/MC/MCTargetOptions.h"
  44. #include "llvm/MC/SectionKind.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Support/ErrorHandling.h"
  48. #include "llvm/Support/MemoryBuffer.h"
  49. #include "llvm/Support/Path.h"
  50. #include "llvm/Support/SMLoc.h"
  51. #include "llvm/Support/SourceMgr.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include <cassert>
  54. #include <cstdlib>
  55. #include <optional>
  56. #include <tuple>
  57. #include <utility>
  58. using namespace llvm;
  59. static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
  60. std::vector<const MDNode *> &) {
  61. SMD.print(nullptr, errs());
  62. }
  63. MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
  64. const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
  65. const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
  66. bool DoAutoReset, StringRef Swift5ReflSegmentName)
  67. : Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
  68. SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
  69. MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator), UsedNames(Allocator),
  70. InlineAsmUsedLabelNames(Allocator),
  71. CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
  72. AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
  73. SecureLogFile = TargetOptions ? TargetOptions->AsSecureLogFile : "";
  74. if (SrcMgr && SrcMgr->getNumBuffers())
  75. MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
  76. ->getBufferIdentifier());
  77. switch (TheTriple.getObjectFormat()) {
  78. case Triple::MachO:
  79. Env = IsMachO;
  80. break;
  81. case Triple::COFF:
  82. if (!TheTriple.isOSWindows())
  83. report_fatal_error(
  84. "Cannot initialize MC for non-Windows COFF object files.");
  85. Env = IsCOFF;
  86. break;
  87. case Triple::ELF:
  88. Env = IsELF;
  89. break;
  90. case Triple::Wasm:
  91. Env = IsWasm;
  92. break;
  93. case Triple::XCOFF:
  94. Env = IsXCOFF;
  95. break;
  96. case Triple::GOFF:
  97. Env = IsGOFF;
  98. break;
  99. case Triple::DXContainer:
  100. Env = IsDXContainer;
  101. break;
  102. case Triple::SPIRV:
  103. Env = IsSPIRV;
  104. break;
  105. case Triple::UnknownObjectFormat:
  106. report_fatal_error("Cannot initialize MC for unknown object file format.");
  107. break;
  108. }
  109. }
  110. MCContext::~MCContext() {
  111. if (AutoReset)
  112. reset();
  113. // NOTE: The symbols are all allocated out of a bump pointer allocator,
  114. // we don't need to free them here.
  115. }
  116. void MCContext::initInlineSourceManager() {
  117. if (!InlineSrcMgr)
  118. InlineSrcMgr.reset(new SourceMgr());
  119. }
  120. //===----------------------------------------------------------------------===//
  121. // Module Lifetime Management
  122. //===----------------------------------------------------------------------===//
  123. void MCContext::reset() {
  124. SrcMgr = nullptr;
  125. InlineSrcMgr.reset();
  126. LocInfos.clear();
  127. DiagHandler = defaultDiagHandler;
  128. // Call the destructors so the fragments are freed
  129. COFFAllocator.DestroyAll();
  130. DXCAllocator.DestroyAll();
  131. ELFAllocator.DestroyAll();
  132. GOFFAllocator.DestroyAll();
  133. MachOAllocator.DestroyAll();
  134. WasmAllocator.DestroyAll();
  135. XCOFFAllocator.DestroyAll();
  136. MCInstAllocator.DestroyAll();
  137. SPIRVAllocator.DestroyAll();
  138. MCSubtargetAllocator.DestroyAll();
  139. InlineAsmUsedLabelNames.clear();
  140. UsedNames.clear();
  141. Symbols.clear();
  142. Allocator.Reset();
  143. Instances.clear();
  144. CompilationDir.clear();
  145. MainFileName.clear();
  146. MCDwarfLineTablesCUMap.clear();
  147. SectionsForRanges.clear();
  148. MCGenDwarfLabelEntries.clear();
  149. DwarfDebugFlags = StringRef();
  150. DwarfCompileUnitID = 0;
  151. CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
  152. CVContext.reset();
  153. MachOUniquingMap.clear();
  154. ELFUniquingMap.clear();
  155. GOFFUniquingMap.clear();
  156. COFFUniquingMap.clear();
  157. WasmUniquingMap.clear();
  158. XCOFFUniquingMap.clear();
  159. DXCUniquingMap.clear();
  160. ELFEntrySizeMap.clear();
  161. ELFSeenGenericMergeableSections.clear();
  162. NextID.clear();
  163. AllowTemporaryLabels = true;
  164. DwarfLocSeen = false;
  165. GenDwarfForAssembly = false;
  166. GenDwarfFileNumber = 0;
  167. HadError = false;
  168. }
  169. //===----------------------------------------------------------------------===//
  170. // MCInst Management
  171. //===----------------------------------------------------------------------===//
  172. MCInst *MCContext::createMCInst() {
  173. return new (MCInstAllocator.Allocate()) MCInst;
  174. }
  175. //===----------------------------------------------------------------------===//
  176. // Symbol Manipulation
  177. //===----------------------------------------------------------------------===//
  178. MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
  179. SmallString<128> NameSV;
  180. StringRef NameRef = Name.toStringRef(NameSV);
  181. assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
  182. MCSymbol *&Sym = Symbols[NameRef];
  183. if (!Sym)
  184. Sym = createSymbol(NameRef, false, false);
  185. return Sym;
  186. }
  187. MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
  188. unsigned Idx) {
  189. return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
  190. "$frame_escape_" + Twine(Idx));
  191. }
  192. MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
  193. return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
  194. "$parent_frame_offset");
  195. }
  196. MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
  197. return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
  198. FuncName);
  199. }
  200. MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
  201. bool IsTemporary) {
  202. static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
  203. "MCSymbol classes must be trivially destructible");
  204. static_assert(std::is_trivially_destructible<MCSymbolELF>(),
  205. "MCSymbol classes must be trivially destructible");
  206. static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
  207. "MCSymbol classes must be trivially destructible");
  208. static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
  209. "MCSymbol classes must be trivially destructible");
  210. static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
  211. "MCSymbol classes must be trivially destructible");
  212. switch (getObjectFileType()) {
  213. case MCContext::IsCOFF:
  214. return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
  215. case MCContext::IsELF:
  216. return new (Name, *this) MCSymbolELF(Name, IsTemporary);
  217. case MCContext::IsGOFF:
  218. return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
  219. case MCContext::IsMachO:
  220. return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
  221. case MCContext::IsWasm:
  222. return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
  223. case MCContext::IsXCOFF:
  224. return createXCOFFSymbolImpl(Name, IsTemporary);
  225. case MCContext::IsDXContainer:
  226. break;
  227. case MCContext::IsSPIRV:
  228. return new (Name, *this)
  229. MCSymbol(MCSymbol::SymbolKindUnset, Name, IsTemporary);
  230. }
  231. return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
  232. IsTemporary);
  233. }
  234. MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
  235. bool CanBeUnnamed) {
  236. if (CanBeUnnamed && !UseNamesOnTempLabels)
  237. return createSymbolImpl(nullptr, true);
  238. // Determine whether this is a user written assembler temporary or normal
  239. // label, if used.
  240. bool IsTemporary = CanBeUnnamed;
  241. if (AllowTemporaryLabels && !IsTemporary)
  242. IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
  243. SmallString<128> NewName = Name;
  244. bool AddSuffix = AlwaysAddSuffix;
  245. unsigned &NextUniqueID = NextID[Name];
  246. while (true) {
  247. if (AddSuffix) {
  248. NewName.resize(Name.size());
  249. raw_svector_ostream(NewName) << NextUniqueID++;
  250. }
  251. auto NameEntry = UsedNames.insert(std::make_pair(NewName.str(), true));
  252. if (NameEntry.second || !NameEntry.first->second) {
  253. // Ok, we found a name.
  254. // Mark it as used for a non-section symbol.
  255. NameEntry.first->second = true;
  256. // Have the MCSymbol object itself refer to the copy of the string that is
  257. // embedded in the UsedNames entry.
  258. return createSymbolImpl(&*NameEntry.first, IsTemporary);
  259. }
  260. assert(IsTemporary && "Cannot rename non-temporary symbols");
  261. AddSuffix = true;
  262. }
  263. llvm_unreachable("Infinite loop");
  264. }
  265. MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
  266. SmallString<128> NameSV;
  267. raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
  268. return createSymbol(NameSV, AlwaysAddSuffix, true);
  269. }
  270. MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
  271. SmallString<128> NameSV;
  272. raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
  273. return createSymbol(NameSV, true, false);
  274. }
  275. MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
  276. SmallString<128> NameSV;
  277. raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
  278. return createSymbol(NameSV, true, false);
  279. }
  280. MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
  281. MCSymbol *MCContext::createNamedTempSymbol() {
  282. return createNamedTempSymbol("tmp");
  283. }
  284. unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
  285. MCLabel *&Label = Instances[LocalLabelVal];
  286. if (!Label)
  287. Label = new (*this) MCLabel(0);
  288. return Label->incInstance();
  289. }
  290. unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
  291. MCLabel *&Label = Instances[LocalLabelVal];
  292. if (!Label)
  293. Label = new (*this) MCLabel(0);
  294. return Label->getInstance();
  295. }
  296. MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
  297. unsigned Instance) {
  298. MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
  299. if (!Sym)
  300. Sym = createNamedTempSymbol();
  301. return Sym;
  302. }
  303. MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
  304. unsigned Instance = NextInstance(LocalLabelVal);
  305. return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
  306. }
  307. MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
  308. bool Before) {
  309. unsigned Instance = GetInstance(LocalLabelVal);
  310. if (!Before)
  311. ++Instance;
  312. return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
  313. }
  314. MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
  315. SmallString<128> NameSV;
  316. StringRef NameRef = Name.toStringRef(NameSV);
  317. return Symbols.lookup(NameRef);
  318. }
  319. void MCContext::setSymbolValue(MCStreamer &Streamer,
  320. StringRef Sym,
  321. uint64_t Val) {
  322. auto Symbol = getOrCreateSymbol(Sym);
  323. Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
  324. }
  325. void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
  326. InlineAsmUsedLabelNames[Sym->getName()] = Sym;
  327. }
  328. MCSymbolXCOFF *
  329. MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
  330. bool IsTemporary) {
  331. if (!Name)
  332. return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
  333. StringRef OriginalName = Name->first();
  334. if (OriginalName.startswith("._Renamed..") ||
  335. OriginalName.startswith("_Renamed.."))
  336. reportError(SMLoc(), "invalid symbol name from source");
  337. if (MAI->isValidUnquotedName(OriginalName))
  338. return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
  339. // Now we have a name that contains invalid character(s) for XCOFF symbol.
  340. // Let's replace with something valid, but save the original name so that
  341. // we could still use the original name in the symbol table.
  342. SmallString<128> InvalidName(OriginalName);
  343. // If it's an entry point symbol, we will keep the '.'
  344. // in front for the convention purpose. Otherwise, add "_Renamed.."
  345. // as prefix to signal this is an renamed symbol.
  346. const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
  347. SmallString<128> ValidName =
  348. StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
  349. // Append the hex values of '_' and invalid characters with "_Renamed..";
  350. // at the same time replace invalid characters with '_'.
  351. for (size_t I = 0; I < InvalidName.size(); ++I) {
  352. if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
  353. raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
  354. InvalidName[I] = '_';
  355. }
  356. }
  357. // Skip entry point symbol's '.' as we already have a '.' in front of
  358. // "_Renamed".
  359. if (IsEntryPoint)
  360. ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
  361. else
  362. ValidName.append(InvalidName);
  363. auto NameEntry = UsedNames.insert(std::make_pair(ValidName.str(), true));
  364. assert((NameEntry.second || !NameEntry.first->second) &&
  365. "This name is used somewhere else.");
  366. // Mark the name as used for a non-section symbol.
  367. NameEntry.first->second = true;
  368. // Have the MCSymbol object itself refer to the copy of the string
  369. // that is embedded in the UsedNames entry.
  370. MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
  371. MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
  372. XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
  373. return XSym;
  374. }
  375. //===----------------------------------------------------------------------===//
  376. // Section Management
  377. //===----------------------------------------------------------------------===//
  378. MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
  379. unsigned TypeAndAttributes,
  380. unsigned Reserved2, SectionKind Kind,
  381. const char *BeginSymName) {
  382. // We unique sections by their segment/section pair. The returned section
  383. // may not have the same flags as the requested section, if so this should be
  384. // diagnosed by the client as an error.
  385. // Form the name to look up.
  386. assert(Section.size() <= 16 && "section name is too long");
  387. assert(!memchr(Section.data(), '\0', Section.size()) &&
  388. "section name cannot contain NUL");
  389. // Do the lookup, if we have a hit, return it.
  390. auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
  391. if (!R.second)
  392. return R.first->second;
  393. MCSymbol *Begin = nullptr;
  394. if (BeginSymName)
  395. Begin = createTempSymbol(BeginSymName, false);
  396. // Otherwise, return a new section.
  397. StringRef Name = R.first->first();
  398. R.first->second = new (MachOAllocator.Allocate())
  399. MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
  400. TypeAndAttributes, Reserved2, Kind, Begin);
  401. return R.first->second;
  402. }
  403. MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
  404. unsigned Flags, SectionKind K,
  405. unsigned EntrySize,
  406. const MCSymbolELF *Group,
  407. bool Comdat, unsigned UniqueID,
  408. const MCSymbolELF *LinkedToSym) {
  409. MCSymbolELF *R;
  410. MCSymbol *&Sym = Symbols[Section];
  411. // A section symbol can not redefine regular symbols. There may be multiple
  412. // sections with the same name, in which case the first such section wins.
  413. if (Sym && Sym->isDefined() &&
  414. (!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
  415. reportError(SMLoc(), "invalid symbol redefinition");
  416. if (Sym && Sym->isUndefined()) {
  417. R = cast<MCSymbolELF>(Sym);
  418. } else {
  419. auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
  420. R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
  421. if (!Sym)
  422. Sym = R;
  423. }
  424. R->setBinding(ELF::STB_LOCAL);
  425. R->setType(ELF::STT_SECTION);
  426. auto *Ret = new (ELFAllocator.Allocate())
  427. MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
  428. R, LinkedToSym);
  429. auto *F = new MCDataFragment();
  430. Ret->getFragmentList().insert(Ret->begin(), F);
  431. F->setParent(Ret);
  432. R->setFragment(F);
  433. return Ret;
  434. }
  435. MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
  436. unsigned Flags, unsigned EntrySize,
  437. const MCSymbolELF *Group,
  438. const MCSectionELF *RelInfoSection) {
  439. StringMap<bool>::iterator I;
  440. bool Inserted;
  441. std::tie(I, Inserted) =
  442. RelSecNames.insert(std::make_pair(Name.str(), true));
  443. return createELFSectionImpl(
  444. I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
  445. true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
  446. }
  447. MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
  448. const Twine &Suffix, unsigned Type,
  449. unsigned Flags,
  450. unsigned EntrySize) {
  451. return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
  452. /*IsComdat=*/true);
  453. }
  454. MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
  455. unsigned Flags, unsigned EntrySize,
  456. const Twine &Group, bool IsComdat,
  457. unsigned UniqueID,
  458. const MCSymbolELF *LinkedToSym) {
  459. MCSymbolELF *GroupSym = nullptr;
  460. if (!Group.isTriviallyEmpty() && !Group.str().empty())
  461. GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
  462. return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
  463. UniqueID, LinkedToSym);
  464. }
  465. MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
  466. unsigned Flags, unsigned EntrySize,
  467. const MCSymbolELF *GroupSym,
  468. bool IsComdat, unsigned UniqueID,
  469. const MCSymbolELF *LinkedToSym) {
  470. StringRef Group = "";
  471. if (GroupSym)
  472. Group = GroupSym->getName();
  473. assert(!(LinkedToSym && LinkedToSym->getName().empty()));
  474. // Do the lookup, if we have a hit, return it.
  475. auto IterBool = ELFUniquingMap.insert(std::make_pair(
  476. ELFSectionKey{Section.str(), Group,
  477. LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
  478. nullptr));
  479. auto &Entry = *IterBool.first;
  480. if (!IterBool.second)
  481. return Entry.second;
  482. StringRef CachedName = Entry.first.SectionName;
  483. SectionKind Kind;
  484. if (Flags & ELF::SHF_ARM_PURECODE)
  485. Kind = SectionKind::getExecuteOnly();
  486. else if (Flags & ELF::SHF_EXECINSTR)
  487. Kind = SectionKind::getText();
  488. else if (~Flags & ELF::SHF_WRITE)
  489. Kind = SectionKind::getReadOnly();
  490. else if (Flags & ELF::SHF_TLS)
  491. Kind = (Type & ELF::SHT_NOBITS) ? SectionKind::getThreadBSS()
  492. : SectionKind::getThreadData();
  493. else
  494. // Default to `SectionKind::getText()`. This is the default for gas as
  495. // well. The condition that falls into this case is where we do not have any
  496. // section flags and must infer a classification rather than where we have
  497. // section flags (i.e. this is not that SHF_EXECINSTR is unset bur rather it
  498. // is unknown).
  499. Kind = llvm::StringSwitch<SectionKind>(CachedName)
  500. .Case(".bss", SectionKind::getBSS())
  501. .StartsWith(".bss.", SectionKind::getBSS())
  502. .StartsWith(".gnu.linkonce.b.", SectionKind::getBSS())
  503. .StartsWith(".llvm.linkonce.b.", SectionKind::getBSS())
  504. .Case(".data", SectionKind::getData())
  505. .Case(".data1", SectionKind::getData())
  506. .Case(".data.rel.ro", SectionKind::getReadOnlyWithRel())
  507. .StartsWith(".data.", SectionKind::getData())
  508. .Case(".rodata", SectionKind::getReadOnly())
  509. .Case(".rodata1", SectionKind::getReadOnly())
  510. .StartsWith(".rodata.", SectionKind::getReadOnly())
  511. .Case(".tbss", SectionKind::getThreadBSS())
  512. .StartsWith(".tbss.", SectionKind::getThreadData())
  513. .StartsWith(".gnu.linkonce.tb.", SectionKind::getThreadData())
  514. .StartsWith(".llvm.linkonce.tb.", SectionKind::getThreadData())
  515. .Case(".tdata", SectionKind::getThreadData())
  516. .StartsWith(".tdata.", SectionKind::getThreadData())
  517. .StartsWith(".gnu.linkonce.td.", SectionKind::getThreadData())
  518. .StartsWith(".llvm.linkonce.td.", SectionKind::getThreadData())
  519. .StartsWith(".debug_", SectionKind::getMetadata())
  520. .Default(SectionKind::getText());
  521. MCSectionELF *Result =
  522. createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
  523. IsComdat, UniqueID, LinkedToSym);
  524. Entry.second = Result;
  525. recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
  526. Result->getUniqueID(), Result->getEntrySize());
  527. return Result;
  528. }
  529. MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
  530. bool IsComdat) {
  531. return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
  532. SectionKind::getReadOnly(), 4, Group, IsComdat,
  533. MCSection::NonUniqueID, nullptr);
  534. }
  535. void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
  536. unsigned Flags, unsigned UniqueID,
  537. unsigned EntrySize) {
  538. bool IsMergeable = Flags & ELF::SHF_MERGE;
  539. if (UniqueID == GenericSectionID)
  540. ELFSeenGenericMergeableSections.insert(SectionName);
  541. // For mergeable sections or non-mergeable sections with a generic mergeable
  542. // section name we enter their Unique ID into the ELFEntrySizeMap so that
  543. // compatible globals can be assigned to the same section.
  544. if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
  545. ELFEntrySizeMap.insert(std::make_pair(
  546. ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
  547. }
  548. }
  549. bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
  550. return SectionName.startswith(".rodata.str") ||
  551. SectionName.startswith(".rodata.cst");
  552. }
  553. bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
  554. return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
  555. ELFSeenGenericMergeableSections.count(SectionName);
  556. }
  557. std::optional<unsigned>
  558. MCContext::getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags,
  559. unsigned EntrySize) {
  560. auto I = ELFEntrySizeMap.find(
  561. MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
  562. return (I != ELFEntrySizeMap.end()) ? std::optional<unsigned>(I->second)
  563. : std::nullopt;
  564. }
  565. MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind,
  566. MCSection *Parent,
  567. const MCExpr *SubsectionId) {
  568. // Do the lookup. If we don't have a hit, return a new section.
  569. auto &GOFFSection = GOFFUniquingMap[Section.str()];
  570. if (!GOFFSection)
  571. GOFFSection = new (GOFFAllocator.Allocate())
  572. MCSectionGOFF(Section, Kind, Parent, SubsectionId);
  573. return GOFFSection;
  574. }
  575. MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
  576. unsigned Characteristics,
  577. SectionKind Kind,
  578. StringRef COMDATSymName, int Selection,
  579. unsigned UniqueID,
  580. const char *BeginSymName) {
  581. MCSymbol *COMDATSymbol = nullptr;
  582. if (!COMDATSymName.empty()) {
  583. COMDATSymbol = getOrCreateSymbol(COMDATSymName);
  584. COMDATSymName = COMDATSymbol->getName();
  585. }
  586. // Do the lookup, if we have a hit, return it.
  587. COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
  588. auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
  589. auto Iter = IterBool.first;
  590. if (!IterBool.second)
  591. return Iter->second;
  592. MCSymbol *Begin = nullptr;
  593. if (BeginSymName)
  594. Begin = createTempSymbol(BeginSymName, false);
  595. StringRef CachedName = Iter->first.SectionName;
  596. MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
  597. CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
  598. Iter->second = Result;
  599. return Result;
  600. }
  601. MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
  602. unsigned Characteristics,
  603. SectionKind Kind,
  604. const char *BeginSymName) {
  605. return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
  606. BeginSymName);
  607. }
  608. MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
  609. const MCSymbol *KeySym,
  610. unsigned UniqueID) {
  611. // Return the normal section if we don't have to be associative or unique.
  612. if (!KeySym && UniqueID == GenericSectionID)
  613. return Sec;
  614. // If we have a key symbol, make an associative section with the same name and
  615. // kind as the normal section.
  616. unsigned Characteristics = Sec->getCharacteristics();
  617. if (KeySym) {
  618. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  619. return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
  620. KeySym->getName(),
  621. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
  622. }
  623. return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
  624. UniqueID);
  625. }
  626. MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
  627. unsigned Flags, const Twine &Group,
  628. unsigned UniqueID,
  629. const char *BeginSymName) {
  630. MCSymbolWasm *GroupSym = nullptr;
  631. if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
  632. GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
  633. GroupSym->setComdat(true);
  634. }
  635. return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
  636. }
  637. MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
  638. unsigned Flags,
  639. const MCSymbolWasm *GroupSym,
  640. unsigned UniqueID,
  641. const char *BeginSymName) {
  642. StringRef Group = "";
  643. if (GroupSym)
  644. Group = GroupSym->getName();
  645. // Do the lookup, if we have a hit, return it.
  646. auto IterBool = WasmUniquingMap.insert(
  647. std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
  648. auto &Entry = *IterBool.first;
  649. if (!IterBool.second)
  650. return Entry.second;
  651. StringRef CachedName = Entry.first.SectionName;
  652. MCSymbol *Begin = createSymbol(CachedName, true, false);
  653. Symbols[Begin->getName()] = Begin;
  654. cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
  655. MCSectionWasm *Result = new (WasmAllocator.Allocate())
  656. MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
  657. Entry.second = Result;
  658. auto *F = new MCDataFragment();
  659. Result->getFragmentList().insert(Result->begin(), F);
  660. F->setParent(Result);
  661. Begin->setFragment(F);
  662. return Result;
  663. }
  664. bool MCContext::hasXCOFFSection(StringRef Section,
  665. XCOFF::CsectProperties CsectProp) const {
  666. return XCOFFUniquingMap.count(
  667. XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
  668. }
  669. MCSectionXCOFF *MCContext::getXCOFFSection(
  670. StringRef Section, SectionKind Kind,
  671. std::optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
  672. const char *BeginSymName,
  673. std::optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
  674. bool IsDwarfSec = DwarfSectionSubtypeFlags.has_value();
  675. assert((IsDwarfSec != CsectProp.has_value()) && "Invalid XCOFF section!");
  676. // Do the lookup. If we have a hit, return it.
  677. auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
  678. IsDwarfSec ? XCOFFSectionKey(Section.str(), *DwarfSectionSubtypeFlags)
  679. : XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
  680. nullptr));
  681. auto &Entry = *IterBool.first;
  682. if (!IterBool.second) {
  683. MCSectionXCOFF *ExistedEntry = Entry.second;
  684. if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
  685. report_fatal_error("section's multiply symbols policy does not match");
  686. return ExistedEntry;
  687. }
  688. // Otherwise, return a new section.
  689. StringRef CachedName = Entry.first.SectionName;
  690. MCSymbolXCOFF *QualName = nullptr;
  691. // Debug section don't have storage class attribute.
  692. if (IsDwarfSec)
  693. QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
  694. else
  695. QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
  696. CachedName + "[" +
  697. XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
  698. MCSymbol *Begin = nullptr;
  699. if (BeginSymName)
  700. Begin = createTempSymbol(BeginSymName, false);
  701. // QualName->getUnqualifiedName() and CachedName are the same except when
  702. // CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
  703. MCSectionXCOFF *Result = nullptr;
  704. if (IsDwarfSec)
  705. Result = new (XCOFFAllocator.Allocate()) MCSectionXCOFF(
  706. QualName->getUnqualifiedName(), Kind, QualName,
  707. *DwarfSectionSubtypeFlags, Begin, CachedName, MultiSymbolsAllowed);
  708. else
  709. Result = new (XCOFFAllocator.Allocate())
  710. MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
  711. CsectProp->Type, Kind, QualName, Begin, CachedName,
  712. MultiSymbolsAllowed);
  713. Entry.second = Result;
  714. auto *F = new MCDataFragment();
  715. Result->getFragmentList().insert(Result->begin(), F);
  716. F->setParent(Result);
  717. if (Begin)
  718. Begin->setFragment(F);
  719. // We might miss calculating the symbols difference as absolute value before
  720. // adding fixups when symbol_A without the fragment set is the csect itself
  721. // and symbol_B is in it.
  722. // TODO: Currently we only set the fragment for XMC_PR csects because we don't
  723. // have other cases that hit this problem yet.
  724. if (!IsDwarfSec && CsectProp->MappingClass == XCOFF::XMC_PR)
  725. QualName->setFragment(F);
  726. return Result;
  727. }
  728. MCSectionSPIRV *MCContext::getSPIRVSection() {
  729. MCSymbol *Begin = nullptr;
  730. MCSectionSPIRV *Result = new (SPIRVAllocator.Allocate())
  731. MCSectionSPIRV(SectionKind::getText(), Begin);
  732. auto *F = new MCDataFragment();
  733. Result->getFragmentList().insert(Result->begin(), F);
  734. F->setParent(Result);
  735. if (Begin)
  736. Begin->setFragment(F);
  737. return Result;
  738. }
  739. MCSectionDXContainer *MCContext::getDXContainerSection(StringRef Section,
  740. SectionKind K) {
  741. // Do the lookup, if we have a hit, return it.
  742. auto ItInsertedPair = DXCUniquingMap.try_emplace(Section);
  743. if (!ItInsertedPair.second)
  744. return ItInsertedPair.first->second;
  745. auto MapIt = ItInsertedPair.first;
  746. // Grab the name from the StringMap. Since the Section is going to keep a
  747. // copy of this StringRef we need to make sure the underlying string stays
  748. // alive as long as we need it.
  749. StringRef Name = MapIt->first();
  750. MapIt->second =
  751. new (DXCAllocator.Allocate()) MCSectionDXContainer(Name, K, nullptr);
  752. // The first fragment will store the header
  753. auto *F = new MCDataFragment();
  754. MapIt->second->getFragmentList().insert(MapIt->second->begin(), F);
  755. F->setParent(MapIt->second);
  756. return MapIt->second;
  757. }
  758. MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
  759. return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
  760. }
  761. void MCContext::addDebugPrefixMapEntry(const std::string &From,
  762. const std::string &To) {
  763. DebugPrefixMap.insert(std::make_pair(From, To));
  764. }
  765. void MCContext::remapDebugPath(SmallVectorImpl<char> &Path) {
  766. for (const auto &[From, To] : DebugPrefixMap)
  767. if (llvm::sys::path::replace_path_prefix(Path, From, To))
  768. break;
  769. }
  770. void MCContext::RemapDebugPaths() {
  771. const auto &DebugPrefixMap = this->DebugPrefixMap;
  772. if (DebugPrefixMap.empty())
  773. return;
  774. // Remap compilation directory.
  775. remapDebugPath(CompilationDir);
  776. // Remap MCDwarfDirs and RootFile.Name in all compilation units.
  777. SmallString<256> P;
  778. for (auto &CUIDTablePair : MCDwarfLineTablesCUMap) {
  779. for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs()) {
  780. P = Dir;
  781. remapDebugPath(P);
  782. Dir = std::string(P);
  783. }
  784. // Used by DW_TAG_compile_unit's DT_AT_name and DW_TAG_label's
  785. // DW_AT_decl_file for DWARF v5 generated for assembly source.
  786. P = CUIDTablePair.second.getRootFile().Name;
  787. remapDebugPath(P);
  788. CUIDTablePair.second.getRootFile().Name = std::string(P);
  789. }
  790. }
  791. //===----------------------------------------------------------------------===//
  792. // Dwarf Management
  793. //===----------------------------------------------------------------------===//
  794. EmitDwarfUnwindType MCContext::emitDwarfUnwindInfo() const {
  795. if (!TargetOptions)
  796. return EmitDwarfUnwindType::Default;
  797. return TargetOptions->EmitDwarfUnwind;
  798. }
  799. void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
  800. // MCDwarf needs the root file as well as the compilation directory.
  801. // If we find a '.file 0' directive that will supersede these values.
  802. std::optional<MD5::MD5Result> Cksum;
  803. if (getDwarfVersion() >= 5) {
  804. MD5 Hash;
  805. MD5::MD5Result Sum;
  806. Hash.update(Buffer);
  807. Hash.final(Sum);
  808. Cksum = Sum;
  809. }
  810. // Canonicalize the root filename. It cannot be empty, and should not
  811. // repeat the compilation dir.
  812. // The MCContext ctor initializes MainFileName to the name associated with
  813. // the SrcMgr's main file ID, which might be the same as InputFileName (and
  814. // possibly include directory components).
  815. // Or, MainFileName might have been overridden by a -main-file-name option,
  816. // which is supposed to be just a base filename with no directory component.
  817. // So, if the InputFileName and MainFileName are not equal, assume
  818. // MainFileName is a substitute basename and replace the last component.
  819. SmallString<1024> FileNameBuf = InputFileName;
  820. if (FileNameBuf.empty() || FileNameBuf == "-")
  821. FileNameBuf = "<stdin>";
  822. if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
  823. llvm::sys::path::remove_filename(FileNameBuf);
  824. llvm::sys::path::append(FileNameBuf, getMainFileName());
  825. }
  826. StringRef FileName = FileNameBuf;
  827. if (FileName.consume_front(getCompilationDir()))
  828. if (llvm::sys::path::is_separator(FileName.front()))
  829. FileName = FileName.drop_front();
  830. assert(!FileName.empty());
  831. setMCLineTableRootFile(
  832. /*CUID=*/0, getCompilationDir(), FileName, Cksum, std::nullopt);
  833. }
  834. /// getDwarfFile - takes a file name and number to place in the dwarf file and
  835. /// directory tables. If the file number has already been allocated it is an
  836. /// error and zero is returned and the client reports the error, else the
  837. /// allocated file number is returned. The file numbers may be in any order.
  838. Expected<unsigned>
  839. MCContext::getDwarfFile(StringRef Directory, StringRef FileName,
  840. unsigned FileNumber,
  841. std::optional<MD5::MD5Result> Checksum,
  842. std::optional<StringRef> Source, unsigned CUID) {
  843. MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
  844. return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
  845. FileNumber);
  846. }
  847. /// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
  848. /// currently is assigned and false otherwise.
  849. bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
  850. const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
  851. if (FileNumber == 0)
  852. return getDwarfVersion() >= 5;
  853. if (FileNumber >= LineTable.getMCDwarfFiles().size())
  854. return false;
  855. return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
  856. }
  857. /// Remove empty sections from SectionsForRanges, to avoid generating
  858. /// useless debug info for them.
  859. void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
  860. SectionsForRanges.remove_if(
  861. [&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
  862. }
  863. CodeViewContext &MCContext::getCVContext() {
  864. if (!CVContext)
  865. CVContext.reset(new CodeViewContext);
  866. return *CVContext;
  867. }
  868. //===----------------------------------------------------------------------===//
  869. // Error Reporting
  870. //===----------------------------------------------------------------------===//
  871. void MCContext::diagnose(const SMDiagnostic &SMD) {
  872. assert(DiagHandler && "MCContext::DiagHandler is not set");
  873. bool UseInlineSrcMgr = false;
  874. const SourceMgr *SMP = nullptr;
  875. if (SrcMgr) {
  876. SMP = SrcMgr;
  877. } else if (InlineSrcMgr) {
  878. SMP = InlineSrcMgr.get();
  879. UseInlineSrcMgr = true;
  880. } else
  881. llvm_unreachable("Either SourceMgr should be available");
  882. DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
  883. }
  884. void MCContext::reportCommon(
  885. SMLoc Loc,
  886. std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
  887. // * MCContext::SrcMgr is null when the MC layer emits machine code for input
  888. // other than assembly file, say, for .c/.cpp/.ll/.bc.
  889. // * MCContext::InlineSrcMgr is null when the inline asm is not used.
  890. // * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
  891. // and MCContext::InlineSrcMgr are null.
  892. SourceMgr SM;
  893. const SourceMgr *SMP = &SM;
  894. bool UseInlineSrcMgr = false;
  895. // FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
  896. // For MC-only execution, only SrcMgr is used;
  897. // For non MC-only execution, InlineSrcMgr is only ctor'd if there is
  898. // inline asm in the IR.
  899. if (Loc.isValid()) {
  900. if (SrcMgr) {
  901. SMP = SrcMgr;
  902. } else if (InlineSrcMgr) {
  903. SMP = InlineSrcMgr.get();
  904. UseInlineSrcMgr = true;
  905. } else
  906. llvm_unreachable("Either SourceMgr should be available");
  907. }
  908. SMDiagnostic D;
  909. GetMessage(D, SMP);
  910. DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
  911. }
  912. void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
  913. HadError = true;
  914. reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
  915. D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
  916. });
  917. }
  918. void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
  919. if (TargetOptions && TargetOptions->MCNoWarn)
  920. return;
  921. if (TargetOptions && TargetOptions->MCFatalWarnings) {
  922. reportError(Loc, Msg);
  923. } else {
  924. reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
  925. D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
  926. });
  927. }
  928. }