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
14 #include "llvm-c/DebugInfo.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DebugProgramInstruction.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GVMaterializer.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/Support/Casting.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <optional>
41 #include <utility>
42
43 using namespace llvm;
44 using namespace llvm::at;
45 using namespace llvm::dwarf;
46
findDbgDeclares(Value * V)47 TinyPtrVector<DbgDeclareInst *> llvm::findDbgDeclares(Value *V) {
48 // This function is hot. Check whether the value has any metadata to avoid a
49 // DenseMap lookup.
50 if (!V->isUsedByMetadata())
51 return {};
52 auto *L = LocalAsMetadata::getIfExists(V);
53 if (!L)
54 return {};
55 auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L);
56 if (!MDV)
57 return {};
58
59 TinyPtrVector<DbgDeclareInst *> Declares;
60 for (User *U : MDV->users())
61 if (auto *DDI = dyn_cast<DbgDeclareInst>(U))
62 Declares.push_back(DDI);
63
64 return Declares;
65 }
findDPVDeclares(Value * V)66 TinyPtrVector<DPValue *> llvm::findDPVDeclares(Value *V) {
67 // This function is hot. Check whether the value has any metadata to avoid a
68 // DenseMap lookup.
69 if (!V->isUsedByMetadata())
70 return {};
71 auto *L = LocalAsMetadata::getIfExists(V);
72 if (!L)
73 return {};
74
75 TinyPtrVector<DPValue *> Declares;
76 for (DPValue *DPV : L->getAllDPValueUsers())
77 if (DPV->getType() == DPValue::LocationType::Declare)
78 Declares.push_back(DPV);
79
80 return Declares;
81 }
82
83 template <typename IntrinsicT,
84 DPValue::LocationType Type = DPValue::LocationType::Any>
findDbgIntrinsics(SmallVectorImpl<IntrinsicT * > & Result,Value * V,SmallVectorImpl<DPValue * > * DPValues)85 static void findDbgIntrinsics(SmallVectorImpl<IntrinsicT *> &Result, Value *V,
86 SmallVectorImpl<DPValue *> *DPValues) {
87 // This function is hot. Check whether the value has any metadata to avoid a
88 // DenseMap lookup.
89 if (!V->isUsedByMetadata())
90 return;
91
92 LLVMContext &Ctx = V->getContext();
93 // TODO: If this value appears multiple times in a DIArgList, we should still
94 // only add the owning DbgValueInst once; use this set to track ArgListUsers.
95 // This behaviour can be removed when we can automatically remove duplicates.
96 // V will also appear twice in a dbg.assign if its used in the both the value
97 // and address components.
98 SmallPtrSet<IntrinsicT *, 4> EncounteredIntrinsics;
99 SmallPtrSet<DPValue *, 4> EncounteredDPValues;
100
101 /// Append IntrinsicT users of MetadataAsValue(MD).
102 auto AppendUsers = [&Ctx, &EncounteredIntrinsics, &Result,
103 DPValues](Metadata *MD) {
104 if (auto *MDV = MetadataAsValue::getIfExists(Ctx, MD)) {
105 for (User *U : MDV->users())
106 if (IntrinsicT *DVI = dyn_cast<IntrinsicT>(U))
107 if (EncounteredIntrinsics.insert(DVI).second)
108 Result.push_back(DVI);
109 }
110 if (!DPValues)
111 return;
112 // Get DPValues that use this as a single value.
113 if (LocalAsMetadata *L = dyn_cast<LocalAsMetadata>(MD)) {
114 for (DPValue *DPV : L->getAllDPValueUsers()) {
115 if (Type == DPValue::LocationType::Any || DPV->getType() == Type)
116 DPValues->push_back(DPV);
117 }
118 }
119 };
120
121 if (auto *L = LocalAsMetadata::getIfExists(V)) {
122 AppendUsers(L);
123 for (Metadata *AL : L->getAllArgListUsers()) {
124 AppendUsers(AL);
125 if (!DPValues)
126 continue;
127 DIArgList *DI = cast<DIArgList>(AL);
128 for (DPValue *DPV : DI->getAllDPValueUsers())
129 if (Type == DPValue::LocationType::Any || DPV->getType() == Type)
130 if (EncounteredDPValues.insert(DPV).second)
131 DPValues->push_back(DPV);
132 }
133 }
134 }
135
findDbgValues(SmallVectorImpl<DbgValueInst * > & DbgValues,Value * V,SmallVectorImpl<DPValue * > * DPValues)136 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues,
137 Value *V, SmallVectorImpl<DPValue *> *DPValues) {
138 findDbgIntrinsics<DbgValueInst, DPValue::LocationType::Value>(DbgValues, V,
139 DPValues);
140 }
141
findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic * > & DbgUsers,Value * V,SmallVectorImpl<DPValue * > * DPValues)142 void llvm::findDbgUsers(SmallVectorImpl<DbgVariableIntrinsic *> &DbgUsers,
143 Value *V, SmallVectorImpl<DPValue *> *DPValues) {
144 findDbgIntrinsics<DbgVariableIntrinsic, DPValue::LocationType::Any>(
145 DbgUsers, V, DPValues);
146 }
147
getDISubprogram(const MDNode * Scope)148 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
149 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
150 return LocalScope->getSubprogram();
151 return nullptr;
152 }
153
getDebugValueLoc(DbgVariableIntrinsic * DII)154 DebugLoc llvm::getDebugValueLoc(DbgVariableIntrinsic *DII) {
155 // Original dbg.declare must have a location.
156 const DebugLoc &DeclareLoc = DII->getDebugLoc();
157 MDNode *Scope = DeclareLoc.getScope();
158 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
159 // Because no machine insts can come from debug intrinsics, only the scope
160 // and inlinedAt is significant. Zero line numbers are used in case this
161 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
162 // with the correct scope / inlinedAt fields.
163 return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
164 }
165
getDebugValueLoc(DPValue * DPV)166 DebugLoc llvm::getDebugValueLoc(DPValue *DPV) {
167 // Original dbg.declare must have a location.
168 const DebugLoc &DeclareLoc = DPV->getDebugLoc();
169 MDNode *Scope = DeclareLoc.getScope();
170 DILocation *InlinedAt = DeclareLoc.getInlinedAt();
171 // Because no machine insts can come from debug intrinsics, only the scope
172 // and inlinedAt is significant. Zero line numbers are used in case this
173 // DebugLoc leaks into any adjacent instructions. Produce an unknown location
174 // with the correct scope / inlinedAt fields.
175 return DILocation::get(DPV->getContext(), 0, 0, Scope, InlinedAt);
176 }
177
178 //===----------------------------------------------------------------------===//
179 // DebugInfoFinder implementations.
180 //===----------------------------------------------------------------------===//
181
reset()182 void DebugInfoFinder::reset() {
183 CUs.clear();
184 SPs.clear();
185 GVs.clear();
186 TYs.clear();
187 Scopes.clear();
188 NodesSeen.clear();
189 }
190
processModule(const Module & M)191 void DebugInfoFinder::processModule(const Module &M) {
192 for (auto *CU : M.debug_compile_units())
193 processCompileUnit(CU);
194 for (auto &F : M.functions()) {
195 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
196 processSubprogram(SP);
197 // There could be subprograms from inlined functions referenced from
198 // instructions only. Walk the function to find them.
199 for (const BasicBlock &BB : F)
200 for (const Instruction &I : BB)
201 processInstruction(M, I);
202 }
203 }
204
processCompileUnit(DICompileUnit * CU)205 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
206 if (!addCompileUnit(CU))
207 return;
208 for (auto *DIG : CU->getGlobalVariables()) {
209 if (!addGlobalVariable(DIG))
210 continue;
211 auto *GV = DIG->getVariable();
212 processScope(GV->getScope());
213 processType(GV->getType());
214 }
215 for (auto *ET : CU->getEnumTypes())
216 processType(ET);
217 for (auto *RT : CU->getRetainedTypes())
218 if (auto *T = dyn_cast<DIType>(RT))
219 processType(T);
220 else
221 processSubprogram(cast<DISubprogram>(RT));
222 for (auto *Import : CU->getImportedEntities()) {
223 auto *Entity = Import->getEntity();
224 if (auto *T = dyn_cast<DIType>(Entity))
225 processType(T);
226 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
227 processSubprogram(SP);
228 else if (auto *NS = dyn_cast<DINamespace>(Entity))
229 processScope(NS->getScope());
230 else if (auto *M = dyn_cast<DIModule>(Entity))
231 processScope(M->getScope());
232 }
233 }
234
processInstruction(const Module & M,const Instruction & I)235 void DebugInfoFinder::processInstruction(const Module &M,
236 const Instruction &I) {
237 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
238 processVariable(M, DVI->getVariable());
239
240 if (auto DbgLoc = I.getDebugLoc())
241 processLocation(M, DbgLoc.get());
242
243 for (const DPValue &DPV : I.getDbgValueRange())
244 processDPValue(M, DPV);
245 }
246
processLocation(const Module & M,const DILocation * Loc)247 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
248 if (!Loc)
249 return;
250 processScope(Loc->getScope());
251 processLocation(M, Loc->getInlinedAt());
252 }
253
processDPValue(const Module & M,const DPValue & DPV)254 void DebugInfoFinder::processDPValue(const Module &M, const DPValue &DPV) {
255 processVariable(M, DPV.getVariable());
256 processLocation(M, DPV.getDebugLoc().get());
257 }
258
processType(DIType * DT)259 void DebugInfoFinder::processType(DIType *DT) {
260 if (!addType(DT))
261 return;
262 processScope(DT->getScope());
263 if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
264 for (DIType *Ref : ST->getTypeArray())
265 processType(Ref);
266 return;
267 }
268 if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
269 processType(DCT->getBaseType());
270 for (Metadata *D : DCT->getElements()) {
271 if (auto *T = dyn_cast<DIType>(D))
272 processType(T);
273 else if (auto *SP = dyn_cast<DISubprogram>(D))
274 processSubprogram(SP);
275 }
276 return;
277 }
278 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
279 processType(DDT->getBaseType());
280 }
281 }
282
processScope(DIScope * Scope)283 void DebugInfoFinder::processScope(DIScope *Scope) {
284 if (!Scope)
285 return;
286 if (auto *Ty = dyn_cast<DIType>(Scope)) {
287 processType(Ty);
288 return;
289 }
290 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
291 addCompileUnit(CU);
292 return;
293 }
294 if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
295 processSubprogram(SP);
296 return;
297 }
298 if (!addScope(Scope))
299 return;
300 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
301 processScope(LB->getScope());
302 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
303 processScope(NS->getScope());
304 } else if (auto *M = dyn_cast<DIModule>(Scope)) {
305 processScope(M->getScope());
306 }
307 }
308
processSubprogram(DISubprogram * SP)309 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
310 if (!addSubprogram(SP))
311 return;
312 processScope(SP->getScope());
313 // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
314 // ValueMap containing identity mappings for all of the DICompileUnit's, not
315 // just DISubprogram's, referenced from anywhere within the Function being
316 // cloned prior to calling MapMetadata / RemapInstruction to avoid their
317 // duplication later as DICompileUnit's are also directly referenced by
318 // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
319 // Also, DICompileUnit's may reference DISubprogram's too and therefore need
320 // to be at least looked through.
321 processCompileUnit(SP->getUnit());
322 processType(SP->getType());
323 for (auto *Element : SP->getTemplateParams()) {
324 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
325 processType(TType->getType());
326 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
327 processType(TVal->getType());
328 }
329 }
330 }
331
processVariable(const Module & M,const DILocalVariable * DV)332 void DebugInfoFinder::processVariable(const Module &M,
333 const DILocalVariable *DV) {
334 if (!NodesSeen.insert(DV).second)
335 return;
336 processScope(DV->getScope());
337 processType(DV->getType());
338 }
339
addType(DIType * DT)340 bool DebugInfoFinder::addType(DIType *DT) {
341 if (!DT)
342 return false;
343
344 if (!NodesSeen.insert(DT).second)
345 return false;
346
347 TYs.push_back(const_cast<DIType *>(DT));
348 return true;
349 }
350
addCompileUnit(DICompileUnit * CU)351 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
352 if (!CU)
353 return false;
354 if (!NodesSeen.insert(CU).second)
355 return false;
356
357 CUs.push_back(CU);
358 return true;
359 }
360
addGlobalVariable(DIGlobalVariableExpression * DIG)361 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
362 if (!NodesSeen.insert(DIG).second)
363 return false;
364
365 GVs.push_back(DIG);
366 return true;
367 }
368
addSubprogram(DISubprogram * SP)369 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
370 if (!SP)
371 return false;
372
373 if (!NodesSeen.insert(SP).second)
374 return false;
375
376 SPs.push_back(SP);
377 return true;
378 }
379
addScope(DIScope * Scope)380 bool DebugInfoFinder::addScope(DIScope *Scope) {
381 if (!Scope)
382 return false;
383 // FIXME: Ocaml binding generates a scope with no content, we treat it
384 // as null for now.
385 if (Scope->getNumOperands() == 0)
386 return false;
387 if (!NodesSeen.insert(Scope).second)
388 return false;
389 Scopes.push_back(Scope);
390 return true;
391 }
392
updateLoopMetadataDebugLocationsImpl(MDNode * OrigLoopID,function_ref<Metadata * (Metadata *)> Updater)393 static MDNode *updateLoopMetadataDebugLocationsImpl(
394 MDNode *OrigLoopID, function_ref<Metadata *(Metadata *)> Updater) {
395 assert(OrigLoopID && OrigLoopID->getNumOperands() > 0 &&
396 "Loop ID needs at least one operand");
397 assert(OrigLoopID && OrigLoopID->getOperand(0).get() == OrigLoopID &&
398 "Loop ID should refer to itself");
399
400 // Save space for the self-referential LoopID.
401 SmallVector<Metadata *, 4> MDs = {nullptr};
402
403 for (unsigned i = 1; i < OrigLoopID->getNumOperands(); ++i) {
404 Metadata *MD = OrigLoopID->getOperand(i);
405 if (!MD)
406 MDs.push_back(nullptr);
407 else if (Metadata *NewMD = Updater(MD))
408 MDs.push_back(NewMD);
409 }
410
411 MDNode *NewLoopID = MDNode::getDistinct(OrigLoopID->getContext(), MDs);
412 // Insert the self-referential LoopID.
413 NewLoopID->replaceOperandWith(0, NewLoopID);
414 return NewLoopID;
415 }
416
updateLoopMetadataDebugLocations(Instruction & I,function_ref<Metadata * (Metadata *)> Updater)417 void llvm::updateLoopMetadataDebugLocations(
418 Instruction &I, function_ref<Metadata *(Metadata *)> Updater) {
419 MDNode *OrigLoopID = I.getMetadata(LLVMContext::MD_loop);
420 if (!OrigLoopID)
421 return;
422 MDNode *NewLoopID = updateLoopMetadataDebugLocationsImpl(OrigLoopID, Updater);
423 I.setMetadata(LLVMContext::MD_loop, NewLoopID);
424 }
425
426 /// Return true if a node is a DILocation or if a DILocation is
427 /// indirectly referenced by one of the node's children.
isDILocationReachable(SmallPtrSetImpl<Metadata * > & Visited,SmallPtrSetImpl<Metadata * > & Reachable,Metadata * MD)428 static bool isDILocationReachable(SmallPtrSetImpl<Metadata *> &Visited,
429 SmallPtrSetImpl<Metadata *> &Reachable,
430 Metadata *MD) {
431 MDNode *N = dyn_cast_or_null<MDNode>(MD);
432 if (!N)
433 return false;
434 if (isa<DILocation>(N) || Reachable.count(N))
435 return true;
436 if (!Visited.insert(N).second)
437 return false;
438 for (auto &OpIt : N->operands()) {
439 Metadata *Op = OpIt.get();
440 if (isDILocationReachable(Visited, Reachable, Op)) {
441 // Don't return just yet as we want to visit all MD's children to
442 // initialize DILocationReachable in stripDebugLocFromLoopID
443 Reachable.insert(N);
444 }
445 }
446 return Reachable.count(N);
447 }
448
isAllDILocation(SmallPtrSetImpl<Metadata * > & Visited,SmallPtrSetImpl<Metadata * > & AllDILocation,const SmallPtrSetImpl<Metadata * > & DIReachable,Metadata * MD)449 static bool isAllDILocation(SmallPtrSetImpl<Metadata *> &Visited,
450 SmallPtrSetImpl<Metadata *> &AllDILocation,
451 const SmallPtrSetImpl<Metadata *> &DIReachable,
452 Metadata *MD) {
453 MDNode *N = dyn_cast_or_null<MDNode>(MD);
454 if (!N)
455 return false;
456 if (isa<DILocation>(N) || AllDILocation.count(N))
457 return true;
458 if (!DIReachable.count(N))
459 return false;
460 if (!Visited.insert(N).second)
461 return false;
462 for (auto &OpIt : N->operands()) {
463 Metadata *Op = OpIt.get();
464 if (Op == MD)
465 continue;
466 if (!isAllDILocation(Visited, AllDILocation, DIReachable, Op)) {
467 return false;
468 }
469 }
470 AllDILocation.insert(N);
471 return true;
472 }
473
474 static Metadata *
stripLoopMDLoc(const SmallPtrSetImpl<Metadata * > & AllDILocation,const SmallPtrSetImpl<Metadata * > & DIReachable,Metadata * MD)475 stripLoopMDLoc(const SmallPtrSetImpl<Metadata *> &AllDILocation,
476 const SmallPtrSetImpl<Metadata *> &DIReachable, Metadata *MD) {
477 if (isa<DILocation>(MD) || AllDILocation.count(MD))
478 return nullptr;
479
480 if (!DIReachable.count(MD))
481 return MD;
482
483 MDNode *N = dyn_cast_or_null<MDNode>(MD);
484 if (!N)
485 return MD;
486
487 SmallVector<Metadata *, 4> Args;
488 bool HasSelfRef = false;
489 for (unsigned i = 0; i < N->getNumOperands(); ++i) {
490 Metadata *A = N->getOperand(i);
491 if (!A) {
492 Args.push_back(nullptr);
493 } else if (A == MD) {
494 assert(i == 0 && "expected i==0 for self-reference");
495 HasSelfRef = true;
496 Args.push_back(nullptr);
497 } else if (Metadata *NewArg =
498 stripLoopMDLoc(AllDILocation, DIReachable, A)) {
499 Args.push_back(NewArg);
500 }
501 }
502 if (Args.empty() || (HasSelfRef && Args.size() == 1))
503 return nullptr;
504
505 MDNode *NewMD = N->isDistinct() ? MDNode::getDistinct(N->getContext(), Args)
506 : MDNode::get(N->getContext(), Args);
507 if (HasSelfRef)
508 NewMD->replaceOperandWith(0, NewMD);
509 return NewMD;
510 }
511
stripDebugLocFromLoopID(MDNode * N)512 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
513 assert(!N->operands().empty() && "Missing self reference?");
514 SmallPtrSet<Metadata *, 8> Visited, DILocationReachable, AllDILocation;
515 // If we already visited N, there is nothing to do.
516 if (!Visited.insert(N).second)
517 return N;
518
519 // If there is no debug location, we do not have to rewrite this
520 // MDNode. This loop also initializes DILocationReachable, later
521 // needed by updateLoopMetadataDebugLocationsImpl; the use of
522 // count_if avoids an early exit.
523 if (!llvm::count_if(llvm::drop_begin(N->operands()),
524 [&Visited, &DILocationReachable](const MDOperand &Op) {
525 return isDILocationReachable(
526 Visited, DILocationReachable, Op.get());
527 }))
528 return N;
529
530 Visited.clear();
531 // If there is only the debug location without any actual loop metadata, we
532 // can remove the metadata.
533 if (llvm::all_of(llvm::drop_begin(N->operands()),
534 [&Visited, &AllDILocation,
535 &DILocationReachable](const MDOperand &Op) {
536 return isAllDILocation(Visited, AllDILocation,
537 DILocationReachable, Op.get());
538 }))
539 return nullptr;
540
541 return updateLoopMetadataDebugLocationsImpl(
542 N, [&AllDILocation, &DILocationReachable](Metadata *MD) -> Metadata * {
543 return stripLoopMDLoc(AllDILocation, DILocationReachable, MD);
544 });
545 }
546
stripDebugInfo(Function & F)547 bool llvm::stripDebugInfo(Function &F) {
548 bool Changed = false;
549 if (F.hasMetadata(LLVMContext::MD_dbg)) {
550 Changed = true;
551 F.setSubprogram(nullptr);
552 }
553
554 DenseMap<MDNode *, MDNode *> LoopIDsMap;
555 for (BasicBlock &BB : F) {
556 for (Instruction &I : llvm::make_early_inc_range(BB)) {
557 if (isa<DbgInfoIntrinsic>(&I)) {
558 I.eraseFromParent();
559 Changed = true;
560 continue;
561 }
562 if (I.getDebugLoc()) {
563 Changed = true;
564 I.setDebugLoc(DebugLoc());
565 }
566 if (auto *LoopID = I.getMetadata(LLVMContext::MD_loop)) {
567 auto *NewLoopID = LoopIDsMap.lookup(LoopID);
568 if (!NewLoopID)
569 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
570 if (NewLoopID != LoopID)
571 I.setMetadata(LLVMContext::MD_loop, NewLoopID);
572 }
573 // Strip other attachments that are or use debug info.
574 if (I.hasMetadataOtherThanDebugLoc()) {
575 // Heapallocsites point into the DIType system.
576 I.setMetadata("heapallocsite", nullptr);
577 // DIAssignID are debug info metadata primitives.
578 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
579 }
580 I.dropDbgValues();
581 }
582 }
583 return Changed;
584 }
585
StripDebugInfo(Module & M)586 bool llvm::StripDebugInfo(Module &M) {
587 bool Changed = false;
588
589 for (NamedMDNode &NMD : llvm::make_early_inc_range(M.named_metadata())) {
590 // We're stripping debug info, and without them, coverage information
591 // doesn't quite make sense.
592 if (NMD.getName().starts_with("llvm.dbg.") ||
593 NMD.getName() == "llvm.gcov") {
594 NMD.eraseFromParent();
595 Changed = true;
596 }
597 }
598
599 for (Function &F : M)
600 Changed |= stripDebugInfo(F);
601
602 for (auto &GV : M.globals()) {
603 Changed |= GV.eraseMetadata(LLVMContext::MD_dbg);
604 }
605
606 if (GVMaterializer *Materializer = M.getMaterializer())
607 Materializer->setStripDebugInfo();
608
609 return Changed;
610 }
611
612 namespace {
613
614 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
615 class DebugTypeInfoRemoval {
616 DenseMap<Metadata *, Metadata *> Replacements;
617
618 public:
619 /// The (void)() type.
620 MDNode *EmptySubroutineType;
621
622 private:
623 /// Remember what linkage name we originally had before stripping. If we end
624 /// up making two subprograms identical who originally had different linkage
625 /// names, then we need to make one of them distinct, to avoid them getting
626 /// uniqued. Maps the new node to the old linkage name.
627 DenseMap<DISubprogram *, StringRef> NewToLinkageName;
628
629 // TODO: Remember the distinct subprogram we created for a given linkage name,
630 // so that we can continue to unique whenever possible. Map <newly created
631 // node, old linkage name> to the first (possibly distinct) mdsubprogram
632 // created for that combination. This is not strictly needed for correctness,
633 // but can cut down on the number of MDNodes and let us diff cleanly with the
634 // output of -gline-tables-only.
635
636 public:
DebugTypeInfoRemoval(LLVMContext & C)637 DebugTypeInfoRemoval(LLVMContext &C)
638 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
639 MDNode::get(C, {}))) {}
640
map(Metadata * M)641 Metadata *map(Metadata *M) {
642 if (!M)
643 return nullptr;
644 auto Replacement = Replacements.find(M);
645 if (Replacement != Replacements.end())
646 return Replacement->second;
647
648 return M;
649 }
mapNode(Metadata * N)650 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
651
652 /// Recursively remap N and all its referenced children. Does a DF post-order
653 /// traversal, so as to remap bottoms up.
traverseAndRemap(MDNode * N)654 void traverseAndRemap(MDNode *N) { traverse(N); }
655
656 private:
657 // Create a new DISubprogram, to replace the one given.
getReplacementSubprogram(DISubprogram * MDS)658 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
659 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
660 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
661 DISubprogram *Declaration = nullptr;
662 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
663 DIType *ContainingType =
664 cast_or_null<DIType>(map(MDS->getContainingType()));
665 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
666 auto Variables = nullptr;
667 auto TemplateParams = nullptr;
668
669 // Make a distinct DISubprogram, for situations that warrent it.
670 auto distinctMDSubprogram = [&]() {
671 return DISubprogram::getDistinct(
672 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
673 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(),
674 ContainingType, MDS->getVirtualIndex(), MDS->getThisAdjustment(),
675 MDS->getFlags(), MDS->getSPFlags(), Unit, TemplateParams, Declaration,
676 Variables);
677 };
678
679 if (MDS->isDistinct())
680 return distinctMDSubprogram();
681
682 auto *NewMDS = DISubprogram::get(
683 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
684 FileAndScope, MDS->getLine(), Type, MDS->getScopeLine(), ContainingType,
685 MDS->getVirtualIndex(), MDS->getThisAdjustment(), MDS->getFlags(),
686 MDS->getSPFlags(), Unit, TemplateParams, Declaration, Variables);
687
688 StringRef OldLinkageName = MDS->getLinkageName();
689
690 // See if we need to make a distinct one.
691 auto OrigLinkage = NewToLinkageName.find(NewMDS);
692 if (OrigLinkage != NewToLinkageName.end()) {
693 if (OrigLinkage->second == OldLinkageName)
694 // We're good.
695 return NewMDS;
696
697 // Otherwise, need to make a distinct one.
698 // TODO: Query the map to see if we already have one.
699 return distinctMDSubprogram();
700 }
701
702 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
703 return NewMDS;
704 }
705
706 /// Create a new compile unit, to replace the one given
getReplacementCU(DICompileUnit * CU)707 DICompileUnit *getReplacementCU(DICompileUnit *CU) {
708 // Drop skeleton CUs.
709 if (CU->getDWOId())
710 return nullptr;
711
712 auto *File = cast_or_null<DIFile>(map(CU->getFile()));
713 MDTuple *EnumTypes = nullptr;
714 MDTuple *RetainedTypes = nullptr;
715 MDTuple *GlobalVariables = nullptr;
716 MDTuple *ImportedEntities = nullptr;
717 return DICompileUnit::getDistinct(
718 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
719 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
720 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
721 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
722 CU->getDWOId(), CU->getSplitDebugInlining(),
723 CU->getDebugInfoForProfiling(), CU->getNameTableKind(),
724 CU->getRangesBaseAddress(), CU->getSysRoot(), CU->getSDK());
725 }
726
getReplacementMDLocation(DILocation * MLD)727 DILocation *getReplacementMDLocation(DILocation *MLD) {
728 auto *Scope = map(MLD->getScope());
729 auto *InlinedAt = map(MLD->getInlinedAt());
730 if (MLD->isDistinct())
731 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
732 MLD->getColumn(), Scope, InlinedAt);
733 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
734 Scope, InlinedAt);
735 }
736
737 /// Create a new generic MDNode, to replace the one given
getReplacementMDNode(MDNode * N)738 MDNode *getReplacementMDNode(MDNode *N) {
739 SmallVector<Metadata *, 8> Ops;
740 Ops.reserve(N->getNumOperands());
741 for (auto &I : N->operands())
742 if (I)
743 Ops.push_back(map(I));
744 auto *Ret = MDNode::get(N->getContext(), Ops);
745 return Ret;
746 }
747
748 /// Attempt to re-map N to a newly created node.
remap(MDNode * N)749 void remap(MDNode *N) {
750 if (Replacements.count(N))
751 return;
752
753 auto doRemap = [&](MDNode *N) -> MDNode * {
754 if (!N)
755 return nullptr;
756 if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
757 remap(MDSub->getUnit());
758 return getReplacementSubprogram(MDSub);
759 }
760 if (isa<DISubroutineType>(N))
761 return EmptySubroutineType;
762 if (auto *CU = dyn_cast<DICompileUnit>(N))
763 return getReplacementCU(CU);
764 if (isa<DIFile>(N))
765 return N;
766 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
767 // Remap to our referenced scope (recursively).
768 return mapNode(MDLB->getScope());
769 if (auto *MLD = dyn_cast<DILocation>(N))
770 return getReplacementMDLocation(MLD);
771
772 // Otherwise, if we see these, just drop them now. Not strictly necessary,
773 // but this speeds things up a little.
774 if (isa<DINode>(N))
775 return nullptr;
776
777 return getReplacementMDNode(N);
778 };
779 Replacements[N] = doRemap(N);
780 }
781
782 /// Do the remapping traversal.
783 void traverse(MDNode *);
784 };
785
786 } // end anonymous namespace
787
traverse(MDNode * N)788 void DebugTypeInfoRemoval::traverse(MDNode *N) {
789 if (!N || Replacements.count(N))
790 return;
791
792 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
793 // parts of the graph.
794 auto prune = [](MDNode *Parent, MDNode *Child) {
795 if (auto *MDS = dyn_cast<DISubprogram>(Parent))
796 return Child == MDS->getRetainedNodes().get();
797 return false;
798 };
799
800 SmallVector<MDNode *, 16> ToVisit;
801 DenseSet<MDNode *> Opened;
802
803 // Visit each node starting at N in post order, and map them.
804 ToVisit.push_back(N);
805 while (!ToVisit.empty()) {
806 auto *N = ToVisit.back();
807 if (!Opened.insert(N).second) {
808 // Close it.
809 remap(N);
810 ToVisit.pop_back();
811 continue;
812 }
813 for (auto &I : N->operands())
814 if (auto *MDN = dyn_cast_or_null<MDNode>(I))
815 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
816 !isa<DICompileUnit>(MDN))
817 ToVisit.push_back(MDN);
818 }
819 }
820
stripNonLineTableDebugInfo(Module & M)821 bool llvm::stripNonLineTableDebugInfo(Module &M) {
822 bool Changed = false;
823
824 // First off, delete the debug intrinsics.
825 auto RemoveUses = [&](StringRef Name) {
826 if (auto *DbgVal = M.getFunction(Name)) {
827 while (!DbgVal->use_empty())
828 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
829 DbgVal->eraseFromParent();
830 Changed = true;
831 }
832 };
833 RemoveUses("llvm.dbg.declare");
834 RemoveUses("llvm.dbg.label");
835 RemoveUses("llvm.dbg.value");
836
837 // Delete non-CU debug info named metadata nodes.
838 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
839 NMI != NME;) {
840 NamedMDNode *NMD = &*NMI;
841 ++NMI;
842 // Specifically keep dbg.cu around.
843 if (NMD->getName() == "llvm.dbg.cu")
844 continue;
845 }
846
847 // Drop all dbg attachments from global variables.
848 for (auto &GV : M.globals())
849 GV.eraseMetadata(LLVMContext::MD_dbg);
850
851 DebugTypeInfoRemoval Mapper(M.getContext());
852 auto remap = [&](MDNode *Node) -> MDNode * {
853 if (!Node)
854 return nullptr;
855 Mapper.traverseAndRemap(Node);
856 auto *NewNode = Mapper.mapNode(Node);
857 Changed |= Node != NewNode;
858 Node = NewNode;
859 return NewNode;
860 };
861
862 // Rewrite the DebugLocs to be equivalent to what
863 // -gline-tables-only would have created.
864 for (auto &F : M) {
865 if (auto *SP = F.getSubprogram()) {
866 Mapper.traverseAndRemap(SP);
867 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
868 Changed |= SP != NewSP;
869 F.setSubprogram(NewSP);
870 }
871 for (auto &BB : F) {
872 for (auto &I : BB) {
873 auto remapDebugLoc = [&](const DebugLoc &DL) -> DebugLoc {
874 auto *Scope = DL.getScope();
875 MDNode *InlinedAt = DL.getInlinedAt();
876 Scope = remap(Scope);
877 InlinedAt = remap(InlinedAt);
878 return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
879 Scope, InlinedAt);
880 };
881
882 if (I.getDebugLoc() != DebugLoc())
883 I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
884
885 // Remap DILocations in llvm.loop attachments.
886 updateLoopMetadataDebugLocations(I, [&](Metadata *MD) -> Metadata * {
887 if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
888 return remapDebugLoc(Loc).get();
889 return MD;
890 });
891
892 // Strip heapallocsite attachments, they point into the DIType system.
893 if (I.hasMetadataOtherThanDebugLoc())
894 I.setMetadata("heapallocsite", nullptr);
895
896 // Strip any DPValues attached.
897 I.dropDbgValues();
898 }
899 }
900 }
901
902 // Create a new llvm.dbg.cu, which is equivalent to the one
903 // -gline-tables-only would have created.
904 for (auto &NMD : M.named_metadata()) {
905 SmallVector<MDNode *, 8> Ops;
906 for (MDNode *Op : NMD.operands())
907 Ops.push_back(remap(Op));
908
909 if (!Changed)
910 continue;
911
912 NMD.clearOperands();
913 for (auto *Op : Ops)
914 if (Op)
915 NMD.addOperand(Op);
916 }
917 return Changed;
918 }
919
getDebugMetadataVersionFromModule(const Module & M)920 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
921 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
922 M.getModuleFlag("Debug Info Version")))
923 return Val->getZExtValue();
924 return 0;
925 }
926
applyMergedLocation(DILocation * LocA,DILocation * LocB)927 void Instruction::applyMergedLocation(DILocation *LocA, DILocation *LocB) {
928 setDebugLoc(DILocation::getMergedLocation(LocA, LocB));
929 }
930
mergeDIAssignID(ArrayRef<const Instruction * > SourceInstructions)931 void Instruction::mergeDIAssignID(
932 ArrayRef<const Instruction *> SourceInstructions) {
933 // Replace all uses (and attachments) of all the DIAssignIDs
934 // on SourceInstructions with a single merged value.
935 assert(getFunction() && "Uninserted instruction merged");
936 // Collect up the DIAssignID tags.
937 SmallVector<DIAssignID *, 4> IDs;
938 for (const Instruction *I : SourceInstructions) {
939 if (auto *MD = I->getMetadata(LLVMContext::MD_DIAssignID))
940 IDs.push_back(cast<DIAssignID>(MD));
941 assert(getFunction() == I->getFunction() &&
942 "Merging with instruction from another function not allowed");
943 }
944
945 // Add this instruction's DIAssignID too, if it has one.
946 if (auto *MD = getMetadata(LLVMContext::MD_DIAssignID))
947 IDs.push_back(cast<DIAssignID>(MD));
948
949 if (IDs.empty())
950 return; // No DIAssignID tags to process.
951
952 DIAssignID *MergeID = IDs[0];
953 for (auto It = std::next(IDs.begin()), End = IDs.end(); It != End; ++It) {
954 if (*It != MergeID)
955 at::RAUW(*It, MergeID);
956 }
957 setMetadata(LLVMContext::MD_DIAssignID, MergeID);
958 }
959
updateLocationAfterHoist()960 void Instruction::updateLocationAfterHoist() { dropLocation(); }
961
dropLocation()962 void Instruction::dropLocation() {
963 const DebugLoc &DL = getDebugLoc();
964 if (!DL)
965 return;
966
967 // If this isn't a call, drop the location to allow a location from a
968 // preceding instruction to propagate.
969 bool MayLowerToCall = false;
970 if (isa<CallBase>(this)) {
971 auto *II = dyn_cast<IntrinsicInst>(this);
972 MayLowerToCall =
973 !II || IntrinsicInst::mayLowerToFunctionCall(II->getIntrinsicID());
974 }
975
976 if (!MayLowerToCall) {
977 setDebugLoc(DebugLoc());
978 return;
979 }
980
981 // Set a line 0 location for calls to preserve scope information in case
982 // inlining occurs.
983 DISubprogram *SP = getFunction()->getSubprogram();
984 if (SP)
985 // If a function scope is available, set it on the line 0 location. When
986 // hoisting a call to a predecessor block, using the function scope avoids
987 // making it look like the callee was reached earlier than it should be.
988 setDebugLoc(DILocation::get(getContext(), 0, 0, SP));
989 else
990 // The parent function has no scope. Go ahead and drop the location. If
991 // the parent function is inlined, and the callee has a subprogram, the
992 // inliner will attach a location to the call.
993 //
994 // One alternative is to set a line 0 location with the existing scope and
995 // inlinedAt info. The location might be sensitive to when inlining occurs.
996 setDebugLoc(DebugLoc());
997 }
998
999 //===----------------------------------------------------------------------===//
1000 // LLVM C API implementations.
1001 //===----------------------------------------------------------------------===//
1002
map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang)1003 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
1004 switch (lang) {
1005 #define HANDLE_DW_LANG(ID, NAME, LOWER_BOUND, VERSION, VENDOR) \
1006 case LLVMDWARFSourceLanguage##NAME: \
1007 return ID;
1008 #include "llvm/BinaryFormat/Dwarf.def"
1009 #undef HANDLE_DW_LANG
1010 }
1011 llvm_unreachable("Unhandled Tag");
1012 }
1013
unwrapDI(LLVMMetadataRef Ref)1014 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
1015 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
1016 }
1017
map_from_llvmDIFlags(LLVMDIFlags Flags)1018 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
1019 return static_cast<DINode::DIFlags>(Flags);
1020 }
1021
map_to_llvmDIFlags(DINode::DIFlags Flags)1022 static LLVMDIFlags map_to_llvmDIFlags(DINode::DIFlags Flags) {
1023 return static_cast<LLVMDIFlags>(Flags);
1024 }
1025
1026 static DISubprogram::DISPFlags
pack_into_DISPFlags(bool IsLocalToUnit,bool IsDefinition,bool IsOptimized)1027 pack_into_DISPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized) {
1028 return DISubprogram::toSPFlags(IsLocalToUnit, IsDefinition, IsOptimized);
1029 }
1030
LLVMDebugMetadataVersion()1031 unsigned LLVMDebugMetadataVersion() {
1032 return DEBUG_METADATA_VERSION;
1033 }
1034
LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M)1035 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
1036 return wrap(new DIBuilder(*unwrap(M), false));
1037 }
1038
LLVMCreateDIBuilder(LLVMModuleRef M)1039 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
1040 return wrap(new DIBuilder(*unwrap(M)));
1041 }
1042
LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M)1043 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
1044 return getDebugMetadataVersionFromModule(*unwrap(M));
1045 }
1046
LLVMStripModuleDebugInfo(LLVMModuleRef M)1047 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
1048 return StripDebugInfo(*unwrap(M));
1049 }
1050
LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder)1051 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
1052 delete unwrap(Builder);
1053 }
1054
LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder)1055 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
1056 unwrap(Builder)->finalize();
1057 }
1058
LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,LLVMMetadataRef subprogram)1059 void LLVMDIBuilderFinalizeSubprogram(LLVMDIBuilderRef Builder,
1060 LLVMMetadataRef subprogram) {
1061 unwrap(Builder)->finalizeSubprogram(unwrapDI<DISubprogram>(subprogram));
1062 }
1063
LLVMDIBuilderCreateCompileUnit(LLVMDIBuilderRef Builder,LLVMDWARFSourceLanguage Lang,LLVMMetadataRef FileRef,const char * Producer,size_t ProducerLen,LLVMBool isOptimized,const char * Flags,size_t FlagsLen,unsigned RuntimeVer,const char * SplitName,size_t SplitNameLen,LLVMDWARFEmissionKind Kind,unsigned DWOId,LLVMBool SplitDebugInlining,LLVMBool DebugInfoForProfiling,const char * SysRoot,size_t SysRootLen,const char * SDK,size_t SDKLen)1064 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
1065 LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
1066 LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
1067 LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
1068 unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
1069 LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
1070 LLVMBool DebugInfoForProfiling, const char *SysRoot, size_t SysRootLen,
1071 const char *SDK, size_t SDKLen) {
1072 auto File = unwrapDI<DIFile>(FileRef);
1073
1074 return wrap(unwrap(Builder)->createCompileUnit(
1075 map_from_llvmDWARFsourcelanguage(Lang), File,
1076 StringRef(Producer, ProducerLen), isOptimized, StringRef(Flags, FlagsLen),
1077 RuntimeVer, StringRef(SplitName, SplitNameLen),
1078 static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
1079 SplitDebugInlining, DebugInfoForProfiling,
1080 DICompileUnit::DebugNameTableKind::Default, false,
1081 StringRef(SysRoot, SysRootLen), StringRef(SDK, SDKLen)));
1082 }
1083
1084 LLVMMetadataRef
LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder,const char * Filename,size_t FilenameLen,const char * Directory,size_t DirectoryLen)1085 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
1086 size_t FilenameLen, const char *Directory,
1087 size_t DirectoryLen) {
1088 return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
1089 StringRef(Directory, DirectoryLen)));
1090 }
1091
1092 LLVMMetadataRef
LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentScope,const char * Name,size_t NameLen,const char * ConfigMacros,size_t ConfigMacrosLen,const char * IncludePath,size_t IncludePathLen,const char * APINotesFile,size_t APINotesFileLen)1093 LLVMDIBuilderCreateModule(LLVMDIBuilderRef Builder, LLVMMetadataRef ParentScope,
1094 const char *Name, size_t NameLen,
1095 const char *ConfigMacros, size_t ConfigMacrosLen,
1096 const char *IncludePath, size_t IncludePathLen,
1097 const char *APINotesFile, size_t APINotesFileLen) {
1098 return wrap(unwrap(Builder)->createModule(
1099 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen),
1100 StringRef(ConfigMacros, ConfigMacrosLen),
1101 StringRef(IncludePath, IncludePathLen),
1102 StringRef(APINotesFile, APINotesFileLen)));
1103 }
1104
LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentScope,const char * Name,size_t NameLen,LLVMBool ExportSymbols)1105 LLVMMetadataRef LLVMDIBuilderCreateNameSpace(LLVMDIBuilderRef Builder,
1106 LLVMMetadataRef ParentScope,
1107 const char *Name, size_t NameLen,
1108 LLVMBool ExportSymbols) {
1109 return wrap(unwrap(Builder)->createNameSpace(
1110 unwrapDI<DIScope>(ParentScope), StringRef(Name, NameLen), ExportSymbols));
1111 }
1112
LLVMDIBuilderCreateFunction(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,const char * LinkageName,size_t LinkageNameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool IsLocalToUnit,LLVMBool IsDefinition,unsigned ScopeLine,LLVMDIFlags Flags,LLVMBool IsOptimized)1113 LLVMMetadataRef LLVMDIBuilderCreateFunction(
1114 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1115 size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
1116 LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1117 LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
1118 unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
1119 return wrap(unwrap(Builder)->createFunction(
1120 unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
1121 unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine,
1122 map_from_llvmDIFlags(Flags),
1123 pack_into_DISPFlags(IsLocalToUnit, IsDefinition, IsOptimized), nullptr,
1124 nullptr, nullptr));
1125 }
1126
1127
LLVMDIBuilderCreateLexicalBlock(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned Col)1128 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
1129 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1130 LLVMMetadataRef File, unsigned Line, unsigned Col) {
1131 return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
1132 unwrapDI<DIFile>(File),
1133 Line, Col));
1134 }
1135
1136 LLVMMetadataRef
LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Discriminator)1137 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
1138 LLVMMetadataRef Scope,
1139 LLVMMetadataRef File,
1140 unsigned Discriminator) {
1141 return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
1142 unwrapDI<DIFile>(File),
1143 Discriminator));
1144 }
1145
1146 LLVMMetadataRef
LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef NS,LLVMMetadataRef File,unsigned Line)1147 LLVMDIBuilderCreateImportedModuleFromNamespace(LLVMDIBuilderRef Builder,
1148 LLVMMetadataRef Scope,
1149 LLVMMetadataRef NS,
1150 LLVMMetadataRef File,
1151 unsigned Line) {
1152 return wrap(unwrap(Builder)->createImportedModule(unwrapDI<DIScope>(Scope),
1153 unwrapDI<DINamespace>(NS),
1154 unwrapDI<DIFile>(File),
1155 Line));
1156 }
1157
LLVMDIBuilderCreateImportedModuleFromAlias(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef ImportedEntity,LLVMMetadataRef File,unsigned Line,LLVMMetadataRef * Elements,unsigned NumElements)1158 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromAlias(
1159 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
1160 LLVMMetadataRef ImportedEntity, LLVMMetadataRef File, unsigned Line,
1161 LLVMMetadataRef *Elements, unsigned NumElements) {
1162 auto Elts =
1163 (NumElements > 0)
1164 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1165 : nullptr;
1166 return wrap(unwrap(Builder)->createImportedModule(
1167 unwrapDI<DIScope>(Scope), unwrapDI<DIImportedEntity>(ImportedEntity),
1168 unwrapDI<DIFile>(File), Line, Elts));
1169 }
1170
LLVMDIBuilderCreateImportedModuleFromModule(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef M,LLVMMetadataRef File,unsigned Line,LLVMMetadataRef * Elements,unsigned NumElements)1171 LLVMMetadataRef LLVMDIBuilderCreateImportedModuleFromModule(
1172 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef M,
1173 LLVMMetadataRef File, unsigned Line, LLVMMetadataRef *Elements,
1174 unsigned NumElements) {
1175 auto Elts =
1176 (NumElements > 0)
1177 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1178 : nullptr;
1179 return wrap(unwrap(Builder)->createImportedModule(
1180 unwrapDI<DIScope>(Scope), unwrapDI<DIModule>(M), unwrapDI<DIFile>(File),
1181 Line, Elts));
1182 }
1183
LLVMDIBuilderCreateImportedDeclaration(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,LLVMMetadataRef Decl,LLVMMetadataRef File,unsigned Line,const char * Name,size_t NameLen,LLVMMetadataRef * Elements,unsigned NumElements)1184 LLVMMetadataRef LLVMDIBuilderCreateImportedDeclaration(
1185 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef Decl,
1186 LLVMMetadataRef File, unsigned Line, const char *Name, size_t NameLen,
1187 LLVMMetadataRef *Elements, unsigned NumElements) {
1188 auto Elts =
1189 (NumElements > 0)
1190 ? unwrap(Builder)->getOrCreateArray({unwrap(Elements), NumElements})
1191 : nullptr;
1192 return wrap(unwrap(Builder)->createImportedDeclaration(
1193 unwrapDI<DIScope>(Scope), unwrapDI<DINode>(Decl), unwrapDI<DIFile>(File),
1194 Line, {Name, NameLen}, Elts));
1195 }
1196
1197 LLVMMetadataRef
LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx,unsigned Line,unsigned Column,LLVMMetadataRef Scope,LLVMMetadataRef InlinedAt)1198 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
1199 unsigned Column, LLVMMetadataRef Scope,
1200 LLVMMetadataRef InlinedAt) {
1201 return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
1202 unwrap(InlinedAt)));
1203 }
1204
LLVMDILocationGetLine(LLVMMetadataRef Location)1205 unsigned LLVMDILocationGetLine(LLVMMetadataRef Location) {
1206 return unwrapDI<DILocation>(Location)->getLine();
1207 }
1208
LLVMDILocationGetColumn(LLVMMetadataRef Location)1209 unsigned LLVMDILocationGetColumn(LLVMMetadataRef Location) {
1210 return unwrapDI<DILocation>(Location)->getColumn();
1211 }
1212
LLVMDILocationGetScope(LLVMMetadataRef Location)1213 LLVMMetadataRef LLVMDILocationGetScope(LLVMMetadataRef Location) {
1214 return wrap(unwrapDI<DILocation>(Location)->getScope());
1215 }
1216
LLVMDILocationGetInlinedAt(LLVMMetadataRef Location)1217 LLVMMetadataRef LLVMDILocationGetInlinedAt(LLVMMetadataRef Location) {
1218 return wrap(unwrapDI<DILocation>(Location)->getInlinedAt());
1219 }
1220
LLVMDIScopeGetFile(LLVMMetadataRef Scope)1221 LLVMMetadataRef LLVMDIScopeGetFile(LLVMMetadataRef Scope) {
1222 return wrap(unwrapDI<DIScope>(Scope)->getFile());
1223 }
1224
LLVMDIFileGetDirectory(LLVMMetadataRef File,unsigned * Len)1225 const char *LLVMDIFileGetDirectory(LLVMMetadataRef File, unsigned *Len) {
1226 auto Dir = unwrapDI<DIFile>(File)->getDirectory();
1227 *Len = Dir.size();
1228 return Dir.data();
1229 }
1230
LLVMDIFileGetFilename(LLVMMetadataRef File,unsigned * Len)1231 const char *LLVMDIFileGetFilename(LLVMMetadataRef File, unsigned *Len) {
1232 auto Name = unwrapDI<DIFile>(File)->getFilename();
1233 *Len = Name.size();
1234 return Name.data();
1235 }
1236
LLVMDIFileGetSource(LLVMMetadataRef File,unsigned * Len)1237 const char *LLVMDIFileGetSource(LLVMMetadataRef File, unsigned *Len) {
1238 if (auto Src = unwrapDI<DIFile>(File)->getSource()) {
1239 *Len = Src->size();
1240 return Src->data();
1241 }
1242 *Len = 0;
1243 return "";
1244 }
1245
LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentMacroFile,unsigned Line,LLVMDWARFMacinfoRecordType RecordType,const char * Name,size_t NameLen,const char * Value,size_t ValueLen)1246 LLVMMetadataRef LLVMDIBuilderCreateMacro(LLVMDIBuilderRef Builder,
1247 LLVMMetadataRef ParentMacroFile,
1248 unsigned Line,
1249 LLVMDWARFMacinfoRecordType RecordType,
1250 const char *Name, size_t NameLen,
1251 const char *Value, size_t ValueLen) {
1252 return wrap(
1253 unwrap(Builder)->createMacro(unwrapDI<DIMacroFile>(ParentMacroFile), Line,
1254 static_cast<MacinfoRecordType>(RecordType),
1255 {Name, NameLen}, {Value, ValueLen}));
1256 }
1257
1258 LLVMMetadataRef
LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,LLVMMetadataRef ParentMacroFile,unsigned Line,LLVMMetadataRef File)1259 LLVMDIBuilderCreateTempMacroFile(LLVMDIBuilderRef Builder,
1260 LLVMMetadataRef ParentMacroFile, unsigned Line,
1261 LLVMMetadataRef File) {
1262 return wrap(unwrap(Builder)->createTempMacroFile(
1263 unwrapDI<DIMacroFile>(ParentMacroFile), Line, unwrapDI<DIFile>(File)));
1264 }
1265
LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,int64_t Value,LLVMBool IsUnsigned)1266 LLVMMetadataRef LLVMDIBuilderCreateEnumerator(LLVMDIBuilderRef Builder,
1267 const char *Name, size_t NameLen,
1268 int64_t Value,
1269 LLVMBool IsUnsigned) {
1270 return wrap(unwrap(Builder)->createEnumerator({Name, NameLen}, Value,
1271 IsUnsigned != 0));
1272 }
1273
LLVMDIBuilderCreateEnumerationType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,LLVMMetadataRef * Elements,unsigned NumElements,LLVMMetadataRef ClassTy)1274 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
1275 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1276 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1277 uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef *Elements,
1278 unsigned NumElements, LLVMMetadataRef ClassTy) {
1279 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1280 NumElements});
1281 return wrap(unwrap(Builder)->createEnumerationType(
1282 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1283 LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
1284 }
1285
LLVMDIBuilderCreateUnionType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags,LLVMMetadataRef * Elements,unsigned NumElements,unsigned RunTimeLang,const char * UniqueId,size_t UniqueIdLen)1286 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
1287 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1288 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1289 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1290 LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
1291 const char *UniqueId, size_t UniqueIdLen) {
1292 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1293 NumElements});
1294 return wrap(unwrap(Builder)->createUnionType(
1295 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1296 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1297 Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
1298 }
1299
1300
1301 LLVMMetadataRef
LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder,uint64_t Size,uint32_t AlignInBits,LLVMMetadataRef Ty,LLVMMetadataRef * Subscripts,unsigned NumSubscripts)1302 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, uint64_t Size,
1303 uint32_t AlignInBits, LLVMMetadataRef Ty,
1304 LLVMMetadataRef *Subscripts,
1305 unsigned NumSubscripts) {
1306 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1307 NumSubscripts});
1308 return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
1309 unwrapDI<DIType>(Ty), Subs));
1310 }
1311
1312 LLVMMetadataRef
LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder,uint64_t Size,uint32_t AlignInBits,LLVMMetadataRef Ty,LLVMMetadataRef * Subscripts,unsigned NumSubscripts)1313 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, uint64_t Size,
1314 uint32_t AlignInBits, LLVMMetadataRef Ty,
1315 LLVMMetadataRef *Subscripts,
1316 unsigned NumSubscripts) {
1317 auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
1318 NumSubscripts});
1319 return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
1320 unwrapDI<DIType>(Ty), Subs));
1321 }
1322
1323 LLVMMetadataRef
LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,uint64_t SizeInBits,LLVMDWARFTypeEncoding Encoding,LLVMDIFlags Flags)1324 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
1325 size_t NameLen, uint64_t SizeInBits,
1326 LLVMDWARFTypeEncoding Encoding,
1327 LLVMDIFlags Flags) {
1328 return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
1329 SizeInBits, Encoding,
1330 map_from_llvmDIFlags(Flags)));
1331 }
1332
LLVMDIBuilderCreatePointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef PointeeTy,uint64_t SizeInBits,uint32_t AlignInBits,unsigned AddressSpace,const char * Name,size_t NameLen)1333 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
1334 LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
1335 uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace,
1336 const char *Name, size_t NameLen) {
1337 return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
1338 SizeInBits, AlignInBits,
1339 AddressSpace, {Name, NameLen}));
1340 }
1341
LLVMDIBuilderCreateStructType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags,LLVMMetadataRef DerivedFrom,LLVMMetadataRef * Elements,unsigned NumElements,unsigned RunTimeLang,LLVMMetadataRef VTableHolder,const char * UniqueId,size_t UniqueIdLen)1342 LLVMMetadataRef LLVMDIBuilderCreateStructType(
1343 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1344 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1345 uint64_t SizeInBits, uint32_t AlignInBits, LLVMDIFlags Flags,
1346 LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
1347 unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
1348 const char *UniqueId, size_t UniqueIdLen) {
1349 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1350 NumElements});
1351 return wrap(unwrap(Builder)->createStructType(
1352 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1353 LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
1354 unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
1355 unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
1356 }
1357
LLVMDIBuilderCreateMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef Ty)1358 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
1359 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1360 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
1361 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1362 LLVMMetadataRef Ty) {
1363 return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
1364 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
1365 OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
1366 }
1367
1368 LLVMMetadataRef
LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen)1369 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
1370 size_t NameLen) {
1371 return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
1372 }
1373
LLVMDIBuilderCreateStaticMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,LLVMMetadataRef Type,LLVMDIFlags Flags,LLVMValueRef ConstantVal,uint32_t AlignInBits)1374 LLVMMetadataRef LLVMDIBuilderCreateStaticMemberType(
1375 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1376 size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
1377 LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
1378 uint32_t AlignInBits) {
1379 return wrap(unwrap(Builder)->createStaticMemberType(
1380 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1381 LineNumber, unwrapDI<DIType>(Type), map_from_llvmDIFlags(Flags),
1382 unwrap<Constant>(ConstantVal), DW_TAG_member, AlignInBits));
1383 }
1384
1385 LLVMMetadataRef
LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef Ty,LLVMMetadataRef PropertyNode)1386 LLVMDIBuilderCreateObjCIVar(LLVMDIBuilderRef Builder,
1387 const char *Name, size_t NameLen,
1388 LLVMMetadataRef File, unsigned LineNo,
1389 uint64_t SizeInBits, uint32_t AlignInBits,
1390 uint64_t OffsetInBits, LLVMDIFlags Flags,
1391 LLVMMetadataRef Ty, LLVMMetadataRef PropertyNode) {
1392 return wrap(unwrap(Builder)->createObjCIVar(
1393 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1394 SizeInBits, AlignInBits, OffsetInBits,
1395 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty),
1396 unwrapDI<MDNode>(PropertyNode)));
1397 }
1398
1399 LLVMMetadataRef
LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,const char * GetterName,size_t GetterNameLen,const char * SetterName,size_t SetterNameLen,unsigned PropertyAttributes,LLVMMetadataRef Ty)1400 LLVMDIBuilderCreateObjCProperty(LLVMDIBuilderRef Builder,
1401 const char *Name, size_t NameLen,
1402 LLVMMetadataRef File, unsigned LineNo,
1403 const char *GetterName, size_t GetterNameLen,
1404 const char *SetterName, size_t SetterNameLen,
1405 unsigned PropertyAttributes,
1406 LLVMMetadataRef Ty) {
1407 return wrap(unwrap(Builder)->createObjCProperty(
1408 {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1409 {GetterName, GetterNameLen}, {SetterName, SetterNameLen},
1410 PropertyAttributes, unwrapDI<DIType>(Ty)));
1411 }
1412
1413 LLVMMetadataRef
LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef Type)1414 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
1415 LLVMMetadataRef Type) {
1416 return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
1417 }
1418
1419 LLVMMetadataRef
LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder,LLVMMetadataRef Type,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Scope,uint32_t AlignInBits)1420 LLVMDIBuilderCreateTypedef(LLVMDIBuilderRef Builder, LLVMMetadataRef Type,
1421 const char *Name, size_t NameLen,
1422 LLVMMetadataRef File, unsigned LineNo,
1423 LLVMMetadataRef Scope, uint32_t AlignInBits) {
1424 return wrap(unwrap(Builder)->createTypedef(
1425 unwrapDI<DIType>(Type), {Name, NameLen}, unwrapDI<DIFile>(File), LineNo,
1426 unwrapDI<DIScope>(Scope), AlignInBits));
1427 }
1428
1429 LLVMMetadataRef
LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,LLVMMetadataRef Ty,LLVMMetadataRef BaseTy,uint64_t BaseOffset,uint32_t VBPtrOffset,LLVMDIFlags Flags)1430 LLVMDIBuilderCreateInheritance(LLVMDIBuilderRef Builder,
1431 LLVMMetadataRef Ty, LLVMMetadataRef BaseTy,
1432 uint64_t BaseOffset, uint32_t VBPtrOffset,
1433 LLVMDIFlags Flags) {
1434 return wrap(unwrap(Builder)->createInheritance(
1435 unwrapDI<DIType>(Ty), unwrapDI<DIType>(BaseTy),
1436 BaseOffset, VBPtrOffset, map_from_llvmDIFlags(Flags)));
1437 }
1438
1439 LLVMMetadataRef
LLVMDIBuilderCreateForwardDecl(LLVMDIBuilderRef Builder,unsigned Tag,const char * Name,size_t NameLen,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,const char * UniqueIdentifier,size_t UniqueIdentifierLen)1440 LLVMDIBuilderCreateForwardDecl(
1441 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1442 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1443 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1444 const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1445 return wrap(unwrap(Builder)->createForwardDecl(
1446 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1447 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1448 AlignInBits, {UniqueIdentifier, UniqueIdentifierLen}));
1449 }
1450
1451 LLVMMetadataRef
LLVMDIBuilderCreateReplaceableCompositeType(LLVMDIBuilderRef Builder,unsigned Tag,const char * Name,size_t NameLen,LLVMMetadataRef Scope,LLVMMetadataRef File,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags,const char * UniqueIdentifier,size_t UniqueIdentifierLen)1452 LLVMDIBuilderCreateReplaceableCompositeType(
1453 LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
1454 size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
1455 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
1456 LLVMDIFlags Flags, const char *UniqueIdentifier,
1457 size_t UniqueIdentifierLen) {
1458 return wrap(unwrap(Builder)->createReplaceableCompositeType(
1459 Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
1460 unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
1461 AlignInBits, map_from_llvmDIFlags(Flags),
1462 {UniqueIdentifier, UniqueIdentifierLen}));
1463 }
1464
1465 LLVMMetadataRef
LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder,unsigned Tag,LLVMMetadataRef Type)1466 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
1467 LLVMMetadataRef Type) {
1468 return wrap(unwrap(Builder)->createQualifiedType(Tag,
1469 unwrapDI<DIType>(Type)));
1470 }
1471
1472 LLVMMetadataRef
LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder,unsigned Tag,LLVMMetadataRef Type)1473 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
1474 LLVMMetadataRef Type) {
1475 return wrap(unwrap(Builder)->createReferenceType(Tag,
1476 unwrapDI<DIType>(Type)));
1477 }
1478
1479 LLVMMetadataRef
LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder)1480 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
1481 return wrap(unwrap(Builder)->createNullPtrType());
1482 }
1483
1484 LLVMMetadataRef
LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,LLVMMetadataRef PointeeType,LLVMMetadataRef ClassType,uint64_t SizeInBits,uint32_t AlignInBits,LLVMDIFlags Flags)1485 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
1486 LLVMMetadataRef PointeeType,
1487 LLVMMetadataRef ClassType,
1488 uint64_t SizeInBits,
1489 uint32_t AlignInBits,
1490 LLVMDIFlags Flags) {
1491 return wrap(unwrap(Builder)->createMemberPointerType(
1492 unwrapDI<DIType>(PointeeType),
1493 unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
1494 map_from_llvmDIFlags(Flags)));
1495 }
1496
1497 LLVMMetadataRef
LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint64_t OffsetInBits,uint64_t StorageOffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef Type)1498 LLVMDIBuilderCreateBitFieldMemberType(LLVMDIBuilderRef Builder,
1499 LLVMMetadataRef Scope,
1500 const char *Name, size_t NameLen,
1501 LLVMMetadataRef File, unsigned LineNumber,
1502 uint64_t SizeInBits,
1503 uint64_t OffsetInBits,
1504 uint64_t StorageOffsetInBits,
1505 LLVMDIFlags Flags, LLVMMetadataRef Type) {
1506 return wrap(unwrap(Builder)->createBitFieldMemberType(
1507 unwrapDI<DIScope>(Scope), {Name, NameLen},
1508 unwrapDI<DIFile>(File), LineNumber,
1509 SizeInBits, OffsetInBits, StorageOffsetInBits,
1510 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Type)));
1511 }
1512
LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,LLVMDIFlags Flags,LLVMMetadataRef DerivedFrom,LLVMMetadataRef * Elements,unsigned NumElements,LLVMMetadataRef VTableHolder,LLVMMetadataRef TemplateParamsNode,const char * UniqueIdentifier,size_t UniqueIdentifierLen)1513 LLVMMetadataRef LLVMDIBuilderCreateClassType(LLVMDIBuilderRef Builder,
1514 LLVMMetadataRef Scope, const char *Name, size_t NameLen,
1515 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
1516 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMDIFlags Flags,
1517 LLVMMetadataRef DerivedFrom,
1518 LLVMMetadataRef *Elements, unsigned NumElements,
1519 LLVMMetadataRef VTableHolder, LLVMMetadataRef TemplateParamsNode,
1520 const char *UniqueIdentifier, size_t UniqueIdentifierLen) {
1521 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
1522 NumElements});
1523 return wrap(unwrap(Builder)->createClassType(
1524 unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
1525 LineNumber, SizeInBits, AlignInBits, OffsetInBits,
1526 map_from_llvmDIFlags(Flags), unwrapDI<DIType>(DerivedFrom), Elts,
1527 /*RunTimeLang=*/0, unwrapDI<DIType>(VTableHolder),
1528 unwrapDI<MDNode>(TemplateParamsNode),
1529 {UniqueIdentifier, UniqueIdentifierLen}));
1530 }
1531
1532 LLVMMetadataRef
LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,LLVMMetadataRef Type)1533 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
1534 LLVMMetadataRef Type) {
1535 return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
1536 }
1537
LLVMGetDINodeTag(LLVMMetadataRef MD)1538 uint16_t LLVMGetDINodeTag(LLVMMetadataRef MD) {
1539 return unwrapDI<DINode>(MD)->getTag();
1540 }
1541
LLVMDITypeGetName(LLVMMetadataRef DType,size_t * Length)1542 const char *LLVMDITypeGetName(LLVMMetadataRef DType, size_t *Length) {
1543 StringRef Str = unwrapDI<DIType>(DType)->getName();
1544 *Length = Str.size();
1545 return Str.data();
1546 }
1547
LLVMDITypeGetSizeInBits(LLVMMetadataRef DType)1548 uint64_t LLVMDITypeGetSizeInBits(LLVMMetadataRef DType) {
1549 return unwrapDI<DIType>(DType)->getSizeInBits();
1550 }
1551
LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType)1552 uint64_t LLVMDITypeGetOffsetInBits(LLVMMetadataRef DType) {
1553 return unwrapDI<DIType>(DType)->getOffsetInBits();
1554 }
1555
LLVMDITypeGetAlignInBits(LLVMMetadataRef DType)1556 uint32_t LLVMDITypeGetAlignInBits(LLVMMetadataRef DType) {
1557 return unwrapDI<DIType>(DType)->getAlignInBits();
1558 }
1559
LLVMDITypeGetLine(LLVMMetadataRef DType)1560 unsigned LLVMDITypeGetLine(LLVMMetadataRef DType) {
1561 return unwrapDI<DIType>(DType)->getLine();
1562 }
1563
LLVMDITypeGetFlags(LLVMMetadataRef DType)1564 LLVMDIFlags LLVMDITypeGetFlags(LLVMMetadataRef DType) {
1565 return map_to_llvmDIFlags(unwrapDI<DIType>(DType)->getFlags());
1566 }
1567
LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,LLVMMetadataRef * Types,size_t Length)1568 LLVMMetadataRef LLVMDIBuilderGetOrCreateTypeArray(LLVMDIBuilderRef Builder,
1569 LLVMMetadataRef *Types,
1570 size_t Length) {
1571 return wrap(
1572 unwrap(Builder)->getOrCreateTypeArray({unwrap(Types), Length}).get());
1573 }
1574
1575 LLVMMetadataRef
LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,LLVMMetadataRef File,LLVMMetadataRef * ParameterTypes,unsigned NumParameterTypes,LLVMDIFlags Flags)1576 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
1577 LLVMMetadataRef File,
1578 LLVMMetadataRef *ParameterTypes,
1579 unsigned NumParameterTypes,
1580 LLVMDIFlags Flags) {
1581 auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
1582 NumParameterTypes});
1583 return wrap(unwrap(Builder)->createSubroutineType(
1584 Elts, map_from_llvmDIFlags(Flags)));
1585 }
1586
LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,uint64_t * Addr,size_t Length)1587 LLVMMetadataRef LLVMDIBuilderCreateExpression(LLVMDIBuilderRef Builder,
1588 uint64_t *Addr, size_t Length) {
1589 return wrap(
1590 unwrap(Builder)->createExpression(ArrayRef<uint64_t>(Addr, Length)));
1591 }
1592
1593 LLVMMetadataRef
LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,uint64_t Value)1594 LLVMDIBuilderCreateConstantValueExpression(LLVMDIBuilderRef Builder,
1595 uint64_t Value) {
1596 return wrap(unwrap(Builder)->createConstantValueExpression(Value));
1597 }
1598
LLVMDIBuilderCreateGlobalVariableExpression(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,const char * Linkage,size_t LinkLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool LocalToUnit,LLVMMetadataRef Expr,LLVMMetadataRef Decl,uint32_t AlignInBits)1599 LLVMMetadataRef LLVMDIBuilderCreateGlobalVariableExpression(
1600 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1601 size_t NameLen, const char *Linkage, size_t LinkLen, LLVMMetadataRef File,
1602 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1603 LLVMMetadataRef Expr, LLVMMetadataRef Decl, uint32_t AlignInBits) {
1604 return wrap(unwrap(Builder)->createGlobalVariableExpression(
1605 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LinkLen},
1606 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1607 true, unwrap<DIExpression>(Expr), unwrapDI<MDNode>(Decl),
1608 nullptr, AlignInBits));
1609 }
1610
LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE)1611 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetVariable(LLVMMetadataRef GVE) {
1612 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getVariable());
1613 }
1614
LLVMDIGlobalVariableExpressionGetExpression(LLVMMetadataRef GVE)1615 LLVMMetadataRef LLVMDIGlobalVariableExpressionGetExpression(
1616 LLVMMetadataRef GVE) {
1617 return wrap(unwrapDI<DIGlobalVariableExpression>(GVE)->getExpression());
1618 }
1619
LLVMDIVariableGetFile(LLVMMetadataRef Var)1620 LLVMMetadataRef LLVMDIVariableGetFile(LLVMMetadataRef Var) {
1621 return wrap(unwrapDI<DIVariable>(Var)->getFile());
1622 }
1623
LLVMDIVariableGetScope(LLVMMetadataRef Var)1624 LLVMMetadataRef LLVMDIVariableGetScope(LLVMMetadataRef Var) {
1625 return wrap(unwrapDI<DIVariable>(Var)->getScope());
1626 }
1627
LLVMDIVariableGetLine(LLVMMetadataRef Var)1628 unsigned LLVMDIVariableGetLine(LLVMMetadataRef Var) {
1629 return unwrapDI<DIVariable>(Var)->getLine();
1630 }
1631
LLVMTemporaryMDNode(LLVMContextRef Ctx,LLVMMetadataRef * Data,size_t Count)1632 LLVMMetadataRef LLVMTemporaryMDNode(LLVMContextRef Ctx, LLVMMetadataRef *Data,
1633 size_t Count) {
1634 return wrap(
1635 MDTuple::getTemporary(*unwrap(Ctx), {unwrap(Data), Count}).release());
1636 }
1637
LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode)1638 void LLVMDisposeTemporaryMDNode(LLVMMetadataRef TempNode) {
1639 MDNode::deleteTemporary(unwrapDI<MDNode>(TempNode));
1640 }
1641
LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,LLVMMetadataRef Replacement)1642 void LLVMMetadataReplaceAllUsesWith(LLVMMetadataRef TargetMetadata,
1643 LLVMMetadataRef Replacement) {
1644 auto *Node = unwrapDI<MDNode>(TargetMetadata);
1645 Node->replaceAllUsesWith(unwrap(Replacement));
1646 MDNode::deleteTemporary(Node);
1647 }
1648
LLVMDIBuilderCreateTempGlobalVariableFwdDecl(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,const char * Linkage,size_t LnkLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool LocalToUnit,LLVMMetadataRef Decl,uint32_t AlignInBits)1649 LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
1650 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1651 size_t NameLen, const char *Linkage, size_t LnkLen, LLVMMetadataRef File,
1652 unsigned LineNo, LLVMMetadataRef Ty, LLVMBool LocalToUnit,
1653 LLVMMetadataRef Decl, uint32_t AlignInBits) {
1654 return wrap(unwrap(Builder)->createTempGlobalVariableFwdDecl(
1655 unwrapDI<DIScope>(Scope), {Name, NameLen}, {Linkage, LnkLen},
1656 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), LocalToUnit,
1657 unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
1658 }
1659
1660 LLVMValueRef
LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder,LLVMValueRef Storage,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DL,LLVMValueRef Instr)1661 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
1662 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
1663 LLVMMetadataRef DL, LLVMValueRef Instr) {
1664 return wrap(unwrap(Builder)->insertDeclare(
1665 unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1666 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1667 unwrap<Instruction>(Instr)));
1668 }
1669
LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Builder,LLVMValueRef Storage,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DL,LLVMBasicBlockRef Block)1670 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
1671 LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
1672 LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
1673 return wrap(unwrap(Builder)->insertDeclare(
1674 unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
1675 unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
1676 unwrap(Block)));
1677 }
1678
LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,LLVMValueRef Val,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DebugLoc,LLVMValueRef Instr)1679 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
1680 LLVMValueRef Val,
1681 LLVMMetadataRef VarInfo,
1682 LLVMMetadataRef Expr,
1683 LLVMMetadataRef DebugLoc,
1684 LLVMValueRef Instr) {
1685 return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1686 unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1687 unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1688 unwrap<Instruction>(Instr)));
1689 }
1690
LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,LLVMValueRef Val,LLVMMetadataRef VarInfo,LLVMMetadataRef Expr,LLVMMetadataRef DebugLoc,LLVMBasicBlockRef Block)1691 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
1692 LLVMValueRef Val,
1693 LLVMMetadataRef VarInfo,
1694 LLVMMetadataRef Expr,
1695 LLVMMetadataRef DebugLoc,
1696 LLVMBasicBlockRef Block) {
1697 return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
1698 unwrap(Val), unwrap<DILocalVariable>(VarInfo),
1699 unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
1700 unwrap(Block)));
1701 }
1702
LLVMDIBuilderCreateAutoVariable(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool AlwaysPreserve,LLVMDIFlags Flags,uint32_t AlignInBits)1703 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
1704 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1705 size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
1706 LLVMBool AlwaysPreserve, LLVMDIFlags Flags, uint32_t AlignInBits) {
1707 return wrap(unwrap(Builder)->createAutoVariable(
1708 unwrap<DIScope>(Scope), {Name, NameLen}, unwrap<DIFile>(File),
1709 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1710 map_from_llvmDIFlags(Flags), AlignInBits));
1711 }
1712
LLVMDIBuilderCreateParameterVariable(LLVMDIBuilderRef Builder,LLVMMetadataRef Scope,const char * Name,size_t NameLen,unsigned ArgNo,LLVMMetadataRef File,unsigned LineNo,LLVMMetadataRef Ty,LLVMBool AlwaysPreserve,LLVMDIFlags Flags)1713 LLVMMetadataRef LLVMDIBuilderCreateParameterVariable(
1714 LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
1715 size_t NameLen, unsigned ArgNo, LLVMMetadataRef File, unsigned LineNo,
1716 LLVMMetadataRef Ty, LLVMBool AlwaysPreserve, LLVMDIFlags Flags) {
1717 return wrap(unwrap(Builder)->createParameterVariable(
1718 unwrap<DIScope>(Scope), {Name, NameLen}, ArgNo, unwrap<DIFile>(File),
1719 LineNo, unwrap<DIType>(Ty), AlwaysPreserve,
1720 map_from_llvmDIFlags(Flags)));
1721 }
1722
LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,int64_t Lo,int64_t Count)1723 LLVMMetadataRef LLVMDIBuilderGetOrCreateSubrange(LLVMDIBuilderRef Builder,
1724 int64_t Lo, int64_t Count) {
1725 return wrap(unwrap(Builder)->getOrCreateSubrange(Lo, Count));
1726 }
1727
LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,LLVMMetadataRef * Data,size_t Length)1728 LLVMMetadataRef LLVMDIBuilderGetOrCreateArray(LLVMDIBuilderRef Builder,
1729 LLVMMetadataRef *Data,
1730 size_t Length) {
1731 Metadata **DataValue = unwrap(Data);
1732 return wrap(unwrap(Builder)->getOrCreateArray({DataValue, Length}).get());
1733 }
1734
LLVMGetSubprogram(LLVMValueRef Func)1735 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1736 return wrap(unwrap<Function>(Func)->getSubprogram());
1737 }
1738
LLVMSetSubprogram(LLVMValueRef Func,LLVMMetadataRef SP)1739 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1740 unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1741 }
1742
LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram)1743 unsigned LLVMDISubprogramGetLine(LLVMMetadataRef Subprogram) {
1744 return unwrapDI<DISubprogram>(Subprogram)->getLine();
1745 }
1746
LLVMInstructionGetDebugLoc(LLVMValueRef Inst)1747 LLVMMetadataRef LLVMInstructionGetDebugLoc(LLVMValueRef Inst) {
1748 return wrap(unwrap<Instruction>(Inst)->getDebugLoc().getAsMDNode());
1749 }
1750
LLVMInstructionSetDebugLoc(LLVMValueRef Inst,LLVMMetadataRef Loc)1751 void LLVMInstructionSetDebugLoc(LLVMValueRef Inst, LLVMMetadataRef Loc) {
1752 if (Loc)
1753 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc(unwrap<MDNode>(Loc)));
1754 else
1755 unwrap<Instruction>(Inst)->setDebugLoc(DebugLoc());
1756 }
1757
LLVMGetMetadataKind(LLVMMetadataRef Metadata)1758 LLVMMetadataKind LLVMGetMetadataKind(LLVMMetadataRef Metadata) {
1759 switch(unwrap(Metadata)->getMetadataID()) {
1760 #define HANDLE_METADATA_LEAF(CLASS) \
1761 case Metadata::CLASS##Kind: \
1762 return (LLVMMetadataKind)LLVM##CLASS##MetadataKind;
1763 #include "llvm/IR/Metadata.def"
1764 default:
1765 return (LLVMMetadataKind)LLVMGenericDINodeMetadataKind;
1766 }
1767 }
1768
getAssignmentInsts(DIAssignID * ID)1769 AssignmentInstRange at::getAssignmentInsts(DIAssignID *ID) {
1770 assert(ID && "Expected non-null ID");
1771 LLVMContext &Ctx = ID->getContext();
1772 auto &Map = Ctx.pImpl->AssignmentIDToInstrs;
1773
1774 auto MapIt = Map.find(ID);
1775 if (MapIt == Map.end())
1776 return make_range(nullptr, nullptr);
1777
1778 return make_range(MapIt->second.begin(), MapIt->second.end());
1779 }
1780
getAssignmentMarkers(DIAssignID * ID)1781 AssignmentMarkerRange at::getAssignmentMarkers(DIAssignID *ID) {
1782 assert(ID && "Expected non-null ID");
1783 LLVMContext &Ctx = ID->getContext();
1784
1785 auto *IDAsValue = MetadataAsValue::getIfExists(Ctx, ID);
1786
1787 // The ID is only used wrapped in MetadataAsValue(ID), so lets check that
1788 // one of those already exists first.
1789 if (!IDAsValue)
1790 return make_range(Value::user_iterator(), Value::user_iterator());
1791
1792 return make_range(IDAsValue->user_begin(), IDAsValue->user_end());
1793 }
1794
deleteAssignmentMarkers(const Instruction * Inst)1795 void at::deleteAssignmentMarkers(const Instruction *Inst) {
1796 auto Range = getAssignmentMarkers(Inst);
1797 SmallVector<DPValue *> DPVAssigns = getDPVAssignmentMarkers(Inst);
1798 if (Range.empty() && DPVAssigns.empty())
1799 return;
1800 SmallVector<DbgAssignIntrinsic *> ToDelete(Range.begin(), Range.end());
1801 for (auto *DAI : ToDelete)
1802 DAI->eraseFromParent();
1803 for (auto *DPV : DPVAssigns)
1804 DPV->eraseFromParent();
1805 }
1806
RAUW(DIAssignID * Old,DIAssignID * New)1807 void at::RAUW(DIAssignID *Old, DIAssignID *New) {
1808 // Replace attachments.
1809 AssignmentInstRange InstRange = getAssignmentInsts(Old);
1810 // Use intermediate storage for the instruction ptrs because the
1811 // getAssignmentInsts range iterators will be invalidated by adding and
1812 // removing DIAssignID attachments.
1813 SmallVector<Instruction *> InstVec(InstRange.begin(), InstRange.end());
1814 for (auto *I : InstVec)
1815 I->setMetadata(LLVMContext::MD_DIAssignID, New);
1816
1817 Old->replaceAllUsesWith(New);
1818 }
1819
deleteAll(Function * F)1820 void at::deleteAll(Function *F) {
1821 SmallVector<DbgAssignIntrinsic *, 12> ToDelete;
1822 SmallVector<DPValue *, 12> DPToDelete;
1823 for (BasicBlock &BB : *F) {
1824 for (Instruction &I : BB) {
1825 for (auto &DPV : I.getDbgValueRange())
1826 if (DPV.isDbgAssign())
1827 DPToDelete.push_back(&DPV);
1828 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I))
1829 ToDelete.push_back(DAI);
1830 else
1831 I.setMetadata(LLVMContext::MD_DIAssignID, nullptr);
1832 }
1833 }
1834 for (auto *DAI : ToDelete)
1835 DAI->eraseFromParent();
1836 for (auto *DPV : DPToDelete)
1837 DPV->eraseFromParent();
1838 }
1839
1840 /// Get the FragmentInfo for the variable if it exists, otherwise return a
1841 /// FragmentInfo that covers the entire variable if the variable size is
1842 /// known, otherwise return a zero-sized fragment.
1843 static DIExpression::FragmentInfo
getFragmentOrEntireVariable(const DPValue * DPV)1844 getFragmentOrEntireVariable(const DPValue *DPV) {
1845 DIExpression::FragmentInfo VariableSlice(0, 0);
1846 // Get the fragment or variable size, or zero.
1847 if (auto Sz = DPV->getFragmentSizeInBits())
1848 VariableSlice.SizeInBits = *Sz;
1849 if (auto Frag = DPV->getExpression()->getFragmentInfo())
1850 VariableSlice.OffsetInBits = Frag->OffsetInBits;
1851 return VariableSlice;
1852 }
1853
1854 static DIExpression::FragmentInfo
getFragmentOrEntireVariable(const DbgVariableIntrinsic * DVI)1855 getFragmentOrEntireVariable(const DbgVariableIntrinsic *DVI) {
1856 DIExpression::FragmentInfo VariableSlice(0, 0);
1857 // Get the fragment or variable size, or zero.
1858 if (auto Sz = DVI->getFragmentSizeInBits())
1859 VariableSlice.SizeInBits = *Sz;
1860 if (auto Frag = DVI->getExpression()->getFragmentInfo())
1861 VariableSlice.OffsetInBits = Frag->OffsetInBits;
1862 return VariableSlice;
1863 }
1864 template <typename T>
calculateFragmentIntersectImpl(const DataLayout & DL,const Value * Dest,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const T * AssignRecord,std::optional<DIExpression::FragmentInfo> & Result)1865 bool calculateFragmentIntersectImpl(
1866 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
1867 uint64_t SliceSizeInBits, const T *AssignRecord,
1868 std::optional<DIExpression::FragmentInfo> &Result) {
1869 // There are multiple offsets at play in this function, so let's break it
1870 // down. Starting with how variables may be stored in allocas:
1871 //
1872 // 1 Simplest case: variable is alloca sized and starts at offset 0.
1873 // 2 Variable is larger than the alloca: the alloca holds just a part of it.
1874 // 3 Variable is smaller than the alloca: the alloca may hold multiple
1875 // variables.
1876 //
1877 // Imagine we have a store to the entire alloca. In case (3) the store
1878 // affects bits outside of the bounds of each variable. In case (2), where
1879 // the alloca holds the Xth bit to the Yth bit of a variable, the
1880 // zero-offset store doesn't represent an assignment at offset zero to the
1881 // variable. It is an assignment to offset X.
1882 //
1883 // # Example 1
1884 // Obviously, not all stores are alloca-sized and have zero offset. Imagine
1885 // the lower 32 bits of this store are dead and are going to be DSEd:
1886 //
1887 // store i64 %v, ptr %dest, !DIAssignID !1
1888 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest,
1889 // !DIExpression(DW_OP_plus_uconst, 4))
1890 //
1891 // Goal: Given our dead bits at offset:0 size:32 for the store, determine the
1892 // part of the variable, which fits in the fragment expressed by the
1893 // dbg.assign, that has been killed, if any.
1894 //
1895 // calculateFragmentIntersect(..., SliceOffsetInBits=0,
1896 // SliceSizeInBits=32, Dest=%dest, Assign=dbg.assign)
1897 //
1898 // Drawing the store (s) in memory followed by the shortened version ($),
1899 // then the dbg.assign (d), with the fragment information on a seperate scale
1900 // underneath:
1901 //
1902 // Memory
1903 // offset
1904 // from
1905 // dest 0 63
1906 // | |
1907 // s[######] - Original stores 64 bits to Dest.
1908 // $----[##] - DSE says the lower 32 bits are dead, to be removed.
1909 // d [##] - Assign's address-modifying expression adds 4 bytes to
1910 // dest.
1911 // Variable | |
1912 // Fragment 128|
1913 // Offsets 159
1914 //
1915 // The answer is achieved in a few steps:
1916 // 1. Add the fragment offset to the store offset:
1917 // SliceOffsetInBits:0 + VarFrag.OffsetInBits:128 = 128
1918 //
1919 // 2. Subtract the address-modifying expression offset plus difference
1920 // between d.address and dest:
1921 // 128 - (expression_offset:32 + (d.address - dest):0) = 96
1922 //
1923 // 3. That offset along with the store size (32) represents the bits of the
1924 // variable that'd be affected by the store. Call it SliceOfVariable.
1925 // Intersect that with Assign's fragment info:
1926 // SliceOfVariable ∩ Assign_fragment = none
1927 //
1928 // In this case: none of the dead bits of the store affect Assign.
1929 //
1930 // # Example 2
1931 // Similar example with the same goal. This time the upper 16 bits
1932 // of the store are going to be DSE'd.
1933 //
1934 // store i64 %v, ptr %dest, !DIAssignID !1
1935 // dbg.assign(..., !DIExpression(fragment, 128, 32), !1, %dest,
1936 // !DIExpression(DW_OP_plus_uconst, 4))
1937 //
1938 // calculateFragmentIntersect(..., SliceOffsetInBits=48,
1939 // SliceSizeInBits=16, Dest=%dest, Assign=dbg.assign)
1940 //
1941 // Memory
1942 // offset
1943 // from
1944 // dest 0 63
1945 // | |
1946 // s[######] - Original stores 64 bits to Dest.
1947 // $[####]-- - DSE says the upper 16 bits are dead, to be removed.
1948 // d [##] - Assign's address-modifying expression adds 4 bytes to
1949 // dest.
1950 // Variable | |
1951 // Fragment 128|
1952 // Offsets 159
1953 //
1954 // Using the same steps in the first example:
1955 // 1. SliceOffsetInBits:48 + VarFrag.OffsetInBits:128 = 176
1956 // 2. 176 - (expression_offset:32 + (d.address - dest):0) = 144
1957 // 3. SliceOfVariable offset = 144, size = 16:
1958 // SliceOfVariable ∩ Assign_fragment = (offset: 144, size: 16)
1959 // SliceOfVariable tells us the bits of the variable described by Assign that
1960 // are affected by the DSE.
1961 if (AssignRecord->isKillAddress())
1962 return false;
1963
1964 DIExpression::FragmentInfo VarFrag =
1965 getFragmentOrEntireVariable(AssignRecord);
1966 if (VarFrag.SizeInBits == 0)
1967 return false; // Variable size is unknown.
1968
1969 // Calculate the difference between Dest and the dbg.assign address +
1970 // address-modifying expression.
1971 int64_t PointerOffsetInBits;
1972 {
1973 auto DestOffsetInBytes =
1974 AssignRecord->getAddress()->getPointerOffsetFrom(Dest, DL);
1975 if (!DestOffsetInBytes)
1976 return false; // Can't calculate difference in addresses.
1977
1978 int64_t ExprOffsetInBytes;
1979 if (!AssignRecord->getAddressExpression()->extractIfOffset(
1980 ExprOffsetInBytes))
1981 return false;
1982
1983 int64_t PointerOffsetInBytes = *DestOffsetInBytes + ExprOffsetInBytes;
1984 PointerOffsetInBits = PointerOffsetInBytes * 8;
1985 }
1986
1987 // Adjust the slice offset so that we go from describing the a slice
1988 // of memory to a slice of the variable.
1989 int64_t NewOffsetInBits =
1990 SliceOffsetInBits + VarFrag.OffsetInBits - PointerOffsetInBits;
1991 if (NewOffsetInBits < 0)
1992 return false; // Fragment offsets can only be positive.
1993 DIExpression::FragmentInfo SliceOfVariable(SliceSizeInBits, NewOffsetInBits);
1994 // Intersect the variable slice with AssignRecord's fragment to trim it down
1995 // to size.
1996 DIExpression::FragmentInfo TrimmedSliceOfVariable =
1997 DIExpression::FragmentInfo::intersect(SliceOfVariable, VarFrag);
1998 if (TrimmedSliceOfVariable == VarFrag)
1999 Result = std::nullopt;
2000 else
2001 Result = TrimmedSliceOfVariable;
2002 return true;
2003 }
calculateFragmentIntersect(const DataLayout & DL,const Value * Dest,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const DbgAssignIntrinsic * DbgAssign,std::optional<DIExpression::FragmentInfo> & Result)2004 bool at::calculateFragmentIntersect(
2005 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
2006 uint64_t SliceSizeInBits, const DbgAssignIntrinsic *DbgAssign,
2007 std::optional<DIExpression::FragmentInfo> &Result) {
2008 return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits,
2009 SliceSizeInBits, DbgAssign, Result);
2010 }
calculateFragmentIntersect(const DataLayout & DL,const Value * Dest,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const DPValue * DPVAssign,std::optional<DIExpression::FragmentInfo> & Result)2011 bool at::calculateFragmentIntersect(
2012 const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits,
2013 uint64_t SliceSizeInBits, const DPValue *DPVAssign,
2014 std::optional<DIExpression::FragmentInfo> &Result) {
2015 return calculateFragmentIntersectImpl(DL, Dest, SliceOffsetInBits,
2016 SliceSizeInBits, DPVAssign, Result);
2017 }
2018
2019 /// Collect constant properies (base, size, offset) of \p StoreDest.
2020 /// Return std::nullopt if any properties are not constants or the
2021 /// offset from the base pointer is negative.
2022 static std::optional<AssignmentInfo>
getAssignmentInfoImpl(const DataLayout & DL,const Value * StoreDest,TypeSize SizeInBits)2023 getAssignmentInfoImpl(const DataLayout &DL, const Value *StoreDest,
2024 TypeSize SizeInBits) {
2025 if (SizeInBits.isScalable())
2026 return std::nullopt;
2027 APInt GEPOffset(DL.getIndexTypeSizeInBits(StoreDest->getType()), 0);
2028 const Value *Base = StoreDest->stripAndAccumulateConstantOffsets(
2029 DL, GEPOffset, /*AllowNonInbounds*/ true);
2030
2031 if (GEPOffset.isNegative())
2032 return std::nullopt;
2033
2034 uint64_t OffsetInBytes = GEPOffset.getLimitedValue();
2035 // Check for overflow.
2036 if (OffsetInBytes == UINT64_MAX)
2037 return std::nullopt;
2038 if (const auto *Alloca = dyn_cast<AllocaInst>(Base))
2039 return AssignmentInfo(DL, Alloca, OffsetInBytes * 8, SizeInBits);
2040 return std::nullopt;
2041 }
2042
getAssignmentInfo(const DataLayout & DL,const MemIntrinsic * I)2043 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
2044 const MemIntrinsic *I) {
2045 const Value *StoreDest = I->getRawDest();
2046 // Assume 8 bit bytes.
2047 auto *ConstLengthInBytes = dyn_cast<ConstantInt>(I->getLength());
2048 if (!ConstLengthInBytes)
2049 // We can't use a non-const size, bail.
2050 return std::nullopt;
2051 uint64_t SizeInBits = 8 * ConstLengthInBytes->getZExtValue();
2052 return getAssignmentInfoImpl(DL, StoreDest, TypeSize::getFixed(SizeInBits));
2053 }
2054
getAssignmentInfo(const DataLayout & DL,const StoreInst * SI)2055 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
2056 const StoreInst *SI) {
2057 TypeSize SizeInBits = DL.getTypeSizeInBits(SI->getValueOperand()->getType());
2058 return getAssignmentInfoImpl(DL, SI->getPointerOperand(), SizeInBits);
2059 }
2060
getAssignmentInfo(const DataLayout & DL,const AllocaInst * AI)2061 std::optional<AssignmentInfo> at::getAssignmentInfo(const DataLayout &DL,
2062 const AllocaInst *AI) {
2063 TypeSize SizeInBits = DL.getTypeSizeInBits(AI->getAllocatedType());
2064 return getAssignmentInfoImpl(DL, AI, SizeInBits);
2065 }
2066
2067 /// Returns nullptr if the assignment shouldn't be attributed to this variable.
emitDbgAssign(AssignmentInfo Info,Value * Val,Value * Dest,Instruction & StoreLikeInst,const VarRecord & VarRec,DIBuilder & DIB)2068 static void emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
2069 Instruction &StoreLikeInst, const VarRecord &VarRec,
2070 DIBuilder &DIB) {
2071 auto *ID = StoreLikeInst.getMetadata(LLVMContext::MD_DIAssignID);
2072 assert(ID && "Store instruction must have DIAssignID metadata");
2073 (void)ID;
2074
2075 const uint64_t StoreStartBit = Info.OffsetInBits;
2076 const uint64_t StoreEndBit = Info.OffsetInBits + Info.SizeInBits;
2077
2078 uint64_t FragStartBit = StoreStartBit;
2079 uint64_t FragEndBit = StoreEndBit;
2080
2081 bool StoreToWholeVariable = Info.StoreToWholeAlloca;
2082 if (auto Size = VarRec.Var->getSizeInBits()) {
2083 // NOTE: trackAssignments doesn't understand base expressions yet, so all
2084 // variables that reach here are guaranteed to start at offset 0 in the
2085 // alloca.
2086 const uint64_t VarStartBit = 0;
2087 const uint64_t VarEndBit = *Size;
2088
2089 // FIXME: trim FragStartBit when nonzero VarStartBit is supported.
2090 FragEndBit = std::min(FragEndBit, VarEndBit);
2091
2092 // Discard stores to bits outside this variable.
2093 if (FragStartBit >= FragEndBit)
2094 return;
2095
2096 StoreToWholeVariable = FragStartBit <= VarStartBit && FragEndBit >= *Size;
2097 }
2098
2099 DIExpression *Expr =
2100 DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
2101 if (!StoreToWholeVariable) {
2102 auto R = DIExpression::createFragmentExpression(Expr, FragStartBit,
2103 FragEndBit - FragStartBit);
2104 assert(R.has_value() && "failed to create fragment expression");
2105 Expr = *R;
2106 }
2107 DIExpression *AddrExpr =
2108 DIExpression::get(StoreLikeInst.getContext(), std::nullopt);
2109 if (StoreLikeInst.getParent()->IsNewDbgInfoFormat) {
2110 auto *Assign = DPValue::createLinkedDPVAssign(
2111 &StoreLikeInst, Val, VarRec.Var, Expr, Dest, AddrExpr, VarRec.DL);
2112 (void)Assign;
2113 LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");
2114 return;
2115 }
2116 auto *Assign = DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr,
2117 Dest, AddrExpr, VarRec.DL);
2118 (void)Assign;
2119 LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");
2120 }
2121
2122 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
2123 #define DEBUG_TYPE "assignment-tracking"
2124
trackAssignments(Function::iterator Start,Function::iterator End,const StorageToVarsMap & Vars,const DataLayout & DL,bool DebugPrints)2125 void at::trackAssignments(Function::iterator Start, Function::iterator End,
2126 const StorageToVarsMap &Vars, const DataLayout &DL,
2127 bool DebugPrints) {
2128 // Early-exit if there are no interesting variables.
2129 if (Vars.empty())
2130 return;
2131
2132 auto &Ctx = Start->getContext();
2133 auto &Module = *Start->getModule();
2134
2135 // Undef type doesn't matter, so long as it isn't void. Let's just use i1.
2136 auto *Undef = UndefValue::get(Type::getInt1Ty(Ctx));
2137 DIBuilder DIB(Module, /*AllowUnresolved*/ false);
2138
2139 // Scan the instructions looking for stores to local variables' storage.
2140 LLVM_DEBUG(errs() << "# Scanning instructions\n");
2141 for (auto BBI = Start; BBI != End; ++BBI) {
2142 for (Instruction &I : *BBI) {
2143
2144 std::optional<AssignmentInfo> Info;
2145 Value *ValueComponent = nullptr;
2146 Value *DestComponent = nullptr;
2147 if (auto *AI = dyn_cast<AllocaInst>(&I)) {
2148 // We want to track the variable's stack home from its alloca's
2149 // position onwards so we treat it as an assignment (where the stored
2150 // value is Undef).
2151 Info = getAssignmentInfo(DL, AI);
2152 ValueComponent = Undef;
2153 DestComponent = AI;
2154 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2155 Info = getAssignmentInfo(DL, SI);
2156 ValueComponent = SI->getValueOperand();
2157 DestComponent = SI->getPointerOperand();
2158 } else if (auto *MI = dyn_cast<MemTransferInst>(&I)) {
2159 Info = getAssignmentInfo(DL, MI);
2160 // May not be able to represent this value easily.
2161 ValueComponent = Undef;
2162 DestComponent = MI->getOperand(0);
2163 } else if (auto *MI = dyn_cast<MemSetInst>(&I)) {
2164 Info = getAssignmentInfo(DL, MI);
2165 // If we're zero-initing we can state the assigned value is zero,
2166 // otherwise use undef.
2167 auto *ConstValue = dyn_cast<ConstantInt>(MI->getOperand(1));
2168 if (ConstValue && ConstValue->isZero())
2169 ValueComponent = ConstValue;
2170 else
2171 ValueComponent = Undef;
2172 DestComponent = MI->getOperand(0);
2173 } else {
2174 // Not a store-like instruction.
2175 continue;
2176 }
2177
2178 assert(ValueComponent && DestComponent);
2179 LLVM_DEBUG(errs() << "SCAN: Found store-like: " << I << "\n");
2180
2181 // Check if getAssignmentInfo failed to understand this store.
2182 if (!Info.has_value()) {
2183 LLVM_DEBUG(
2184 errs()
2185 << " | SKIP: Untrackable store (e.g. through non-const gep)\n");
2186 continue;
2187 }
2188 LLVM_DEBUG(errs() << " | BASE: " << *Info->Base << "\n");
2189
2190 // Check if the store destination is a local variable with debug info.
2191 auto LocalIt = Vars.find(Info->Base);
2192 if (LocalIt == Vars.end()) {
2193 LLVM_DEBUG(
2194 errs()
2195 << " | SKIP: Base address not associated with local variable\n");
2196 continue;
2197 }
2198
2199 DIAssignID *ID =
2200 cast_or_null<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID));
2201 if (!ID) {
2202 ID = DIAssignID::getDistinct(Ctx);
2203 I.setMetadata(LLVMContext::MD_DIAssignID, ID);
2204 }
2205
2206 for (const VarRecord &R : LocalIt->second)
2207 emitDbgAssign(*Info, ValueComponent, DestComponent, I, R, DIB);
2208 }
2209 }
2210 }
2211
runOnFunction(Function & F)2212 bool AssignmentTrackingPass::runOnFunction(Function &F) {
2213 // No value in assignment tracking without optimisations.
2214 if (F.hasFnAttribute(Attribute::OptimizeNone))
2215 return /*Changed*/ false;
2216
2217 // FIXME: https://github.com/llvm/llvm-project/issues/76545
2218 if (F.hasFnAttribute(Attribute::SanitizeHWAddress))
2219 return /*Changed*/ false;
2220
2221 bool Changed = false;
2222 auto *DL = &F.getParent()->getDataLayout();
2223 // Collect a map of {backing storage : dbg.declares} (currently "backing
2224 // storage" is limited to Allocas). We'll use this to find dbg.declares to
2225 // delete after running `trackAssignments`.
2226 DenseMap<const AllocaInst *, SmallPtrSet<DbgDeclareInst *, 2>> DbgDeclares;
2227 DenseMap<const AllocaInst *, SmallPtrSet<DPValue *, 2>> DPVDeclares;
2228 // Create another similar map of {storage : variables} that we'll pass to
2229 // trackAssignments.
2230 StorageToVarsMap Vars;
2231 auto ProcessDeclare = [&](auto *Declare, auto &DeclareList) {
2232 // FIXME: trackAssignments doesn't let you specify any modifiers to the
2233 // variable (e.g. fragment) or location (e.g. offset), so we have to
2234 // leave dbg.declares with non-empty expressions in place.
2235 if (Declare->getExpression()->getNumElements() != 0)
2236 return;
2237 if (!Declare->getAddress())
2238 return;
2239 if (AllocaInst *Alloca =
2240 dyn_cast<AllocaInst>(Declare->getAddress()->stripPointerCasts())) {
2241 // FIXME: Skip VLAs for now (let these variables use dbg.declares).
2242 if (!Alloca->isStaticAlloca())
2243 return;
2244 // Similarly, skip scalable vectors (use dbg.declares instead).
2245 if (auto Sz = Alloca->getAllocationSize(*DL); Sz && Sz->isScalable())
2246 return;
2247 DeclareList[Alloca].insert(Declare);
2248 Vars[Alloca].insert(VarRecord(Declare));
2249 }
2250 };
2251 for (auto &BB : F) {
2252 for (auto &I : BB) {
2253 for (auto &DPV : I.getDbgValueRange()) {
2254 if (DPV.isDbgDeclare())
2255 ProcessDeclare(&DPV, DPVDeclares);
2256 }
2257 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(&I))
2258 ProcessDeclare(DDI, DbgDeclares);
2259 }
2260 }
2261
2262 // FIXME: Locals can be backed by caller allocas (sret, byval).
2263 // Note: trackAssignments doesn't respect dbg.declare's IR positions (as it
2264 // doesn't "understand" dbg.declares). However, this doesn't appear to break
2265 // any rules given this description of dbg.declare from
2266 // llvm/docs/SourceLevelDebugging.rst:
2267 //
2268 // It is not control-dependent, meaning that if a call to llvm.dbg.declare
2269 // exists and has a valid location argument, that address is considered to
2270 // be the true home of the variable across its entire lifetime.
2271 trackAssignments(F.begin(), F.end(), Vars, *DL);
2272
2273 // Delete dbg.declares for variables now tracked with assignment tracking.
2274 auto DeleteSubsumedDeclare = [&](const auto &Markers, auto &Declares) {
2275 (void)Markers;
2276 for (auto *Declare : Declares) {
2277 // Assert that the alloca that Declare uses is now linked to a dbg.assign
2278 // describing the same variable (i.e. check that this dbg.declare has
2279 // been replaced by a dbg.assign). Use DebugVariableAggregate to Discard
2280 // the fragment part because trackAssignments may alter the
2281 // fragment. e.g. if the alloca is smaller than the variable, then
2282 // trackAssignments will create an alloca-sized fragment for the
2283 // dbg.assign.
2284 assert(llvm::any_of(Markers, [Declare](auto *Assign) {
2285 return DebugVariableAggregate(Assign) ==
2286 DebugVariableAggregate(Declare);
2287 }));
2288 // Delete Declare because the variable location is now tracked using
2289 // assignment tracking.
2290 Declare->eraseFromParent();
2291 Changed = true;
2292 }
2293 };
2294 for (auto &P : DbgDeclares)
2295 DeleteSubsumedDeclare(at::getAssignmentMarkers(P.first), P.second);
2296 for (auto &P : DPVDeclares)
2297 DeleteSubsumedDeclare(at::getDPVAssignmentMarkers(P.first), P.second);
2298 return Changed;
2299 }
2300
2301 static const char *AssignmentTrackingModuleFlag =
2302 "debug-info-assignment-tracking";
2303
setAssignmentTrackingModuleFlag(Module & M)2304 static void setAssignmentTrackingModuleFlag(Module &M) {
2305 M.setModuleFlag(Module::ModFlagBehavior::Max, AssignmentTrackingModuleFlag,
2306 ConstantAsMetadata::get(
2307 ConstantInt::get(Type::getInt1Ty(M.getContext()), 1)));
2308 }
2309
getAssignmentTrackingModuleFlag(const Module & M)2310 static bool getAssignmentTrackingModuleFlag(const Module &M) {
2311 Metadata *Value = M.getModuleFlag(AssignmentTrackingModuleFlag);
2312 return Value && !cast<ConstantAsMetadata>(Value)->getValue()->isZeroValue();
2313 }
2314
isAssignmentTrackingEnabled(const Module & M)2315 bool llvm::isAssignmentTrackingEnabled(const Module &M) {
2316 return getAssignmentTrackingModuleFlag(M);
2317 }
2318
run(Function & F,FunctionAnalysisManager & AM)2319 PreservedAnalyses AssignmentTrackingPass::run(Function &F,
2320 FunctionAnalysisManager &AM) {
2321 if (!runOnFunction(F))
2322 return PreservedAnalyses::all();
2323
2324 // Record that this module uses assignment tracking. It doesn't matter that
2325 // some functons in the module may not use it - the debug info in those
2326 // functions will still be handled properly.
2327 setAssignmentTrackingModuleFlag(*F.getParent());
2328
2329 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2330 // return PreservedAnalyses::all()?
2331 PreservedAnalyses PA;
2332 PA.preserveSet<CFGAnalyses>();
2333 return PA;
2334 }
2335
run(Module & M,ModuleAnalysisManager & AM)2336 PreservedAnalyses AssignmentTrackingPass::run(Module &M,
2337 ModuleAnalysisManager &AM) {
2338 bool Changed = false;
2339 for (auto &F : M)
2340 Changed |= runOnFunction(F);
2341
2342 if (!Changed)
2343 return PreservedAnalyses::all();
2344
2345 // Record that this module uses assignment tracking.
2346 setAssignmentTrackingModuleFlag(M);
2347
2348 // Q: Can we return a less conservative set than just CFGAnalyses? Can we
2349 // return PreservedAnalyses::all()?
2350 PreservedAnalyses PA;
2351 PA.preserveSet<CFGAnalyses>();
2352 return PA;
2353 }
2354
2355 #undef DEBUG_TYPE
2356