DIBuilder.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
  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. //
  9. // This file implements the DIBuilder.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/DIBuilder.h"
  13. #include "LLVMContextImpl.h"
  14. #include "llvm/BinaryFormat/Dwarf.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DebugInfo.h"
  17. #include "llvm/IR/IRBuilder.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/Support/CommandLine.h"
  20. #include <optional>
  21. using namespace llvm;
  22. using namespace llvm::dwarf;
  23. static cl::opt<bool>
  24. UseDbgAddr("use-dbg-addr",
  25. llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
  26. cl::init(false), cl::Hidden);
  27. DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU)
  28. : M(m), VMContext(M.getContext()), CUNode(CU), DeclareFn(nullptr),
  29. ValueFn(nullptr), LabelFn(nullptr), AddrFn(nullptr), AssignFn(nullptr),
  30. AllowUnresolvedNodes(AllowUnresolvedNodes) {
  31. if (CUNode) {
  32. if (const auto &ETs = CUNode->getEnumTypes())
  33. AllEnumTypes.assign(ETs.begin(), ETs.end());
  34. if (const auto &RTs = CUNode->getRetainedTypes())
  35. AllRetainTypes.assign(RTs.begin(), RTs.end());
  36. if (const auto &GVs = CUNode->getGlobalVariables())
  37. AllGVs.assign(GVs.begin(), GVs.end());
  38. if (const auto &IMs = CUNode->getImportedEntities())
  39. AllImportedModules.assign(IMs.begin(), IMs.end());
  40. if (const auto &MNs = CUNode->getMacros())
  41. AllMacrosPerParent.insert({nullptr, {MNs.begin(), MNs.end()}});
  42. }
  43. }
  44. void DIBuilder::trackIfUnresolved(MDNode *N) {
  45. if (!N)
  46. return;
  47. if (N->isResolved())
  48. return;
  49. assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
  50. UnresolvedNodes.emplace_back(N);
  51. }
  52. void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
  53. MDTuple *Temp = SP->getRetainedNodes().get();
  54. if (!Temp || !Temp->isTemporary())
  55. return;
  56. SmallVector<Metadata *, 16> RetainedNodes;
  57. auto PV = PreservedVariables.find(SP);
  58. if (PV != PreservedVariables.end())
  59. RetainedNodes.append(PV->second.begin(), PV->second.end());
  60. auto PL = PreservedLabels.find(SP);
  61. if (PL != PreservedLabels.end())
  62. RetainedNodes.append(PL->second.begin(), PL->second.end());
  63. DINodeArray Node = getOrCreateArray(RetainedNodes);
  64. TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
  65. }
  66. void DIBuilder::finalize() {
  67. if (!CUNode) {
  68. assert(!AllowUnresolvedNodes &&
  69. "creating type nodes without a CU is not supported");
  70. return;
  71. }
  72. if (!AllEnumTypes.empty())
  73. CUNode->replaceEnumTypes(MDTuple::get(
  74. VMContext, SmallVector<Metadata *, 16>(AllEnumTypes.begin(),
  75. AllEnumTypes.end())));
  76. SmallVector<Metadata *, 16> RetainValues;
  77. // Declarations and definitions of the same type may be retained. Some
  78. // clients RAUW these pairs, leaving duplicates in the retained types
  79. // list. Use a set to remove the duplicates while we transform the
  80. // TrackingVHs back into Values.
  81. SmallPtrSet<Metadata *, 16> RetainSet;
  82. for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
  83. if (RetainSet.insert(AllRetainTypes[I]).second)
  84. RetainValues.push_back(AllRetainTypes[I]);
  85. if (!RetainValues.empty())
  86. CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
  87. DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
  88. for (auto *SP : SPs)
  89. finalizeSubprogram(SP);
  90. for (auto *N : RetainValues)
  91. if (auto *SP = dyn_cast<DISubprogram>(N))
  92. finalizeSubprogram(SP);
  93. if (!AllGVs.empty())
  94. CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
  95. if (!AllImportedModules.empty())
  96. CUNode->replaceImportedEntities(MDTuple::get(
  97. VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
  98. AllImportedModules.end())));
  99. for (const auto &I : AllMacrosPerParent) {
  100. // DIMacroNode's with nullptr parent are DICompileUnit direct children.
  101. if (!I.first) {
  102. CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
  103. continue;
  104. }
  105. // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
  106. auto *TMF = cast<DIMacroFile>(I.first);
  107. auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
  108. TMF->getLine(), TMF->getFile(),
  109. getOrCreateMacroArray(I.second.getArrayRef()));
  110. replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
  111. }
  112. // Now that all temp nodes have been replaced or deleted, resolve remaining
  113. // cycles.
  114. for (const auto &N : UnresolvedNodes)
  115. if (N && !N->isResolved())
  116. N->resolveCycles();
  117. UnresolvedNodes.clear();
  118. // Can't handle unresolved nodes anymore.
  119. AllowUnresolvedNodes = false;
  120. }
  121. /// If N is compile unit return NULL otherwise return N.
  122. static DIScope *getNonCompileUnitScope(DIScope *N) {
  123. if (!N || isa<DICompileUnit>(N))
  124. return nullptr;
  125. return cast<DIScope>(N);
  126. }
  127. DICompileUnit *DIBuilder::createCompileUnit(
  128. unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized,
  129. StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
  130. DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
  131. bool SplitDebugInlining, bool DebugInfoForProfiling,
  132. DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress,
  133. StringRef SysRoot, StringRef SDK) {
  134. assert(((Lang <= dwarf::DW_LANG_Ada2012 && Lang >= dwarf::DW_LANG_C89) ||
  135. (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
  136. "Invalid Language tag");
  137. assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
  138. CUNode = DICompileUnit::getDistinct(
  139. VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
  140. SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
  141. SplitDebugInlining, DebugInfoForProfiling, NameTableKind,
  142. RangesBaseAddress, SysRoot, SDK);
  143. // Create a named metadata so that it is easier to find cu in a module.
  144. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
  145. NMD->addOperand(CUNode);
  146. trackIfUnresolved(CUNode);
  147. return CUNode;
  148. }
  149. static DIImportedEntity *
  150. createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
  151. Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
  152. DINodeArray Elements,
  153. SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
  154. if (Line)
  155. assert(File && "Source location has line number but no file");
  156. unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
  157. auto *M = DIImportedEntity::get(C, Tag, Context, cast_or_null<DINode>(NS),
  158. File, Line, Name, Elements);
  159. if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
  160. // A new Imported Entity was just added to the context.
  161. // Add it to the Imported Modules list.
  162. AllImportedModules.emplace_back(M);
  163. return M;
  164. }
  165. DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
  166. DINamespace *NS, DIFile *File,
  167. unsigned Line,
  168. DINodeArray Elements) {
  169. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
  170. Context, NS, File, Line, StringRef(), Elements,
  171. AllImportedModules);
  172. }
  173. DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
  174. DIImportedEntity *NS,
  175. DIFile *File, unsigned Line,
  176. DINodeArray Elements) {
  177. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
  178. Context, NS, File, Line, StringRef(), Elements,
  179. AllImportedModules);
  180. }
  181. DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
  182. DIFile *File, unsigned Line,
  183. DINodeArray Elements) {
  184. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
  185. Context, M, File, Line, StringRef(), Elements,
  186. AllImportedModules);
  187. }
  188. DIImportedEntity *
  189. DIBuilder::createImportedDeclaration(DIScope *Context, DINode *Decl,
  190. DIFile *File, unsigned Line,
  191. StringRef Name, DINodeArray Elements) {
  192. // Make sure to use the unique identifier based metadata reference for
  193. // types that have one.
  194. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
  195. Context, Decl, File, Line, Name, Elements,
  196. AllImportedModules);
  197. }
  198. DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
  199. std::optional<DIFile::ChecksumInfo<StringRef>> CS,
  200. std::optional<StringRef> Source) {
  201. return DIFile::get(VMContext, Filename, Directory, CS, Source);
  202. }
  203. DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
  204. unsigned MacroType, StringRef Name,
  205. StringRef Value) {
  206. assert(!Name.empty() && "Unable to create macro without name");
  207. assert((MacroType == dwarf::DW_MACINFO_undef ||
  208. MacroType == dwarf::DW_MACINFO_define) &&
  209. "Unexpected macro type");
  210. auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
  211. AllMacrosPerParent[Parent].insert(M);
  212. return M;
  213. }
  214. DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
  215. unsigned LineNumber, DIFile *File) {
  216. auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
  217. LineNumber, File, DIMacroNodeArray())
  218. .release();
  219. AllMacrosPerParent[Parent].insert(MF);
  220. // Add the new temporary DIMacroFile to the macro per parent map as a parent.
  221. // This is needed to assure DIMacroFile with no children to have an entry in
  222. // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
  223. AllMacrosPerParent.insert({MF, {}});
  224. return MF;
  225. }
  226. DIEnumerator *DIBuilder::createEnumerator(StringRef Name, uint64_t Val,
  227. bool IsUnsigned) {
  228. assert(!Name.empty() && "Unable to create enumerator without name");
  229. return DIEnumerator::get(VMContext, APInt(64, Val, !IsUnsigned), IsUnsigned,
  230. Name);
  231. }
  232. DIEnumerator *DIBuilder::createEnumerator(StringRef Name, const APSInt &Value) {
  233. assert(!Name.empty() && "Unable to create enumerator without name");
  234. return DIEnumerator::get(VMContext, APInt(Value), Value.isUnsigned(), Name);
  235. }
  236. DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
  237. assert(!Name.empty() && "Unable to create type without name");
  238. return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
  239. }
  240. DIBasicType *DIBuilder::createNullPtrType() {
  241. return createUnspecifiedType("decltype(nullptr)");
  242. }
  243. DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
  244. unsigned Encoding,
  245. DINode::DIFlags Flags) {
  246. assert(!Name.empty() && "Unable to create type without name");
  247. return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
  248. 0, Encoding, Flags);
  249. }
  250. DIStringType *DIBuilder::createStringType(StringRef Name, uint64_t SizeInBits) {
  251. assert(!Name.empty() && "Unable to create type without name");
  252. return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name,
  253. SizeInBits, 0);
  254. }
  255. DIStringType *DIBuilder::createStringType(StringRef Name,
  256. DIVariable *StringLength,
  257. DIExpression *StrLocationExp) {
  258. assert(!Name.empty() && "Unable to create type without name");
  259. return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name,
  260. StringLength, nullptr, StrLocationExp, 0, 0, 0);
  261. }
  262. DIStringType *DIBuilder::createStringType(StringRef Name,
  263. DIExpression *StringLengthExp,
  264. DIExpression *StrLocationExp) {
  265. assert(!Name.empty() && "Unable to create type without name");
  266. return DIStringType::get(VMContext, dwarf::DW_TAG_string_type, Name, nullptr,
  267. StringLengthExp, StrLocationExp, 0, 0, 0);
  268. }
  269. DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
  270. return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
  271. 0, 0, std::nullopt, DINode::FlagZero);
  272. }
  273. DIDerivedType *
  274. DIBuilder::createPointerType(DIType *PointeeTy, uint64_t SizeInBits,
  275. uint32_t AlignInBits,
  276. std::optional<unsigned> DWARFAddressSpace,
  277. StringRef Name, DINodeArray Annotations) {
  278. // FIXME: Why is there a name here?
  279. return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
  280. nullptr, 0, nullptr, PointeeTy, SizeInBits,
  281. AlignInBits, 0, DWARFAddressSpace, DINode::FlagZero,
  282. nullptr, Annotations);
  283. }
  284. DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
  285. DIType *Base,
  286. uint64_t SizeInBits,
  287. uint32_t AlignInBits,
  288. DINode::DIFlags Flags) {
  289. return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
  290. nullptr, 0, nullptr, PointeeTy, SizeInBits,
  291. AlignInBits, 0, std::nullopt, Flags, Base);
  292. }
  293. DIDerivedType *
  294. DIBuilder::createReferenceType(unsigned Tag, DIType *RTy, uint64_t SizeInBits,
  295. uint32_t AlignInBits,
  296. std::optional<unsigned> DWARFAddressSpace) {
  297. assert(RTy && "Unable to create reference type");
  298. return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
  299. SizeInBits, AlignInBits, 0, DWARFAddressSpace,
  300. DINode::FlagZero);
  301. }
  302. DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
  303. DIFile *File, unsigned LineNo,
  304. DIScope *Context, uint32_t AlignInBits,
  305. DINode::DIFlags Flags,
  306. DINodeArray Annotations) {
  307. return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
  308. LineNo, getNonCompileUnitScope(Context), Ty, 0,
  309. AlignInBits, 0, std::nullopt, Flags, nullptr,
  310. Annotations);
  311. }
  312. DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
  313. assert(Ty && "Invalid type!");
  314. assert(FriendTy && "Invalid friend type!");
  315. return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
  316. FriendTy, 0, 0, 0, std::nullopt, DINode::FlagZero);
  317. }
  318. DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
  319. uint64_t BaseOffset,
  320. uint32_t VBPtrOffset,
  321. DINode::DIFlags Flags) {
  322. assert(Ty && "Unable to create inheritance");
  323. Metadata *ExtraData = ConstantAsMetadata::get(
  324. ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
  325. return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
  326. 0, Ty, BaseTy, 0, 0, BaseOffset, std::nullopt,
  327. Flags, ExtraData);
  328. }
  329. DIDerivedType *DIBuilder::createMemberType(
  330. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  331. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  332. DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations) {
  333. return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
  334. LineNumber, getNonCompileUnitScope(Scope), Ty,
  335. SizeInBits, AlignInBits, OffsetInBits, std::nullopt,
  336. Flags, nullptr, Annotations);
  337. }
  338. static ConstantAsMetadata *getConstantOrNull(Constant *C) {
  339. if (C)
  340. return ConstantAsMetadata::get(C);
  341. return nullptr;
  342. }
  343. DIDerivedType *DIBuilder::createVariantMemberType(
  344. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  345. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  346. Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
  347. return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
  348. LineNumber, getNonCompileUnitScope(Scope), Ty,
  349. SizeInBits, AlignInBits, OffsetInBits, std::nullopt,
  350. Flags, getConstantOrNull(Discriminant));
  351. }
  352. DIDerivedType *DIBuilder::createBitFieldMemberType(
  353. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  354. uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
  355. DINode::DIFlags Flags, DIType *Ty, DINodeArray Annotations) {
  356. Flags |= DINode::FlagBitField;
  357. return DIDerivedType::get(
  358. VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
  359. getNonCompileUnitScope(Scope), Ty, SizeInBits, /*AlignInBits=*/0,
  360. OffsetInBits, std::nullopt, Flags,
  361. ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
  362. StorageOffsetInBits)),
  363. Annotations);
  364. }
  365. DIDerivedType *
  366. DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
  367. unsigned LineNumber, DIType *Ty,
  368. DINode::DIFlags Flags, llvm::Constant *Val,
  369. uint32_t AlignInBits) {
  370. Flags |= DINode::FlagStaticMember;
  371. return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
  372. LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
  373. AlignInBits, 0, std::nullopt, Flags,
  374. getConstantOrNull(Val));
  375. }
  376. DIDerivedType *
  377. DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
  378. uint64_t SizeInBits, uint32_t AlignInBits,
  379. uint64_t OffsetInBits, DINode::DIFlags Flags,
  380. DIType *Ty, MDNode *PropertyNode) {
  381. return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
  382. LineNumber, getNonCompileUnitScope(File), Ty,
  383. SizeInBits, AlignInBits, OffsetInBits, std::nullopt,
  384. Flags, PropertyNode);
  385. }
  386. DIObjCProperty *
  387. DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
  388. StringRef GetterName, StringRef SetterName,
  389. unsigned PropertyAttributes, DIType *Ty) {
  390. return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
  391. SetterName, PropertyAttributes, Ty);
  392. }
  393. DITemplateTypeParameter *
  394. DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
  395. DIType *Ty, bool isDefault) {
  396. assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
  397. return DITemplateTypeParameter::get(VMContext, Name, Ty, isDefault);
  398. }
  399. static DITemplateValueParameter *
  400. createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
  401. DIScope *Context, StringRef Name, DIType *Ty,
  402. bool IsDefault, Metadata *MD) {
  403. assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
  404. return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, IsDefault, MD);
  405. }
  406. DITemplateValueParameter *
  407. DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
  408. DIType *Ty, bool isDefault,
  409. Constant *Val) {
  410. return createTemplateValueParameterHelper(
  411. VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
  412. isDefault, getConstantOrNull(Val));
  413. }
  414. DITemplateValueParameter *
  415. DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
  416. DIType *Ty, StringRef Val,
  417. bool IsDefault) {
  418. return createTemplateValueParameterHelper(
  419. VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
  420. IsDefault, MDString::get(VMContext, Val));
  421. }
  422. DITemplateValueParameter *
  423. DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
  424. DIType *Ty, DINodeArray Val) {
  425. return createTemplateValueParameterHelper(
  426. VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
  427. false, Val.get());
  428. }
  429. DICompositeType *DIBuilder::createClassType(
  430. DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
  431. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  432. DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
  433. DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
  434. assert((!Context || isa<DIScope>(Context)) &&
  435. "createClassType should be called with a valid Context");
  436. auto *R = DICompositeType::get(
  437. VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
  438. getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
  439. OffsetInBits, Flags, Elements, 0, VTableHolder,
  440. cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
  441. trackIfUnresolved(R);
  442. return R;
  443. }
  444. DICompositeType *DIBuilder::createStructType(
  445. DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
  446. uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
  447. DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
  448. DIType *VTableHolder, StringRef UniqueIdentifier) {
  449. auto *R = DICompositeType::get(
  450. VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
  451. getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
  452. Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
  453. trackIfUnresolved(R);
  454. return R;
  455. }
  456. DICompositeType *DIBuilder::createUnionType(
  457. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  458. uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
  459. DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
  460. auto *R = DICompositeType::get(
  461. VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
  462. getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
  463. Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
  464. trackIfUnresolved(R);
  465. return R;
  466. }
  467. DICompositeType *
  468. DIBuilder::createVariantPart(DIScope *Scope, StringRef Name, DIFile *File,
  469. unsigned LineNumber, uint64_t SizeInBits,
  470. uint32_t AlignInBits, DINode::DIFlags Flags,
  471. DIDerivedType *Discriminator, DINodeArray Elements,
  472. StringRef UniqueIdentifier) {
  473. auto *R = DICompositeType::get(
  474. VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
  475. getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
  476. Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
  477. trackIfUnresolved(R);
  478. return R;
  479. }
  480. DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
  481. DINode::DIFlags Flags,
  482. unsigned CC) {
  483. return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
  484. }
  485. DICompositeType *DIBuilder::createEnumerationType(
  486. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  487. uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
  488. DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
  489. auto *CTy = DICompositeType::get(
  490. VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
  491. getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
  492. IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
  493. nullptr, UniqueIdentifier);
  494. AllEnumTypes.emplace_back(CTy);
  495. trackIfUnresolved(CTy);
  496. return CTy;
  497. }
  498. DIDerivedType *DIBuilder::createSetType(DIScope *Scope, StringRef Name,
  499. DIFile *File, unsigned LineNo,
  500. uint64_t SizeInBits,
  501. uint32_t AlignInBits, DIType *Ty) {
  502. auto *R =
  503. DIDerivedType::get(VMContext, dwarf::DW_TAG_set_type, Name, File, LineNo,
  504. getNonCompileUnitScope(Scope), Ty, SizeInBits,
  505. AlignInBits, 0, std::nullopt, DINode::FlagZero);
  506. trackIfUnresolved(R);
  507. return R;
  508. }
  509. DICompositeType *
  510. DIBuilder::createArrayType(uint64_t Size, uint32_t AlignInBits, DIType *Ty,
  511. DINodeArray Subscripts,
  512. PointerUnion<DIExpression *, DIVariable *> DL,
  513. PointerUnion<DIExpression *, DIVariable *> AS,
  514. PointerUnion<DIExpression *, DIVariable *> AL,
  515. PointerUnion<DIExpression *, DIVariable *> RK) {
  516. auto *R = DICompositeType::get(
  517. VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty, Size,
  518. AlignInBits, 0, DINode::FlagZero, Subscripts, 0, nullptr, nullptr, "",
  519. nullptr,
  520. DL.is<DIExpression *>() ? (Metadata *)DL.get<DIExpression *>()
  521. : (Metadata *)DL.get<DIVariable *>(),
  522. AS.is<DIExpression *>() ? (Metadata *)AS.get<DIExpression *>()
  523. : (Metadata *)AS.get<DIVariable *>(),
  524. AL.is<DIExpression *>() ? (Metadata *)AL.get<DIExpression *>()
  525. : (Metadata *)AL.get<DIVariable *>(),
  526. RK.is<DIExpression *>() ? (Metadata *)RK.get<DIExpression *>()
  527. : (Metadata *)RK.get<DIVariable *>());
  528. trackIfUnresolved(R);
  529. return R;
  530. }
  531. DICompositeType *DIBuilder::createVectorType(uint64_t Size,
  532. uint32_t AlignInBits, DIType *Ty,
  533. DINodeArray Subscripts) {
  534. auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
  535. nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
  536. DINode::FlagVector, Subscripts, 0, nullptr);
  537. trackIfUnresolved(R);
  538. return R;
  539. }
  540. DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
  541. auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
  542. return MDNode::replaceWithDistinct(std::move(NewSP));
  543. }
  544. static DIType *createTypeWithFlags(const DIType *Ty,
  545. DINode::DIFlags FlagsToSet) {
  546. auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
  547. return MDNode::replaceWithUniqued(std::move(NewTy));
  548. }
  549. DIType *DIBuilder::createArtificialType(DIType *Ty) {
  550. // FIXME: Restrict this to the nodes where it's valid.
  551. if (Ty->isArtificial())
  552. return Ty;
  553. return createTypeWithFlags(Ty, DINode::FlagArtificial);
  554. }
  555. DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
  556. // FIXME: Restrict this to the nodes where it's valid.
  557. if (Ty->isObjectPointer())
  558. return Ty;
  559. DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
  560. return createTypeWithFlags(Ty, Flags);
  561. }
  562. void DIBuilder::retainType(DIScope *T) {
  563. assert(T && "Expected non-null type");
  564. assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
  565. cast<DISubprogram>(T)->isDefinition() == false)) &&
  566. "Expected type or subprogram declaration");
  567. AllRetainTypes.emplace_back(T);
  568. }
  569. DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
  570. DICompositeType *
  571. DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
  572. DIFile *F, unsigned Line, unsigned RuntimeLang,
  573. uint64_t SizeInBits, uint32_t AlignInBits,
  574. StringRef UniqueIdentifier) {
  575. // FIXME: Define in terms of createReplaceableForwardDecl() by calling
  576. // replaceWithUniqued().
  577. auto *RetTy = DICompositeType::get(
  578. VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
  579. SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
  580. nullptr, nullptr, UniqueIdentifier);
  581. trackIfUnresolved(RetTy);
  582. return RetTy;
  583. }
  584. DICompositeType *DIBuilder::createReplaceableCompositeType(
  585. unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
  586. unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
  587. DINode::DIFlags Flags, StringRef UniqueIdentifier,
  588. DINodeArray Annotations) {
  589. auto *RetTy =
  590. DICompositeType::getTemporary(
  591. VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
  592. SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
  593. nullptr, UniqueIdentifier, nullptr, nullptr, nullptr, nullptr,
  594. nullptr, Annotations)
  595. .release();
  596. trackIfUnresolved(RetTy);
  597. return RetTy;
  598. }
  599. DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
  600. return MDTuple::get(VMContext, Elements);
  601. }
  602. DIMacroNodeArray
  603. DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
  604. return MDTuple::get(VMContext, Elements);
  605. }
  606. DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
  607. SmallVector<llvm::Metadata *, 16> Elts;
  608. for (Metadata *E : Elements) {
  609. if (isa_and_nonnull<MDNode>(E))
  610. Elts.push_back(cast<DIType>(E));
  611. else
  612. Elts.push_back(E);
  613. }
  614. return DITypeRefArray(MDNode::get(VMContext, Elts));
  615. }
  616. DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
  617. auto *LB = ConstantAsMetadata::get(
  618. ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo));
  619. auto *CountNode = ConstantAsMetadata::get(
  620. ConstantInt::getSigned(Type::getInt64Ty(VMContext), Count));
  621. return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr);
  622. }
  623. DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
  624. auto *LB = ConstantAsMetadata::get(
  625. ConstantInt::getSigned(Type::getInt64Ty(VMContext), Lo));
  626. return DISubrange::get(VMContext, CountNode, LB, nullptr, nullptr);
  627. }
  628. DISubrange *DIBuilder::getOrCreateSubrange(Metadata *CountNode, Metadata *LB,
  629. Metadata *UB, Metadata *Stride) {
  630. return DISubrange::get(VMContext, CountNode, LB, UB, Stride);
  631. }
  632. DIGenericSubrange *DIBuilder::getOrCreateGenericSubrange(
  633. DIGenericSubrange::BoundType CountNode, DIGenericSubrange::BoundType LB,
  634. DIGenericSubrange::BoundType UB, DIGenericSubrange::BoundType Stride) {
  635. auto ConvToMetadata = [&](DIGenericSubrange::BoundType Bound) -> Metadata * {
  636. return Bound.is<DIExpression *>() ? (Metadata *)Bound.get<DIExpression *>()
  637. : (Metadata *)Bound.get<DIVariable *>();
  638. };
  639. return DIGenericSubrange::get(VMContext, ConvToMetadata(CountNode),
  640. ConvToMetadata(LB), ConvToMetadata(UB),
  641. ConvToMetadata(Stride));
  642. }
  643. static void checkGlobalVariableScope(DIScope *Context) {
  644. #ifndef NDEBUG
  645. if (auto *CT =
  646. dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
  647. assert(CT->getIdentifier().empty() &&
  648. "Context of a global variable should not be a type with identifier");
  649. #endif
  650. }
  651. DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
  652. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
  653. unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, bool isDefined,
  654. DIExpression *Expr, MDNode *Decl, MDTuple *TemplateParams,
  655. uint32_t AlignInBits, DINodeArray Annotations) {
  656. checkGlobalVariableScope(Context);
  657. auto *GV = DIGlobalVariable::getDistinct(
  658. VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
  659. LineNumber, Ty, IsLocalToUnit, isDefined,
  660. cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits,
  661. Annotations);
  662. if (!Expr)
  663. Expr = createExpression();
  664. auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
  665. AllGVs.push_back(N);
  666. return N;
  667. }
  668. DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
  669. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
  670. unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
  671. MDTuple *TemplateParams, uint32_t AlignInBits) {
  672. checkGlobalVariableScope(Context);
  673. return DIGlobalVariable::getTemporary(
  674. VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
  675. LineNumber, Ty, IsLocalToUnit, false,
  676. cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits,
  677. nullptr)
  678. .release();
  679. }
  680. static DILocalVariable *createLocalVariable(
  681. LLVMContext &VMContext,
  682. DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
  683. DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
  684. unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
  685. uint32_t AlignInBits, DINodeArray Annotations = nullptr) {
  686. // FIXME: Why getNonCompileUnitScope()?
  687. // FIXME: Why is "!Context" okay here?
  688. // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
  689. // the only valid scopes)?
  690. DIScope *Context = getNonCompileUnitScope(Scope);
  691. auto *Node = DILocalVariable::get(
  692. VMContext, cast_or_null<DILocalScope>(Context), Name, File, LineNo, Ty,
  693. ArgNo, Flags, AlignInBits, Annotations);
  694. if (AlwaysPreserve) {
  695. // The optimizer may remove local variables. If there is an interest
  696. // to preserve variable info in such situation then stash it in a
  697. // named mdnode.
  698. DISubprogram *Fn = getDISubprogram(Scope);
  699. assert(Fn && "Missing subprogram for local variable");
  700. PreservedVariables[Fn].emplace_back(Node);
  701. }
  702. return Node;
  703. }
  704. DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
  705. DIFile *File, unsigned LineNo,
  706. DIType *Ty, bool AlwaysPreserve,
  707. DINode::DIFlags Flags,
  708. uint32_t AlignInBits) {
  709. return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
  710. /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
  711. Flags, AlignInBits);
  712. }
  713. DILocalVariable *DIBuilder::createParameterVariable(
  714. DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
  715. unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
  716. DINodeArray Annotations) {
  717. assert(ArgNo && "Expected non-zero argument number for parameter");
  718. return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
  719. File, LineNo, Ty, AlwaysPreserve, Flags,
  720. /*AlignInBits=*/0, Annotations);
  721. }
  722. DILabel *DIBuilder::createLabel(DIScope *Scope, StringRef Name, DIFile *File,
  723. unsigned LineNo, bool AlwaysPreserve) {
  724. DIScope *Context = getNonCompileUnitScope(Scope);
  725. auto *Node = DILabel::get(VMContext, cast_or_null<DILocalScope>(Context),
  726. Name, File, LineNo);
  727. if (AlwaysPreserve) {
  728. /// The optimizer may remove labels. If there is an interest
  729. /// to preserve label info in such situation then append it to
  730. /// the list of retained nodes of the DISubprogram.
  731. DISubprogram *Fn = getDISubprogram(Scope);
  732. assert(Fn && "Missing subprogram for label");
  733. PreservedLabels[Fn].emplace_back(Node);
  734. }
  735. return Node;
  736. }
  737. DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
  738. return DIExpression::get(VMContext, Addr);
  739. }
  740. template <class... Ts>
  741. static DISubprogram *getSubprogram(bool IsDistinct, Ts &&...Args) {
  742. if (IsDistinct)
  743. return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
  744. return DISubprogram::get(std::forward<Ts>(Args)...);
  745. }
  746. DISubprogram *DIBuilder::createFunction(
  747. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
  748. unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
  749. DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
  750. DITemplateParameterArray TParams, DISubprogram *Decl,
  751. DITypeArray ThrownTypes, DINodeArray Annotations,
  752. StringRef TargetFuncName) {
  753. bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
  754. auto *Node = getSubprogram(
  755. /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
  756. Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
  757. SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
  758. MDTuple::getTemporary(VMContext, std::nullopt).release(), ThrownTypes,
  759. Annotations, TargetFuncName);
  760. if (IsDefinition)
  761. AllSubprograms.push_back(Node);
  762. trackIfUnresolved(Node);
  763. return Node;
  764. }
  765. DISubprogram *DIBuilder::createTempFunctionFwdDecl(
  766. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
  767. unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
  768. DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
  769. DITemplateParameterArray TParams, DISubprogram *Decl,
  770. DITypeArray ThrownTypes) {
  771. bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
  772. return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
  773. Name, LinkageName, File, LineNo, Ty,
  774. ScopeLine, nullptr, 0, 0, Flags, SPFlags,
  775. IsDefinition ? CUNode : nullptr, TParams,
  776. Decl, nullptr, ThrownTypes)
  777. .release();
  778. }
  779. DISubprogram *DIBuilder::createMethod(
  780. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
  781. unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
  782. DIType *VTableHolder, DINode::DIFlags Flags,
  783. DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
  784. DITypeArray ThrownTypes) {
  785. assert(getNonCompileUnitScope(Context) &&
  786. "Methods should have both a Context and a context that isn't "
  787. "the compile unit.");
  788. // FIXME: Do we want to use different scope/lines?
  789. bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
  790. auto *SP = getSubprogram(
  791. /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
  792. LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
  793. Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
  794. nullptr, ThrownTypes);
  795. if (IsDefinition)
  796. AllSubprograms.push_back(SP);
  797. trackIfUnresolved(SP);
  798. return SP;
  799. }
  800. DICommonBlock *DIBuilder::createCommonBlock(DIScope *Scope,
  801. DIGlobalVariable *Decl,
  802. StringRef Name, DIFile *File,
  803. unsigned LineNo) {
  804. return DICommonBlock::get(VMContext, Scope, Decl, Name, File, LineNo);
  805. }
  806. DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
  807. bool ExportSymbols) {
  808. // It is okay to *not* make anonymous top-level namespaces distinct, because
  809. // all nodes that have an anonymous namespace as their parent scope are
  810. // guaranteed to be unique and/or are linked to their containing
  811. // DICompileUnit. This decision is an explicit tradeoff of link time versus
  812. // memory usage versus code simplicity and may get revisited in the future.
  813. return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
  814. ExportSymbols);
  815. }
  816. DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
  817. StringRef ConfigurationMacros,
  818. StringRef IncludePath, StringRef APINotesFile,
  819. DIFile *File, unsigned LineNo, bool IsDecl) {
  820. return DIModule::get(VMContext, File, getNonCompileUnitScope(Scope), Name,
  821. ConfigurationMacros, IncludePath, APINotesFile, LineNo,
  822. IsDecl);
  823. }
  824. DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
  825. DIFile *File,
  826. unsigned Discriminator) {
  827. return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
  828. }
  829. DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
  830. unsigned Line, unsigned Col) {
  831. // Make these distinct, to avoid merging two lexical blocks on the same
  832. // file/line/column.
  833. return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
  834. File, Line, Col);
  835. }
  836. Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
  837. DIExpression *Expr, const DILocation *DL,
  838. Instruction *InsertBefore) {
  839. return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
  840. InsertBefore);
  841. }
  842. Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
  843. DIExpression *Expr, const DILocation *DL,
  844. BasicBlock *InsertAtEnd) {
  845. // If this block already has a terminator then insert this intrinsic before
  846. // the terminator. Otherwise, put it at the end of the block.
  847. Instruction *InsertBefore = InsertAtEnd->getTerminator();
  848. return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
  849. }
  850. DbgAssignIntrinsic *
  851. DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val,
  852. DILocalVariable *SrcVar, DIExpression *ValExpr,
  853. Value *Addr, DIExpression *AddrExpr,
  854. const DILocation *DL) {
  855. LLVMContext &Ctx = LinkedInstr->getContext();
  856. Module *M = LinkedInstr->getModule();
  857. if (!AssignFn)
  858. AssignFn = Intrinsic::getDeclaration(M, Intrinsic::dbg_assign);
  859. auto *Link = LinkedInstr->getMetadata(LLVMContext::MD_DIAssignID);
  860. assert(Link && "Linked instruction must have DIAssign metadata attached");
  861. std::array<Value *, 6> Args = {
  862. MetadataAsValue::get(Ctx, ValueAsMetadata::get(Val)),
  863. MetadataAsValue::get(Ctx, SrcVar),
  864. MetadataAsValue::get(Ctx, ValExpr),
  865. MetadataAsValue::get(Ctx, Link),
  866. MetadataAsValue::get(Ctx, ValueAsMetadata::get(Addr)),
  867. MetadataAsValue::get(Ctx, AddrExpr),
  868. };
  869. IRBuilder<> B(Ctx);
  870. B.SetCurrentDebugLocation(DL);
  871. auto *DVI = cast<DbgAssignIntrinsic>(B.CreateCall(AssignFn, Args));
  872. DVI->insertAfter(LinkedInstr);
  873. return DVI;
  874. }
  875. Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
  876. Instruction *InsertBefore) {
  877. return insertLabel(LabelInfo, DL,
  878. InsertBefore ? InsertBefore->getParent() : nullptr,
  879. InsertBefore);
  880. }
  881. Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
  882. BasicBlock *InsertAtEnd) {
  883. return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
  884. }
  885. Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
  886. DILocalVariable *VarInfo,
  887. DIExpression *Expr,
  888. const DILocation *DL,
  889. Instruction *InsertBefore) {
  890. return insertDbgValueIntrinsic(
  891. V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
  892. InsertBefore);
  893. }
  894. Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
  895. DILocalVariable *VarInfo,
  896. DIExpression *Expr,
  897. const DILocation *DL,
  898. BasicBlock *InsertAtEnd) {
  899. return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
  900. }
  901. Instruction *DIBuilder::insertDbgAddrIntrinsic(Value *V,
  902. DILocalVariable *VarInfo,
  903. DIExpression *Expr,
  904. const DILocation *DL,
  905. Instruction *InsertBefore) {
  906. return insertDbgAddrIntrinsic(
  907. V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
  908. InsertBefore);
  909. }
  910. Instruction *DIBuilder::insertDbgAddrIntrinsic(Value *V,
  911. DILocalVariable *VarInfo,
  912. DIExpression *Expr,
  913. const DILocation *DL,
  914. BasicBlock *InsertAtEnd) {
  915. return insertDbgAddrIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
  916. }
  917. /// Initialize IRBuilder for inserting dbg.declare and dbg.value intrinsics.
  918. /// This abstracts over the various ways to specify an insert position.
  919. static void initIRBuilder(IRBuilder<> &Builder, const DILocation *DL,
  920. BasicBlock *InsertBB, Instruction *InsertBefore) {
  921. if (InsertBefore)
  922. Builder.SetInsertPoint(InsertBefore);
  923. else if (InsertBB)
  924. Builder.SetInsertPoint(InsertBB);
  925. Builder.SetCurrentDebugLocation(DL);
  926. }
  927. static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
  928. assert(V && "no value passed to dbg intrinsic");
  929. return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
  930. }
  931. static Function *getDeclareIntrin(Module &M) {
  932. return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
  933. : Intrinsic::dbg_declare);
  934. }
  935. Instruction *DIBuilder::insertDbgValueIntrinsic(
  936. llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr,
  937. const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
  938. if (!ValueFn)
  939. ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
  940. return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB,
  941. InsertBefore);
  942. }
  943. Instruction *DIBuilder::insertDbgAddrIntrinsic(
  944. llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr,
  945. const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
  946. if (!AddrFn)
  947. AddrFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_addr);
  948. return insertDbgIntrinsic(AddrFn, Val, VarInfo, Expr, DL, InsertBB,
  949. InsertBefore);
  950. }
  951. Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
  952. DIExpression *Expr, const DILocation *DL,
  953. BasicBlock *InsertBB,
  954. Instruction *InsertBefore) {
  955. assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
  956. assert(DL && "Expected debug loc");
  957. assert(DL->getScope()->getSubprogram() ==
  958. VarInfo->getScope()->getSubprogram() &&
  959. "Expected matching subprograms");
  960. if (!DeclareFn)
  961. DeclareFn = getDeclareIntrin(M);
  962. trackIfUnresolved(VarInfo);
  963. trackIfUnresolved(Expr);
  964. Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
  965. MetadataAsValue::get(VMContext, VarInfo),
  966. MetadataAsValue::get(VMContext, Expr)};
  967. IRBuilder<> B(DL->getContext());
  968. initIRBuilder(B, DL, InsertBB, InsertBefore);
  969. return B.CreateCall(DeclareFn, Args);
  970. }
  971. Instruction *DIBuilder::insertDbgIntrinsic(llvm::Function *IntrinsicFn,
  972. Value *V, DILocalVariable *VarInfo,
  973. DIExpression *Expr,
  974. const DILocation *DL,
  975. BasicBlock *InsertBB,
  976. Instruction *InsertBefore) {
  977. assert(IntrinsicFn && "must pass a non-null intrinsic function");
  978. assert(V && "must pass a value to a dbg intrinsic");
  979. assert(VarInfo &&
  980. "empty or invalid DILocalVariable* passed to debug intrinsic");
  981. assert(DL && "Expected debug loc");
  982. assert(DL->getScope()->getSubprogram() ==
  983. VarInfo->getScope()->getSubprogram() &&
  984. "Expected matching subprograms");
  985. trackIfUnresolved(VarInfo);
  986. trackIfUnresolved(Expr);
  987. Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
  988. MetadataAsValue::get(VMContext, VarInfo),
  989. MetadataAsValue::get(VMContext, Expr)};
  990. IRBuilder<> B(DL->getContext());
  991. initIRBuilder(B, DL, InsertBB, InsertBefore);
  992. return B.CreateCall(IntrinsicFn, Args);
  993. }
  994. Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
  995. BasicBlock *InsertBB,
  996. Instruction *InsertBefore) {
  997. assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
  998. assert(DL && "Expected debug loc");
  999. assert(DL->getScope()->getSubprogram() ==
  1000. LabelInfo->getScope()->getSubprogram() &&
  1001. "Expected matching subprograms");
  1002. if (!LabelFn)
  1003. LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
  1004. trackIfUnresolved(LabelInfo);
  1005. Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
  1006. IRBuilder<> B(DL->getContext());
  1007. initIRBuilder(B, DL, InsertBB, InsertBefore);
  1008. return B.CreateCall(LabelFn, Args);
  1009. }
  1010. void DIBuilder::replaceVTableHolder(DICompositeType *&T, DIType *VTableHolder) {
  1011. {
  1012. TypedTrackingMDRef<DICompositeType> N(T);
  1013. N->replaceVTableHolder(VTableHolder);
  1014. T = N.get();
  1015. }
  1016. // If this didn't create a self-reference, just return.
  1017. if (T != VTableHolder)
  1018. return;
  1019. // Look for unresolved operands. T will drop RAUW support, orphaning any
  1020. // cycles underneath it.
  1021. if (T->isResolved())
  1022. for (const MDOperand &O : T->operands())
  1023. if (auto *N = dyn_cast_or_null<MDNode>(O))
  1024. trackIfUnresolved(N);
  1025. }
  1026. void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
  1027. DINodeArray TParams) {
  1028. {
  1029. TypedTrackingMDRef<DICompositeType> N(T);
  1030. if (Elements)
  1031. N->replaceElements(Elements);
  1032. if (TParams)
  1033. N->replaceTemplateParams(DITemplateParameterArray(TParams));
  1034. T = N.get();
  1035. }
  1036. // If T isn't resolved, there's no problem.
  1037. if (!T->isResolved())
  1038. return;
  1039. // If T is resolved, it may be due to a self-reference cycle. Track the
  1040. // arrays explicitly if they're unresolved, or else the cycles will be
  1041. // orphaned.
  1042. if (Elements)
  1043. trackIfUnresolved(Elements.get());
  1044. if (TParams)
  1045. trackIfUnresolved(TParams.get());
  1046. }