DebugInfo.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  1. //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
  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 helper classes used to build and interpret debug
  10. // information in LLVM IR form.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm-c/DebugInfo.h"
  14. #include "LLVMContextImpl.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/IR/BasicBlock.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/DIBuilder.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/DebugInfoMetadata.h"
  26. #include "llvm/IR/DebugLoc.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/IR/GVMaterializer.h"
  29. #include "llvm/IR/Instruction.h"
  30. #include "llvm/IR/IntrinsicInst.h"
  31. #include "llvm/IR/LLVMContext.h"
  32. #include "llvm/IR/Metadata.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/PassManager.h"
  35. #include "llvm/Support/Casting.h"
  36. #include <algorithm>
  37. #include <cassert>
  38. #include <optional>
  39. #include <utility>
  40. using namespace llvm;
  41. using namespace llvm::at;
  42. using namespace llvm::dwarf;
  43. /// Finds all intrinsics declaring local variables as living in the memory that
  44. /// 'V' points to. This may include a mix of dbg.declare and
  45. /// dbg.addr intrinsics.
  46. TinyPtrVector<DbgVariableIntrinsic *> llvm::FindDbgAddrUses(Value *V) {
  47. // This function is hot. Check whether the value has any metadata to avoid a
  48. // DenseMap lookup.
  49. if (!V->isUsedByMetadata())
  50. return {};
  51. auto *L = LocalAsMetadata::getIfExists(V);
  52. if (!L)
  53. return {};
  54. auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
  55. if (!MDV)
  56. return {};
  57. TinyPtrVector<DbgVariableIntrinsic *> Declares;
  58. for (User *U : MDV->users()) {
  59. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(U))
  60. if (DII->isAddressOfVariable())
  61. Declares.push_back(DII);
  62. }
  63. return Declares;
  64. }
  65. TinyPtrVector<DbgDeclareInst *> llvm::FindDbgDeclareUses(Value *V) {
  66. TinyPtrVector<DbgDeclareInst *> DDIs;
  67. for (DbgVariableIntrinsic *DVI : FindDbgAddrUses(V))
  68. if (auto *DDI = dyn_cast<DbgDeclareInst>(DVI))
  69. DDIs.push_back(DDI);
  70. return DDIs;
  71. }
  72. void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
  73. // This function is hot. Check whether the value has any metadata to avoid a
  74. // DenseMap lookup.
  75. if (!V->isUsedByMetadata())
  76. return;
  77. // TODO: If this value appears multiple times in a DIArgList, we should still
  78. // only add the owning DbgValueInst once; use this set to track ArgListUsers.
  79. // This behaviour can be removed when we can automatically remove duplicates.
  80. SmallPtrSet<DbgValueInst *, 4> EncounteredDbgValues;
  81. if (auto *L = LocalAsMetadata::getIfExists(V)) {
  82. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
  83. for (User *U : MDV->users())
  84. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  85. DbgValues.push_back(DVI);
  86. }
  87. for (Metadata *AL : L->getAllArgListUsers()) {
  88. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
  89. for (User *U : MDV->users())
  90. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  91. if (EncounteredDbgValues.insert(DVI).second)
  92. DbgValues.push_back(DVI);
  93. }
  94. }
  95. }
  96. }
  97. void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
  98. Value *V) {
  99. // This function is hot. Check whether the value has any metadata to avoid a
  100. // DenseMap lookup.
  101. if (!V->isUsedByMetadata())
  102. return;
  103. // TODO: If this value appears multiple times in a DIArgList, we should still
  104. // only add the owning DbgValueInst once; use this set to track ArgListUsers.
  105. // This behaviour can be removed when we can automatically remove duplicates.
  106. SmallPtrSet<DbgVariableIntrinsic *, 4> EncounteredDbgValues;
  107. if (auto *L = LocalAsMetadata::getIfExists(V)) {
  108. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L)) {
  109. for (User *U : MDV->users())
  110. if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
  111. DbgUsers.push_back(DII);
  112. }
  113. for (Metadata *AL : L->getAllArgListUsers()) {
  114. if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), AL)) {
  115. for (User *U : MDV->users())
  116. if (DbgVariableIntrinsic *DII = dyn_cast<DbgVariableIntrinsic>(U))
  117. if (EncounteredDbgValues.insert(DII).second)
  118. DbgUsers.push_back(DII);
  119. }
  120. }
  121. }
  122. }
  123. DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
  124. if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
  125. return LocalScope->getSubprogram();
  126. return nullptr;
  127. }
  128. DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {
  129. // Original dbg.declare must have a location.
  130. const DebugLoc &DeclareLoc = DII->getDebugLoc();
  131. MDNode *Scope = DeclareLoc.getScope();
  132. DILocation *InlinedAt = DeclareLoc.getInlinedAt();
  133. // Because no machine insts can come from debug intrinsics, only the scope
  134. // and inlinedAt is significant. Zero line numbers are used in case this
  135. // DebugLoc leaks into any adjacent instructions. Produce an unknown location
  136. // with the correct scope / inlinedAt fields.
  137. return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
  138. }
  139. //===----------------------------------------------------------------------===//
  140. // DebugInfoFinder implementations.
  141. //===----------------------------------------------------------------------===//
  142. void DebugInfoFinder::reset() {
  143. CUs.clear();
  144. SPs.clear();
  145. GVs.clear();
  146. TYs.clear();
  147. Scopes.clear();
  148. NodesSeen.clear();
  149. }
  150. void DebugInfoFinder::processModule(const Module &M) {
  151. for (auto *CU : M.debug_compile_units())
  152. processCompileUnit(CU);
  153. for (auto &F : M.functions()) {
  154. if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
  155. processSubprogram(SP);
  156. // There could be subprograms from inlined functions referenced from
  157. // instructions only. Walk the function to find them.
  158. for (const BasicBlock &BB : F)
  159. for (const Instruction &I : BB)
  160. processInstruction(M, I);
  161. }
  162. }
  163. void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
  164. if (!addCompileUnit(CU))
  165. return;
  166. for (auto *DIG : CU->getGlobalVariables()) {
  167. if (!addGlobalVariable(DIG))
  168. continue;
  169. auto *GV = DIG->getVariable();
  170. processScope(GV->getScope());
  171. processType(GV->getType());
  172. }
  173. for (auto *ET : CU->getEnumTypes())
  174. processType(ET);
  175. for (auto *RT : CU->getRetainedTypes())
  176. if (auto *T = dyn_cast<DIType>(RT))
  177. processType(T);
  178. else
  179. processSubprogram(cast<DISubprogram>(RT));
  180. for (auto *Import : CU->getImportedEntities()) {
  181. auto *Entity = Import->getEntity();
  182. if (auto *T = dyn_cast<DIType>(Entity))
  183. processType(T);
  184. else if (auto *SP = dyn_cast<DISubprogram>(Entity))
  185. processSubprogram(SP);
  186. else if (auto *NS = dyn_cast<DINamespace>(Entity))
  187. processScope(NS->getScope());
  188. else if (auto *M = dyn_cast<DIModule>(Entity))
  189. processScope(M->getScope());
  190. }
  191. }
  192. void DebugInfoFinder::processInstruction(const Module &M,
  193. const Instruction &I) {
  194. if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
  195. processVariable(M, *DVI);
  196. if (auto DbgLoc = I.getDebugLoc())
  197. processLocation(M, DbgLoc.get());
  198. }
  199. void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
  200. if (!Loc)
  201. return;
  202. processScope(Loc->getScope());
  203. processLocation(M, Loc->getInlinedAt());
  204. }
  205. void DebugInfoFinder::processType(DIType *DT) {
  206. if (!addType(DT))
  207. return;
  208. processScope(DT->getScope());
  209. if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
  210. for (DIType *Ref : ST->getTypeArray())
  211. processType(Ref);
  212. return;
  213. }
  214. if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
  215. processType(DCT->getBaseType());
  216. for (Metadata *D : DCT->getElements()) {
  217. if (auto *T = dyn_cast<DIType>(D))
  218. processType(T);
  219. else if (auto *SP = dyn_cast<DISubprogram>(D))
  220. processSubprogram(SP);
  221. }
  222. return;
  223. }
  224. if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
  225. processType(DDT->getBaseType());
  226. }
  227. }
  228. void DebugInfoFinder::processScope(DIScope *Scope) {
  229. if (!Scope)
  230. return;
  231. if (auto *Ty = dyn_cast<DIType>(Scope)) {
  232. processType(Ty);
  233. return;
  234. }
  235. if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
  236. addCompileUnit(CU);
  237. return;
  238. }
  239. if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
  240. processSubprogram(SP);
  241. return;
  242. }
  243. if (!addScope(Scope))
  244. return;
  245. if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
  246. processScope(LB->getScope());
  247. } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
  248. processScope(NS->getScope());
  249. } else if (auto *M = dyn_cast<DIModule>(Scope)) {
  250. processScope(M->getScope());
  251. }
  252. }
  253. void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
  254. if (!addSubprogram(SP))
  255. return;
  256. processScope(SP->getScope());
  257. // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
  258. // ValueMap containing identity mappings for all of the DICompileUnit's, not
  259. // just DISubprogram's, referenced from anywhere within the Function being
  260. // cloned prior to calling MapMetadata / RemapInstruction to avoid their
  261. // duplication later as DICompileUnit's are also directly referenced by
  262. // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
  263. // Also, DICompileUnit's may reference DISubprogram's too and therefore need
  264. // to be at least looked through.
  265. processCompileUnit(SP->getUnit());
  266. processType(SP->getType());
  267. for (auto *Element : SP->getTemplateParams()) {
  268. if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
  269. processType(TType->getType());
  270. } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
  271. processType(TVal->getType());
  272. }
  273. }
  274. }
  275. void DebugInfoFinder::processVariable(const Module &M,
  276. const DbgVariableIntrinsic &DVI) {
  277. auto *N = dyn_cast<MDNode>(DVI.getVariable());
  278. if (!N)
  279. return;
  280. auto *DV = dyn_cast<DILocalVariable>(N);
  281. if (!DV)
  282. return;
  283. if (!NodesSeen.insert(DV).second)
  284. return;
  285. processScope(DV->getScope());
  286. processType(DV->getType());
  287. }
  288. bool DebugInfoFinder::addType(DIType *DT) {
  289. if (!DT)
  290. return false;
  291. if (!NodesSeen.insert(DT).second)
  292. return false;
  293. TYs.push_back(const_cast<DIType *>(DT));
  294. return true;
  295. }
  296. bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
  297. if (!CU)
  298. return false;
  299. if (!NodesSeen.insert(CU).second)
  300. return false;
  301. CUs.push_back(CU);
  302. return true;
  303. }
  304. bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
  305. if (!NodesSeen.insert(DIG).second)
  306. return false;
  307. GVs.push_back(DIG);
  308. return true;
  309. }
  310. bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
  311. if (!SP)
  312. return false;
  313. if (!NodesSeen.insert(SP).second)
  314. return false;
  315. SPs.push_back(SP);
  316. return true;
  317. }
  318. bool DebugInfoFinder::addScope(DIScope *Scope) {
  319. if (!Scope)
  320. return false;
  321. // FIXME: Ocaml binding generates a scope with no content, we treat it
  322. // as null for now.
  323. if (Scope->getNumOperands() == 0)
  324. return false;
  325. if (!NodesSeen.insert(Scope).second)
  326. return false;
  327. Scopes.push_back(Scope);
  328. return true;
  329. }
  330. static MDNode *updateLoopMetadataDebugLocationsImpl(
  331. MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
  332. assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
  333. "Loop ID needs at least one operand");
  334. assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
  335. "Loop ID should refer to itself");
  336. // Save space for the self-referential LoopID.
  337. SmallVector<Metadata *, 4> MDs = {nullptr};
  338. for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
  339. Metadata *MD = OrigLoopID->getOperand(i);
  340. if (!MD)
  341. MDs.push_back(nullptr);
  342. else if (Metadata *NewMD = Updater(MD))
  343. MDs.push_back(NewMD);
  344. }
  345. MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
  346. // Insert the self-referential LoopID.
  347. NewLoopID->replaceOperandWith(0, NewLoopID);
  348. return NewLoopID;
  349. }
  350. void llvm::updateLoopMetadataDebugLocations(
  351. Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
  352. MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
  353. if (!OrigLoopID)
  354. return;
  355. MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
  356. I.setMetadata(LLVMContext::MD_loop, NewLoopID);
  357. }
  358. /// Return true if a node is a DILocation or if a DILocation is
  359. /// indirectly referenced by one of the node's children.
  360. static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
  361. SmallPtrSetImpl<Metadata *> &Reachable,
  362. Metadata *MD) {
  363. MDNode *N = dyn_cast_or_null<MDNode>(MD);
  364. if (!N)
  365. return false;
  366. if (isa<DILocation>(N) || Reachable.count(N))
  367. return true;
  368. if (!Visited.insert(N).second)
  369. return false;
  370. for (auto &OpIt : N->operands()) {
  371. Metadata *Op = OpIt.get();
  372. if (isDILocationReachable(Visited, Reachable, Op)) {
  373. Reachable.insert(N);
  374. return true;
  375. }
  376. }
  377. return false;
  378. }
  379. static MDNode *stripDebugLocFromLoopID(MDNode *N) {
  380. assert(!N->operands().empty() && "Missing self reference?");
  381. SmallPtrSet<Metadata *, 8> Visited, DILocationReachable;
  382. // If we already visited N, there is nothing to do.
  383. if (!Visited.insert(N).second)
  384. return N;
  385. // If there is no debug location, we do not have to rewrite this
  386. // MDNode. This loop also initializes DILocationReachable, later
  387. // needed by updateLoopMetadataDebugLocationsImpl; the use of
  388. // count_if avoids an early exit.
  389. if (!std::count_if(N->op_begin() + 1, N->op_end(),
  390. [&Visited, &DILocationReachable](const MDOperand &Op) {
  391. return isDILocationReachable(
  392. Visited, DILocationReachable, Op.get());
  393. }))
  394. return N;
  395. // If there is only the debug location without any actual loop metadata, we
  396. // can remove the metadata.
  397. if (llvm::all_of(llvm::drop_begin(N->operands()),
  398. [&Visited, &DILocationReachable](const MDOperand &Op) {
  399. return isDILocationReachable(Visited, DILocationReachable,
  400. Op.get());
  401. }))
  402. return nullptr;
  403. return updateLoopMetadataDebugLocationsImpl(
  404. N, [&DILocationReachable](Metadata *MD) -> Metadata * {
  405. if (isa<DILocation>(MD) || DILocationReachable.count(MD))
  406. return nullptr;
  407. return MD;
  408. });
  409. }
  410. bool llvm::stripDebugInfo(Function &F) {
  411. bool Changed = false;
  412. if (F.hasMetadata(LLVMContext::MD_dbg)) {
  413. Changed = true;
  414. F.setSubprogram(nullptr);
  415. }
  416. DenseMap<MDNode *, MDNode *> LoopIDsMap;
  417. for (BasicBlock &BB : F) {
  418. for (Instruction &I : llvm::make_early_inc_range(BB)) {
  419. if (isa<DbgInfoIntrinsic>(&I)) {
  420. I.eraseFromParent();
  421. Changed = true;
  422. continue;
  423. }
  424. if (I.getDebugLoc()) {
  425. Changed = true;
  426. I.setDebugLoc(DebugLoc());
  427. }
  428. if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
  429. auto *NewLoopID = LoopIDsMap.lookup(LoopID);
  430. if (!NewLoopID)
  431. NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
  432. if (NewLoopID != LoopID)
  433. I.setMetadata(LLVMContext::MD_loop, NewLoopID);
  434. }
  435. // Strip other attachments that are or use debug info.
  436. if (I.hasMetadataOtherThanDebugLoc()) {
  437. // Heapallocsites point into the DIType system.
  438. I.setMetadata("heapallocsite", nullptr);
  439. // DIAssignID are debug info metadata primitives.
  440. I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
  441. }
  442. }
  443. }
  444. return Changed;
  445. }
  446. bool llvm::StripDebugInfo(Module &M) {
  447. bool Changed = false;
  448. for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
  449. // We're stripping debug info, and without them, coverage information
  450. // doesn't quite make sense.
  451. if (NMD.getName().startswith("llvm.dbg.") ||
  452. NMD.getName() == "llvm.gcov") {
  453. NMD.eraseFromParent();
  454. Changed = true;
  455. }
  456. }
  457. for (Function &F : M)
  458. Changed |= stripDebugInfo(F);
  459. for (auto &GV : M.globals()) {
  460. Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
  461. }
  462. if (GVMaterializer *Materializer = M.getMaterializer())
  463. Materializer->setStripDebugInfo();
  464. return Changed;
  465. }
  466. namespace {
  467. /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
  468. class DebugTypeInfoRemoval {
  469. DenseMap<Metadata *, Metadata *> Replacements;
  470. public:
  471. /// The (void)() type.
  472. MDNode *EmptySubroutineType;
  473. private:
  474. /// Remember what linkage name we originally had before stripping. If we end
  475. /// up making two subprograms identical who originally had different linkage
  476. /// names, then we need to make one of them distinct, to avoid them getting
  477. /// uniqued. Maps the new node to the old linkage name.
  478. DenseMap<DISubprogram *, StringRef> NewToLinkageName;
  479. // TODO: Remember the distinct subprogram we created for a given linkage name,
  480. // so that we can continue to unique whenever possible. Map <newly created
  481. // node, old linkage name> to the first (possibly distinct) mdsubprogram
  482. // created for that combination. This is not strictly needed for correctness,
  483. // but can cut down on the number of MDNodes and let us diff cleanly with the
  484. // output of -gline-tables-only.
  485. public:
  486. DebugTypeInfoRemoval(LLVMContext &C)
  487. : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
  488. MDNode::get(C, {}))) {}
  489. Metadata *map(Metadata *M) {
  490. if (!M)
  491. return nullptr;
  492. auto Replacement = Replacements.find(M);
  493. if (Replacement != Replacements.end())
  494. return Replacement->second;
  495. return M;
  496. }
  497. MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
  498. /// Recursively remap N and all its referenced children. Does a DF post-order
  499. /// traversal, so as to remap bottoms up.
  500. void traverseAndRemap(MDNode *N) { traverse(N); }
  501. private:
  502. // Create a new DISubprogram, to replace the one given.
  503. DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
  504. auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
  505. StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
  506. DISubprogram *Declaration = nullptr;
  507. auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
  508. DIType *ContainingType =
  509. cast_or_null<DIType>(map(MDS->getContainingType()));
  510. auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
  511. auto Variables = nullptr;
  512. auto TemplateParams = nullptr;
  513. // Make a distinct DISubprogram, for situations that warrent it.
  514. auto distinctMDSubprogram = [&]() {
  515. return DISubprogram::getDistinct(
  516. MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
  517. FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
  518. ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
  519. MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
  520. Variables);
  521. };
  522. if (MDS->isDistinct())
  523. return distinctMDSubprogram();
  524. auto *NewMDS = DISubprogram::get(
  525. MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
  526. FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
  527. MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
  528. MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
  529. StringRef OldLinkageName = MDS->getLinkageName();
  530. // See if we need to make a distinct one.
  531. auto OrigLinkage = NewToLinkageName.find(NewMDS);
  532. if (OrigLinkage != NewToLinkageName.end()) {
  533. if (OrigLinkage->second == OldLinkageName)
  534. // We're good.
  535. return NewMDS;
  536. // Otherwise, need to make a distinct one.
  537. // TODO: Query the map to see if we already have one.
  538. return distinctMDSubprogram();
  539. }
  540. NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
  541. return NewMDS;
  542. }
  543. /// Create a new compile unit, to replace the one given
  544. DICompileUnit *getReplacementCU(DICompileUnit *CU) {
  545. // Drop skeleton CUs.
  546. if (CU->getDWOId())
  547. return nullptr;
  548. auto *File = cast_or_null<DIFile>(map(CU->getFile()));
  549. MDTuple *EnumTypes = nullptr;
  550. MDTuple *RetainedTypes = nullptr;
  551. MDTuple *GlobalVariables = nullptr;
  552. MDTuple *ImportedEntities = nullptr;
  553. return DICompileUnit::getDistinct(
  554. CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
  555. CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
  556. CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
  557. RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
  558. CU->getDWOId(), CU->getSplitDebugInlining(),
  559. CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
  560. CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
  561. }
  562. DILocation *getReplacementMDLocation(DILocation *MLD) {
  563. auto *Scope = map(MLD->getScope());
  564. auto *InlinedAt = map(MLD->getInlinedAt());
  565. if (MLD->isDistinct())
  566. return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
  567. MLD->getColumn(), Scope, InlinedAt);
  568. return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
  569. Scope, InlinedAt);
  570. }
  571. /// Create a new generic MDNode, to replace the one given
  572. MDNode *getReplacementMDNode(MDNode *N) {
  573. SmallVector<Metadata *, 8> Ops;
  574. Ops.reserve(N->getNumOperands());
  575. for (auto &I : N->operands())
  576. if (I)
  577. Ops.push_back(map(I));
  578. auto *Ret = MDNode::get(N->getContext(), Ops);
  579. return Ret;
  580. }
  581. /// Attempt to re-map N to a newly created node.
  582. void remap(MDNode *N) {
  583. if (Replacements.count(N))
  584. return;
  585. auto doRemap = [&](MDNode *N) -> MDNode * {
  586. if (!N)
  587. return nullptr;
  588. if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
  589. remap(MDSub->getUnit());
  590. return getReplacementSubprogram(MDSub);
  591. }
  592. if (isa<DISubroutineType>(N))
  593. return EmptySubroutineType;
  594. if (auto *CU = dyn_cast<DICompileUnit>(N))
  595. return getReplacementCU(CU);
  596. if (isa<DIFile>(N))
  597. return N;
  598. if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
  599. // Remap to our referenced scope (recursively).
  600. return mapNode(MDLB->getScope());
  601. if (auto *MLD = dyn_cast<DILocation>(N))
  602. return getReplacementMDLocation(MLD);
  603. // Otherwise, if we see these, just drop them now. Not strictly necessary,
  604. // but this speeds things up a little.
  605. if (isa<DINode>(N))
  606. return nullptr;
  607. return getReplacementMDNode(N);
  608. };
  609. Replacements[N] = doRemap(N);
  610. }
  611. /// Do the remapping traversal.
  612. void traverse(MDNode *);
  613. };
  614. } // end anonymous namespace
  615. void DebugTypeInfoRemoval::traverse(MDNode *N) {
  616. if (!N || Replacements.count(N))
  617. return;
  618. // To avoid cycles, as well as for efficiency sake, we will sometimes prune
  619. // parts of the graph.
  620. auto prune = [](MDNode *Parent, MDNode *Child) {
  621. if (auto *MDS = dyn_cast<DISubprogram>(Parent))
  622. return Child == MDS->getRetainedNodes().get();
  623. return false;
  624. };
  625. SmallVector<MDNode *, 16> ToVisit;
  626. DenseSet<MDNode *> Opened;
  627. // Visit each node starting at N in post order, and map them.
  628. ToVisit.push_back(N);
  629. while (!ToVisit.empty()) {
  630. auto *N = ToVisit.back();
  631. if (!Opened.insert(N).second) {
  632. // Close it.
  633. remap(N);
  634. ToVisit.pop_back();
  635. continue;
  636. }
  637. for (auto &I : N->operands())
  638. if (auto *MDN = dyn_cast_or_null<MDNode>(I))
  639. if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
  640. !isa<DICompileUnit>(MDN))
  641. ToVisit.push_back(MDN);
  642. }
  643. }
  644. bool llvm::stripNonLineTableDebugInfo(Module &M) {
  645. bool Changed = false;
  646. // First off, delete the debug intrinsics.
  647. auto RemoveUses = [&](StringRef Name) {
  648. if (auto *DbgVal = M.getFunction(Name)) {
  649. while (!DbgVal->use_empty())
  650. cast<Instruction>(DbgVal->user_back())->eraseFromParent();
  651. DbgVal->eraseFromParent();
  652. Changed = true;
  653. }
  654. };
  655. RemoveUses("llvm.dbg.addr");
  656. RemoveUses("llvm.dbg.declare");
  657. RemoveUses("llvm.dbg.label");
  658. RemoveUses("llvm.dbg.value");
  659. // Delete non-CU debug info named metadata nodes.
  660. for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
  661. NMI != NME;) {
  662. NamedMDNode *NMD = &*NMI;
  663. ++NMI;
  664. // Specifically keep dbg.cu around.
  665. if (NMD->getName() == "llvm.dbg.cu")
  666. continue;
  667. }
  668. // Drop all dbg attachments from global variables.
  669. for (auto &GV : M.globals())
  670. GV.eraseMetadata(LLVMContext::MD_dbg);
  671. DebugTypeInfoRemoval Mapper(M.getContext());
  672. auto remap = [&](MDNode *Node) -> MDNode * {
  673. if (!Node)
  674. return nullptr;
  675. Mapper.traverseAndRemap(Node);
  676. auto *NewNode = Mapper.mapNode(Node);
  677. Changed |= Node != NewNode;
  678. Node = NewNode;
  679. return NewNode;
  680. };
  681. // Rewrite the DebugLocs to be equivalent to what
  682. // -gline-tables-only would have created.
  683. for (auto &F : M) {
  684. if (auto *SP = F.getSubprogram()) {
  685. Mapper.traverseAndRemap(SP);
  686. auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
  687. Changed |= SP != NewSP;
  688. F.setSubprogram(NewSP);
  689. }
  690. for (auto &BB : F) {
  691. for (auto &I : BB) {
  692. auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
  693. auto *Scope = DL.getScope();
  694. MDNode *InlinedAt = DL.getInlinedAt();
  695. Scope = remap(Scope);
  696. InlinedAt = remap(InlinedAt);
  697. return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
  698. Scope, InlinedAt);
  699. };
  700. if (I.getDebugLoc() != DebugLoc())
  701. I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
  702. // Remap DILocations in llvm.loop attachments.
  703. updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
  704. if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
  705. return remapDebugLoc(Loc).get();
  706. return MD;
  707. });
  708. // Strip heapallocsite attachments, they point into the DIType system.
  709. if (I.hasMetadataOtherThanDebugLoc())
  710. I.setMetadata("heapallocsite", nullptr);
  711. }
  712. }
  713. }
  714. // Create a new llvm.dbg.cu, which is equivalent to the one
  715. // -gline-tables-only would have created.
  716. for (auto &NMD : M.getNamedMDList()) {
  717. SmallVector<MDNode *, 8> Ops;
  718. for (MDNode *Op : NMD.operands())
  719. Ops.push_back(remap(Op));
  720. if (!Changed)
  721. continue;
  722. NMD.clearOperands();
  723. for (auto *Op : Ops)
  724. if (Op)
  725. NMD.addOperand(Op);
  726. }
  727. return Changed;
  728. }
  729. unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
  730. if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
  731. M.getModuleFlag("Debug Info Version")))
  732. return Val->getZExtValue();
  733. return 0;
  734. }
  735. void Instruction::applyMergedLocation(const DILocation *LocA,
  736. const DILocation *LocB) {
  737. setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
  738. }
  739. void Instruction::mergeDIAssignID(
  740. ArrayRef<const Instruction *> SourceInstructions) {
  741. // Replace all uses (and attachments) of all the DIAssignIDs
  742. // on SourceInstructions with a single merged value.
  743. assert(getFunction() && "Uninserted instruction merged");
  744. // Collect up the DIAssignID tags.
  745. SmallVector<DIAssignID *, 4> IDs;
  746. for (const Instruction *I : SourceInstructions) {
  747. if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))
  748. IDs.push_back(cast<DIAssignID>(MD));
  749. assert(getFunction() == I->getFunction() &&
  750. "Merging with instruction from another function not allowed");
  751. }
  752. // Add this instruction's DIAssignID too, if it has one.
  753. if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))
  754. IDs.push_back(cast<DIAssignID>(MD));
  755. if (IDs.empty())
  756. return; // No DIAssignID tags to process.
  757. DIAssignID *MergeID = IDs[0];
  758. for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {
  759. if (*It != MergeID)
  760. at::RAUW(*It, MergeID);
  761. }
  762. setMetadata(LLVMContext::MD_DIAssignID, MergeID);
  763. }
  764. void Instruction::updateLocationAfterHoist() { dropLocation(); }
  765. void Instruction::dropLocation() {
  766. const DebugLoc &DL = getDebugLoc();
  767. if (!DL)
  768. return;
  769. // If this isn't a call, drop the location to allow a location from a
  770. // preceding instruction to propagate.
  771. bool MayLowerToCall = false;
  772. if (isa<CallBase>(this)) {
  773. auto *II = dyn_cast<IntrinsicInst>(this);
  774. MayLowerToCall =
  775. !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());
  776. }
  777. if (!MayLowerToCall) {
  778. setDebugLoc(DebugLoc());
  779. return;
  780. }
  781. // Set a line 0 location for calls to preserve scope information in case
  782. // inlining occurs.
  783. DISubprogram *SP = getFunction()->getSubprogram();
  784. if (SP)
  785. // If a function scope is available, set it on the line 0 location. When
  786. // hoisting a call to a predecessor block, using the function scope avoids
  787. // making it look like the callee was reached earlier than it should be.
  788. setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
  789. else
  790. // The parent function has no scope. Go ahead and drop the location. If
  791. // the parent function is inlined, and the callee has a subprogram, the
  792. // inliner will attach a location to the call.
  793. //
  794. // One alternative is to set a line 0 location with the existing scope and
  795. // inlinedAt info. The location might be sensitive to when inlining occurs.
  796. setDebugLoc(DebugLoc());
  797. }
  798. //===----------------------------------------------------------------------===//
  799. // LLVM C API implementations.
  800. //===----------------------------------------------------------------------===//
  801. static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
  802. switch (lang) {
  803. #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \
  804. case LLVMDWARFSourceLanguage##NAME: \
  805. return ID;
  806. #include "llvm/BinaryFormat/Dwarf.def"
  807. #undef HANDLE_DW_LANG
  808. }
  809. llvm_unreachable("Unhandled Tag");
  810. }
  811. template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
  812. return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
  813. }
  814. static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
  815. return static_cast<DINode::DIFlags>(Flags);
  816. }
  817. static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
  818. return static_cast<LLVMDIFlags>(Flags);
  819. }
  820. static DISubprogram::DISPFlags
  821. pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
  822. return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
  823. }
  824. unsigned LLVMDebugMetadataVersion() {
  825. return DEBUG_METADATA_VERSION;
  826. }
  827. LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
  828. return wrap(new DIBuilder(*unwrap(M), false));
  829. }
  830. LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
  831. return wrap(new DIBuilder(*unwrap(M)));
  832. }
  833. unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
  834. return getDebugMetadataVersionFromModule(*unwrap(M));
  835. }
  836. LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
  837. return StripDebugInfo(*unwrap(M));
  838. }
  839. void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
  840. delete unwrap(Builder);
  841. }
  842. void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
  843. unwrap(Builder)->finalize();
  844. }
  845. void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
  846. LLVMMetadataRef subprogram) {
  847. unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
  848. }
  849. LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
  850. LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
  851. LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
  852. LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
  853. unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
  854. LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
  855. LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
  856. const char *SDK, size_t SDKLen) {
  857. auto File = unwrapDI<DIFile>(FileRef);
  858. return wrap(unwrap(Builder)->createCompileUnit(
  859. map_from_llvmDWARFsourcelanguage(Lang), File,
  860. StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
  861. RuntimeVer, StringRef(SplitName, SplitNameLen),
  862. static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
  863. SplitDebugInlining, DebugInfoForProfiling,
  864. DICompileUnit::DebugNameTableKind::Default, false,
  865. StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
  866. }
  867. LLVMMetadataRef
  868. LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
  869. size_t FilenameLen, const char *Directory,
  870. size_t DirectoryLen) {
  871. return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
  872. StringRef(Directory, DirectoryLen)));
  873. }
  874. LLVMMetadataRef
  875. LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
  876. const char *Name, size_t NameLen,
  877. const char *ConfigMacros, size_t ConfigMacrosLen,
  878. const char *IncludePath, size_t IncludePathLen,
  879. const char *APINotesFile, size_t APINotesFileLen) {
  880. return wrap(unwrap(Builder)->createModule(
  881. unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
  882. StringRef(ConfigMacros, ConfigMacrosLen),
  883. StringRef(IncludePath, IncludePathLen),
  884. StringRef(APINotesFile, APINotesFileLen)));
  885. }
  886. LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
  887. LLVMMetadataRef ParentScope,
  888. const char *Name, size_t NameLen,
  889. LLVMBool ExportSymbols) {
  890. return wrap(unwrap(Builder)->createNameSpace(
  891. unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
  892. }
  893. LLVMMetadataRef LLVMDIBuilderCreateFunction(
  894. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  895. size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
  896. LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
  897. LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
  898. unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
  899. return wrap(unwrap(Builder)->createFunction(
  900. unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
  901. unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
  902. map_from_llvmDIFlags(Flags),
  903. pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
  904. nullptr, nullptr));
  905. }
  906. LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
  907. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
  908. LLVMMetadataRef File, unsigned Line, unsigned Col) {
  909. return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
  910. unwrapDI<DIFile>(File),
  911. Line, Col));
  912. }
  913. LLVMMetadataRef
  914. LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
  915. LLVMMetadataRef Scope,
  916. LLVMMetadataRef File,
  917. unsigned Discriminator) {
  918. return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
  919. unwrapDI<DIFile>(File),
  920. Discriminator));
  921. }
  922. LLVMMetadataRef
  923. LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
  924. LLVMMetadataRef Scope,
  925. LLVMMetadataRef NS,
  926. LLVMMetadataRef File,
  927. unsigned Line) {
  928. return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
  929. unwrapDI<DINamespace>(NS),
  930. unwrapDI<DIFile>(File),
  931. Line));
  932. }
  933. LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
  934. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
  935. LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
  936. LLVMMetadataRef *Elements, unsigned NumElements) {
  937. auto Elts =
  938. (NumElements > 0)
  939. ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
  940. : nullptr;
  941. return wrap(unwrap(Builder)->createImportedModule(
  942. unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
  943. unwrapDI<DIFile>(File), Line, Elts));
  944. }
  945. LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
  946. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
  947. LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
  948. unsigned NumElements) {
  949. auto Elts =
  950. (NumElements > 0)
  951. ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
  952. : nullptr;
  953. return wrap(unwrap(Builder)->createImportedModule(
  954. unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
  955. Line, Elts));
  956. }
  957. LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
  958. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
  959. LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
  960. LLVMMetadataRef *Elements, unsigned NumElements) {
  961. auto Elts =
  962. (NumElements > 0)
  963. ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
  964. : nullptr;
  965. return wrap(unwrap(Builder)->createImportedDeclaration(
  966. unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
  967. Line, {Name, NameLen}, Elts));
  968. }
  969. LLVMMetadataRef
  970. LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
  971. unsigned Column, LLVMMetadataRef Scope,
  972. LLVMMetadataRef InlinedAt) {
  973. return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
  974. unwrap(InlinedAt)));
  975. }
  976. unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
  977. return unwrapDI<DILocation>(Location)->getLine();
  978. }
  979. unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
  980. return unwrapDI<DILocation>(Location)->getColumn();
  981. }
  982. LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
  983. return wrap(unwrapDI<DILocation>(Location)->getScope());
  984. }
  985. LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
  986. return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
  987. }
  988. LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
  989. return wrap(unwrapDI<DIScope>(Scope)->getFile());
  990. }
  991. const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
  992. auto Dir = unwrapDI<DIFile>(File)->getDirectory();
  993. *Len = Dir.size();
  994. return Dir.data();
  995. }
  996. const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
  997. auto Name = unwrapDI<DIFile>(File)->getFilename();
  998. *Len = Name.size();
  999. return Name.data();
  1000. }
  1001. const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
  1002. if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
  1003. *Len = Src->size();
  1004. return Src->data();
  1005. }
  1006. *Len = 0;
  1007. return "";
  1008. }
  1009. LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
  1010. LLVMMetadataRef ParentMacroFile,
  1011. unsigned Line,
  1012. LLVMDWARFMacinfoRecordType RecordType,
  1013. const char *Name, size_t NameLen,
  1014. const char *Value, size_t ValueLen) {
  1015. return wrap(
  1016. unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
  1017. static_cast<MacinfoRecordType>(RecordType),
  1018. {Name, NameLen}, {Value, ValueLen}));
  1019. }
  1020. LLVMMetadataRef
  1021. LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
  1022. LLVMMetadataRef ParentMacroFile, unsigned Line,
  1023. LLVMMetadataRef File) {
  1024. return wrap(unwrap(Builder)->createTempMacroFile(
  1025. unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
  1026. }
  1027. LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
  1028. const char *Name, size_t NameLen,
  1029. int64_t Value,
  1030. LLVMBool IsUnsigned) {
  1031. return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
  1032. IsUnsigned != 0));
  1033. }
  1034. LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
  1035. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1036. size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
  1037. uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
  1038. unsigned NumElements, LLVMMetadataRef ClassTy) {
  1039. auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
  1040. NumElements});
  1041. return wrap(unwrap(Builder)->createEnumerationType(
  1042. unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
  1043. LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
  1044. }
  1045. LLVMMetadataRef LLVMDIBuilderCreateUnionType(
  1046. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1047. size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
  1048. uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
  1049. LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
  1050. const char *UniqueId, size_t UniqueIdLen) {
  1051. auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
  1052. NumElements});
  1053. return wrap(unwrap(Builder)->createUnionType(
  1054. unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
  1055. LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
  1056. Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
  1057. }
  1058. LLVMMetadataRef
  1059. LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
  1060. uint32_t AlignInBits, LLVMMetadataRef Ty,
  1061. LLVMMetadataRef *Subscripts,
  1062. unsigned NumSubscripts) {
  1063. auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
  1064. NumSubscripts});
  1065. return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
  1066. unwrapDI<DIType>(Ty), Subs));
  1067. }
  1068. LLVMMetadataRef
  1069. LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
  1070. uint32_t AlignInBits, LLVMMetadataRef Ty,
  1071. LLVMMetadataRef *Subscripts,
  1072. unsigned NumSubscripts) {
  1073. auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
  1074. NumSubscripts});
  1075. return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
  1076. unwrapDI<DIType>(Ty), Subs));
  1077. }
  1078. LLVMMetadataRef
  1079. LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
  1080. size_t NameLen, uint64_t SizeInBits,
  1081. LLVMDWARFTypeEncoding Encoding,
  1082. LLVMDIFlags Flags) {
  1083. return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
  1084. SizeInBits, Encoding,
  1085. map_from_llvmDIFlags(Flags)));
  1086. }
  1087. LLVMMetadataRef LLVMDIBuilderCreatePointerType(
  1088. LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
  1089. uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
  1090. const char *Name, size_t NameLen) {
  1091. return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
  1092. SizeInBits, AlignInBits,
  1093. AddressSpace, {Name, NameLen}));
  1094. }
  1095. LLVMMetadataRef LLVMDIBuilderCreateStructType(
  1096. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1097. size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
  1098. uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
  1099. LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
  1100. unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
  1101. const char *UniqueId, size_t UniqueIdLen) {
  1102. auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
  1103. NumElements});
  1104. return wrap(unwrap(Builder)->createStructType(
  1105. unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
  1106. LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
  1107. unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
  1108. unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
  1109. }
  1110. LLVMMetadataRef LLVMDIBuilderCreateMemberType(
  1111. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1112. size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
  1113. uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
  1114. LLVMMetadataRef Ty) {
  1115. return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
  1116. {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
  1117. OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
  1118. }
  1119. LLVMMetadataRef
  1120. LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
  1121. size_t NameLen) {
  1122. return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
  1123. }
  1124. LLVMMetadataRef
  1125. LLVMDIBuilderCreateStaticMemberType(
  1126. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1127. size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
  1128. LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
  1129. uint32_t AlignInBits) {
  1130. return wrap(unwrap(Builder)->createStaticMemberType(
  1131. unwrapDI<DIScope>(Scope), {Name, NameLen},
  1132. unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
  1133. map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
  1134. AlignInBits));
  1135. }
  1136. LLVMMetadataRef
  1137. LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
  1138. const char *Name, size_t NameLen,
  1139. LLVMMetadataRef File, unsigned LineNo,
  1140. uint64_t SizeInBits, uint32_t AlignInBits,
  1141. uint64_t OffsetInBits, LLVMDIFlags Flags,
  1142. LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
  1143. return wrap(unwrap(Builder)->createObjCIVar(
  1144. {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
  1145. SizeInBits, AlignInBits, OffsetInBits,
  1146. map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
  1147. unwrapDI<MDNode>(PropertyNode)));
  1148. }
  1149. LLVMMetadataRef
  1150. LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
  1151. const char *Name, size_t NameLen,
  1152. LLVMMetadataRef File, unsigned LineNo,
  1153. const char *GetterName, size_t GetterNameLen,
  1154. const char *SetterName, size_t SetterNameLen,
  1155. unsigned PropertyAttributes,
  1156. LLVMMetadataRef Ty) {
  1157. return wrap(unwrap(Builder)->createObjCProperty(
  1158. {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
  1159. {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
  1160. PropertyAttributes, unwrapDI<DIType>(Ty)));
  1161. }
  1162. LLVMMetadataRef
  1163. LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
  1164. LLVMMetadataRef Type) {
  1165. return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
  1166. }
  1167. LLVMMetadataRef
  1168. LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
  1169. const char *Name, size_t NameLen,
  1170. LLVMMetadataRef File, unsigned LineNo,
  1171. LLVMMetadataRef Scope, uint32_t AlignInBits) {
  1172. return wrap(unwrap(Builder)->createTypedef(
  1173. unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
  1174. unwrapDI<DIScope>(Scope), AlignInBits));
  1175. }
  1176. LLVMMetadataRef
  1177. LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
  1178. LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
  1179. uint64_t BaseOffset, uint32_t VBPtrOffset,
  1180. LLVMDIFlags Flags) {
  1181. return wrap(unwrap(Builder)->createInheritance(
  1182. unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
  1183. BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
  1184. }
  1185. LLVMMetadataRef
  1186. LLVMDIBuilderCreateForwardDecl(
  1187. LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
  1188. size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
  1189. unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
  1190. const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
  1191. return wrap(unwrap(Builder)->createForwardDecl(
  1192. Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
  1193. unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
  1194. AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
  1195. }
  1196. LLVMMetadataRef
  1197. LLVMDIBuilderCreateReplaceableCompositeType(
  1198. LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
  1199. size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
  1200. unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
  1201. LLVMDIFlags Flags, const char *UniqueIdentifier,
  1202. size_t UniqueIdentifierLen) {
  1203. return wrap(unwrap(Builder)->createReplaceableCompositeType(
  1204. Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
  1205. unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
  1206. AlignInBits, map_from_llvmDIFlags(Flags),
  1207. {UniqueIdentifier, UniqueIdentifierLen}));
  1208. }
  1209. LLVMMetadataRef
  1210. LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
  1211. LLVMMetadataRef Type) {
  1212. return wrap(unwrap(Builder)->createQualifiedType(Tag,
  1213. unwrapDI<DIType>(Type)));
  1214. }
  1215. LLVMMetadataRef
  1216. LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
  1217. LLVMMetadataRef Type) {
  1218. return wrap(unwrap(Builder)->createReferenceType(Tag,
  1219. unwrapDI<DIType>(Type)));
  1220. }
  1221. LLVMMetadataRef
  1222. LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
  1223. return wrap(unwrap(Builder)->createNullPtrType());
  1224. }
  1225. LLVMMetadataRef
  1226. LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
  1227. LLVMMetadataRef PointeeType,
  1228. LLVMMetadataRef ClassType,
  1229. uint64_t SizeInBits,
  1230. uint32_t AlignInBits,
  1231. LLVMDIFlags Flags) {
  1232. return wrap(unwrap(Builder)->createMemberPointerType(
  1233. unwrapDI<DIType>(PointeeType),
  1234. unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
  1235. map_from_llvmDIFlags(Flags)));
  1236. }
  1237. LLVMMetadataRef
  1238. LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
  1239. LLVMMetadataRef Scope,
  1240. const char *Name, size_t NameLen,
  1241. LLVMMetadataRef File, unsigned LineNumber,
  1242. uint64_t SizeInBits,
  1243. uint64_t OffsetInBits,
  1244. uint64_t StorageOffsetInBits,
  1245. LLVMDIFlags Flags, LLVMMetadataRef Type) {
  1246. return wrap(unwrap(Builder)->createBitFieldMemberType(
  1247. unwrapDI<DIScope>(Scope), {Name, NameLen},
  1248. unwrapDI<DIFile>(File), LineNumber,
  1249. SizeInBits, OffsetInBits, StorageOffsetInBits,
  1250. map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
  1251. }
  1252. LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
  1253. LLVMMetadataRef Scope, const char *Name, size_t NameLen,
  1254. LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
  1255. uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
  1256. LLVMMetadataRef DerivedFrom,
  1257. LLVMMetadataRef *Elements, unsigned NumElements,
  1258. LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
  1259. const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
  1260. auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
  1261. NumElements});
  1262. return wrap(unwrap(Builder)->createClassType(
  1263. unwrapDI<DIScope>(Scope), {Name, NameLen},
  1264. unwrapDI<DIFile>(File), LineNumber,
  1265. SizeInBits, AlignInBits, OffsetInBits,
  1266. map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom),
  1267. Elts, unwrapDI<DIType>(VTableHolder),
  1268. unwrapDI<MDNode>(TemplateParamsNode),
  1269. {UniqueIdentifier, UniqueIdentifierLen}));
  1270. }
  1271. LLVMMetadataRef
  1272. LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
  1273. LLVMMetadataRef Type) {
  1274. return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
  1275. }
  1276. const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
  1277. StringRef Str = unwrap<DIType>(DType)->getName();
  1278. *Length = Str.size();
  1279. return Str.data();
  1280. }
  1281. uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
  1282. return unwrapDI<DIType>(DType)->getSizeInBits();
  1283. }
  1284. uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
  1285. return unwrapDI<DIType>(DType)->getOffsetInBits();
  1286. }
  1287. uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
  1288. return unwrapDI<DIType>(DType)->getAlignInBits();
  1289. }
  1290. unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
  1291. return unwrapDI<DIType>(DType)->getLine();
  1292. }
  1293. LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
  1294. return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
  1295. }
  1296. LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
  1297. LLVMMetadataRef *Types,
  1298. size_t Length) {
  1299. return wrap(
  1300. unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
  1301. }
  1302. LLVMMetadataRef
  1303. LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
  1304. LLVMMetadataRef File,
  1305. LLVMMetadataRef *ParameterTypes,
  1306. unsigned NumParameterTypes,
  1307. LLVMDIFlags Flags) {
  1308. auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
  1309. NumParameterTypes});
  1310. return wrap(unwrap(Builder)->createSubroutineType(
  1311. Elts, map_from_llvmDIFlags(Flags)));
  1312. }
  1313. LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
  1314. uint64_t *Addr, size_t Length) {
  1315. return wrap(
  1316. unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
  1317. }
  1318. LLVMMetadataRef
  1319. LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
  1320. uint64_t Value) {
  1321. return wrap(unwrap(Builder)->createConstantValueExpression(Value));
  1322. }
  1323. LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
  1324. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1325. size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
  1326. unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
  1327. LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
  1328. return wrap(unwrap(Builder)->createGlobalVariableExpression(
  1329. unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
  1330. unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
  1331. true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
  1332. nullptr, AlignInBits));
  1333. }
  1334. LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
  1335. return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
  1336. }
  1337. LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
  1338. LLVMMetadataRef GVE) {
  1339. return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
  1340. }
  1341. LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
  1342. return wrap(unwrapDI<DIVariable>(Var)->getFile());
  1343. }
  1344. LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
  1345. return wrap(unwrapDI<DIVariable>(Var)->getScope());
  1346. }
  1347. unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
  1348. return unwrapDI<DIVariable>(Var)->getLine();
  1349. }
  1350. LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
  1351. size_t Count) {
  1352. return wrap(
  1353. MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
  1354. }
  1355. void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
  1356. MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
  1357. }
  1358. void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
  1359. LLVMMetadataRef Replacement) {
  1360. auto *Node = unwrapDI<MDNode>(TargetMetadata);
  1361. Node->replaceAllUsesWith(unwrap(Replacement));
  1362. MDNode::deleteTemporary(Node);
  1363. }
  1364. LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
  1365. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1366. size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
  1367. unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
  1368. LLVMMetadataRef Decl, uint32_t AlignInBits) {
  1369. return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
  1370. unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
  1371. unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
  1372. unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
  1373. }
  1374. LLVMValueRef
  1375. LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
  1376. LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
  1377. LLVMMetadataRef DL, LLVMValueRef Instr) {
  1378. return wrap(unwrap(Builder)->insertDeclare(
  1379. unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
  1380. unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
  1381. unwrap<Instruction>(Instr)));
  1382. }
  1383. LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
  1384. LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
  1385. LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
  1386. return wrap(unwrap(Builder)->insertDeclare(
  1387. unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
  1388. unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
  1389. unwrap(Block)));
  1390. }
  1391. LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
  1392. LLVMValueRef Val,
  1393. LLVMMetadataRef VarInfo,
  1394. LLVMMetadataRef Expr,
  1395. LLVMMetadataRef DebugLoc,
  1396. LLVMValueRef Instr) {
  1397. return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
  1398. unwrap(Val), unwrap<DILocalVariable>(VarInfo),
  1399. unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
  1400. unwrap<Instruction>(Instr)));
  1401. }
  1402. LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
  1403. LLVMValueRef Val,
  1404. LLVMMetadataRef VarInfo,
  1405. LLVMMetadataRef Expr,
  1406. LLVMMetadataRef DebugLoc,
  1407. LLVMBasicBlockRef Block) {
  1408. return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
  1409. unwrap(Val), unwrap<DILocalVariable>(VarInfo),
  1410. unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
  1411. unwrap(Block)));
  1412. }
  1413. LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
  1414. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1415. size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
  1416. LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
  1417. return wrap(unwrap(Builder)->createAutoVariable(
  1418. unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
  1419. LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
  1420. map_from_llvmDIFlags(Flags), AlignInBits));
  1421. }
  1422. LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
  1423. LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
  1424. size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
  1425. LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
  1426. return wrap(unwrap(Builder)->createParameterVariable(
  1427. unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
  1428. LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
  1429. map_from_llvmDIFlags(Flags)));
  1430. }
  1431. LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
  1432. int64_t Lo, int64_t Count) {
  1433. return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
  1434. }
  1435. LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
  1436. LLVMMetadataRef *Data,
  1437. size_t Length) {
  1438. Metadata **DataValue = unwrap(Data);
  1439. return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
  1440. }
  1441. LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
  1442. return wrap(unwrap<Function>(Func)->getSubprogram());
  1443. }
  1444. void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
  1445. unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
  1446. }
  1447. unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
  1448. return unwrapDI<DISubprogram>(Subprogram)->getLine();
  1449. }
  1450. LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
  1451. return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
  1452. }
  1453. void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
  1454. if (Loc)
  1455. unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
  1456. else
  1457. unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
  1458. }
  1459. LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
  1460. switch(unwrap(Metadata)->getMetadataID()) {
  1461. #define HANDLE_METADATA_LEAF(CLASS) \
  1462. case Metadata::CLASS##Kind: \
  1463. return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
  1464. #include "llvm/IR/Metadata.def"
  1465. default:
  1466. return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
  1467. }
  1468. }
  1469. AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {
  1470. assert(ID && "Expected non-null ID");
  1471. LLVMContext &Ctx = ID->getContext();
  1472. auto &Map = Ctx.pImpl->AssignmentIDToInstrs;
  1473. auto MapIt = Map.find(ID);
  1474. if (MapIt == Map.end())
  1475. return make_range(nullptr, nullptr);
  1476. return make_range(MapIt->second.begin(), MapIt->second.end());
  1477. }
  1478. AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {
  1479. assert(ID && "Expected non-null ID");
  1480. LLVMContext &Ctx = ID->getContext();
  1481. auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);
  1482. // The ID is only used wrapped in MetadataAsValue(ID), so lets check that
  1483. // one of those already exists first.
  1484. if (!IDAsValue)
  1485. return make_range(Value::user_iterator(), Value::user_iterator());
  1486. return make_range(IDAsValue->user_begin(), IDAsValue->user_end());
  1487. }
  1488. void at::deleteAssignmentMarkers(const Instruction *Inst) {
  1489. auto Range = getAssignmentMarkers(Inst);
  1490. if (Range.empty())
  1491. return;
  1492. SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());
  1493. for (auto *DAI : ToDelete)
  1494. DAI->eraseFromParent();
  1495. }
  1496. void at::RAUW(DIAssignID *Old, DIAssignID *New) {
  1497. // Replace MetadataAsValue uses.
  1498. if (auto *OldIDAsValue =
  1499. MetadataAsValue::getIfExists(Old->getContext(), Old)) {
  1500. auto *NewIDAsValue = MetadataAsValue::get(Old->getContext(), New);
  1501. OldIDAsValue->replaceAllUsesWith(NewIDAsValue);
  1502. }
  1503. // Replace attachments.
  1504. AssignmentInstRange InstRange = getAssignmentInsts(Old);
  1505. // Use intermediate storage for the instruction ptrs because the
  1506. // getAssignmentInsts range iterators will be invalidated by adding and
  1507. // removing DIAssignID attachments.
  1508. SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());
  1509. for (auto *I : InstVec)
  1510. I->setMetadata(LLVMContext::MD_DIAssignID, New);
  1511. }
  1512. void at::deleteAll(Function *F) {
  1513. SmallVector<DbgAssignIntrinsic *, 12> ToDelete;
  1514. for (BasicBlock &BB : *F) {
  1515. for (Instruction &I : BB) {
  1516. if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
  1517. ToDelete.push_back(DAI);
  1518. else
  1519. I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
  1520. }
  1521. }
  1522. for (auto *DAI : ToDelete)
  1523. DAI->eraseFromParent();
  1524. }
  1525. /// Collect constant properies (base, size, offset) of \p StoreDest.
  1526. /// Return std::nullopt if any properties are not constants.
  1527. static std::optional<AssignmentInfo>
  1528. getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,
  1529. uint64_t SizeInBits) {
  1530. APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);
  1531. const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(
  1532. DL, GEPOffset, /*AllowNonInbounds*/ true);
  1533. uint64_t OffsetInBytes = GEPOffset.getLimitedValue();
  1534. // Check for overflow.
  1535. if (OffsetInBytes == UINT64_MAX)
  1536. return std::nullopt;
  1537. if (const auto *Alloca = dyn_cast<AllocaInst>(Base))
  1538. return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);
  1539. return std::nullopt;
  1540. }
  1541. std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
  1542. const MemIntrinsic *I) {
  1543. const Value *StoreDest = I->getRawDest();
  1544. // Assume 8 bit bytes.
  1545. auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());
  1546. if (!ConstLengthInBytes)
  1547. // We can't use a non-const size, bail.
  1548. return std::nullopt;
  1549. uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
  1550. return getAssignmentInfoImpl(DL, StoreDest, SizeInBits);
  1551. }
  1552. std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
  1553. const StoreInst *SI) {
  1554. const Value *StoreDest = SI->getPointerOperand();
  1555. uint64_t SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());
  1556. return getAssignmentInfoImpl(DL, StoreDest, SizeInBits);
  1557. }
  1558. std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
  1559. const AllocaInst *AI) {
  1560. uint64_t SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());
  1561. return getAssignmentInfoImpl(DL, AI, SizeInBits);
  1562. }
  1563. static CallInst *emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
  1564. Instruction &StoreLikeInst,
  1565. const VarRecord &VarRec, DIBuilder &DIB) {
  1566. auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);
  1567. assert(ID && "Store instruction must have DIAssignID metadata");
  1568. (void)ID;
  1569. DIExpression *Expr =
  1570. DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
  1571. if (!Info.StoreToWholeAlloca) {
  1572. auto R = DIExpression::createFragmentExpression(Expr, Info.OffsetInBits,
  1573. Info.SizeInBits);
  1574. assert(R.has_value() && "failed to create fragment expression");
  1575. Expr = *R;
  1576. }
  1577. DIExpression *AddrExpr =
  1578. DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
  1579. return DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,
  1580. AddrExpr, VarRec.DL);
  1581. }
  1582. #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
  1583. #define DEBUG_TYPE "assignment-tracking"
  1584. void at::trackAssignments(Function::iterator Start, Function::iterator End,
  1585. const StorageToVarsMap &Vars, const DataLayout &DL,
  1586. bool DebugPrints) {
  1587. // Early-exit if there are no interesting variables.
  1588. if (Vars.empty())
  1589. return;
  1590. auto &Ctx = Start->getContext();
  1591. auto &Module = *Start->getModule();
  1592. // Undef type doesn't matter, so long as it isn't void. Let's just use i1.
  1593. auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));
  1594. DIBuilder DIB(Module, /*AllowUnresolved*/ false);
  1595. // Scan the instructions looking for stores to local variables' storage.
  1596. LLVM_DEBUG(errs() << "# Scanning instructions\n");
  1597. for (auto BBI = Start; BBI != End; ++BBI) {
  1598. for (Instruction &I : *BBI) {
  1599. std::optional<AssignmentInfo> Info;
  1600. Value *ValueComponent = nullptr;
  1601. Value *DestComponent = nullptr;
  1602. if (auto *AI = dyn_cast<AllocaInst>(&I)) {
  1603. // We want to track the variable's stack home from its alloca's
  1604. // position onwards so we treat it as an assignment (where the stored
  1605. // value is Undef).
  1606. Info = getAssignmentInfo(DL, AI);
  1607. ValueComponent = Undef;
  1608. DestComponent = AI;
  1609. } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
  1610. Info = getAssignmentInfo(DL, SI);
  1611. ValueComponent = SI->getValueOperand();
  1612. DestComponent = SI->getPointerOperand();
  1613. } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {
  1614. Info = getAssignmentInfo(DL, MI);
  1615. // May not be able to represent this value easily.
  1616. ValueComponent = Undef;
  1617. DestComponent = MI->getOperand(0);
  1618. } else if (auto *MI = dyn_cast<MemSetInst>(&I)) {
  1619. Info = getAssignmentInfo(DL, MI);
  1620. // If we're zero-initing we can state the assigned value is zero,
  1621. // otherwise use undef.
  1622. auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));
  1623. if (ConstValue && ConstValue->isZero())
  1624. ValueComponent = ConstValue;
  1625. else
  1626. ValueComponent = Undef;
  1627. DestComponent = MI->getOperand(0);
  1628. } else {
  1629. // Not a store-like instruction.
  1630. continue;
  1631. }
  1632. assert(ValueComponent && DestComponent);
  1633. LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");
  1634. // Check if getAssignmentInfo failed to understand this store.
  1635. if (!Info.has_value()) {
  1636. LLVM_DEBUG(
  1637. errs()
  1638. << " | SKIP: Untrackable store (e.g. through non-const gep)\n");
  1639. continue;
  1640. }
  1641. LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");
  1642. // Check if the store destination is a local variable with debug info.
  1643. auto LocalIt = Vars.find(Info->Base);
  1644. if (LocalIt == Vars.end()) {
  1645. LLVM_DEBUG(
  1646. errs()
  1647. << " | SKIP: Base address not associated with local variable\n");
  1648. continue;
  1649. }
  1650. DIAssignID *ID =
  1651. cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));
  1652. if (!ID) {
  1653. ID = DIAssignID::getDistinct(Ctx);
  1654. I.setMetadata(LLVMContext::MD_DIAssignID, ID);
  1655. }
  1656. for (const VarRecord &R : LocalIt->second) {
  1657. auto *Assign =
  1658. emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);
  1659. (void)Assign;
  1660. LLVM_DEBUG(errs() << " > INSERT: " << *Assign << "\n");
  1661. }
  1662. }
  1663. }
  1664. }
  1665. void AssignmentTrackingPass::runOnFunction(Function &F) {
  1666. // Collect a map of {backing storage : dbg.declares} (currently "backing
  1667. // storage" is limited to Allocas). We'll use this to find dbg.declares to
  1668. // delete after running `trackAssignments`.
  1669. DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;
  1670. // Create another similar map of {storage : variables} that we'll pass to
  1671. // trackAssignments.
  1672. StorageToVarsMap Vars;
  1673. for (auto &BB : F) {
  1674. for (auto &I : BB) {
  1675. DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I);
  1676. if (!DDI)
  1677. continue;
  1678. // FIXME: trackAssignments doesn't let you specify any modifiers to the
  1679. // variable (e.g. fragment) or location (e.g. offset), so we have to
  1680. // leave dbg.declares with non-empty expressions in place.
  1681. if (DDI->getExpression()->getNumElements() != 0)
  1682. continue;
  1683. if (AllocaInst *Alloca =
  1684. dyn_cast<AllocaInst>(DDI->getAddress()->stripPointerCasts())) {
  1685. DbgDeclares[Alloca].insert(DDI);
  1686. Vars[Alloca].insert(VarRecord(DDI));
  1687. }
  1688. }
  1689. }
  1690. auto DL = std::make_unique<DataLayout>(F.getParent());
  1691. // FIXME: Locals can be backed by caller allocas (sret, byval).
  1692. // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
  1693. // doesn't "understand" dbg.declares). However, this doesn't appear to break
  1694. // any rules given this description of dbg.declare from
  1695. // llvm/docs/SourceLevelDebugging.rst:
  1696. //
  1697. // It is not control-dependent, meaning that if a call to llvm.dbg.declare
  1698. // exists and has a valid location argument, that address is considered to
  1699. // be the true home of the variable across its entire lifetime.
  1700. trackAssignments(F.begin(), F.end(), Vars, *DL);
  1701. // Delete dbg.declares for variables now tracked with assignment tracking.
  1702. for (auto &P : DbgDeclares) {
  1703. const AllocaInst *Alloca = P.first;
  1704. auto Markers = at::getAssignmentMarkers(Alloca);
  1705. (void)Markers;
  1706. for (DbgDeclareInst *DDI : P.second) {
  1707. // Assert that the alloca that DDI uses is now linked to a dbg.assign
  1708. // describing the same variable (i.e. check that this dbg.declare
  1709. // has been replaced by a dbg.assign).
  1710. assert(llvm::any_of(Markers, [DDI](DbgAssignIntrinsic *DAI) {
  1711. return DebugVariable(DAI) == DebugVariable(DDI);
  1712. }));
  1713. // Delete DDI because the variable location is now tracked using
  1714. // assignment tracking.
  1715. DDI->eraseFromParent();
  1716. }
  1717. }
  1718. }
  1719. static const char *AssignmentTrackingModuleFlag =
  1720. "debug-info-assignment-tracking";
  1721. static void setAssignmentTrackingModuleFlag(Module &M) {
  1722. M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,
  1723. ConstantAsMetadata::get(
  1724. ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));
  1725. }
  1726. static bool getAssignmentTrackingModuleFlag(const Module &M) {
  1727. Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);
  1728. return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();
  1729. }
  1730. bool llvm::isAssignmentTrackingEnabled(const Module &M) {
  1731. return getAssignmentTrackingModuleFlag(M);
  1732. }
  1733. PreservedAnalyses AssignmentTrackingPass::run(Function &F,
  1734. FunctionAnalysisManager &AM) {
  1735. runOnFunction(F);
  1736. // Record that this module uses assignment tracking. It doesn't matter that
  1737. // some functons in the module may not use it - the debug info in those
  1738. // functions will still be handled properly.
  1739. setAssignmentTrackingModuleFlag(*F.getParent());
  1740. // Q: Can we return a less conservative set than just CFGAnalyses? Can we
  1741. // return PreservedAnalyses::all()?
  1742. PreservedAnalyses PA;
  1743. PA.preserveSet<CFGAnalyses>();
  1744. return PA;
  1745. }
  1746. PreservedAnalyses AssignmentTrackingPass::run(Module &M,
  1747. ModuleAnalysisManager &AM) {
  1748. for (auto &F : M)
  1749. runOnFunction(F);
  1750. // Record that this module uses assignment tracking.
  1751. setAssignmentTrackingModuleFlag(M);
  1752. // Q: Can we return a less conservative set than just CFGAnalyses? Can we
  1753. // return PreservedAnalyses::all()?
  1754. PreservedAnalyses PA;
  1755. PA.preserveSet<CFGAnalyses>();
  1756. return PA;
  1757. }
  1758. #undef DEBUG_TYPE