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