DIBuilder.cpp 49 KB

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