1 //===- DebugInfo.cpp - Debug Information Helper Classes -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm-c/DebugInfo.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfoMetadata.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GVMaterializer.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Support/Casting.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <utility>
40 
41 using namespace llvm;
42 using namespace llvm::dwarf;
43 
44 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
45   if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
46     return LocalScope->getSubprogram();
47   return nullptr;
48 }
49 
50 //===----------------------------------------------------------------------===//
51 // DebugInfoFinder implementations.
52 //===----------------------------------------------------------------------===//
53 
54 void DebugInfoFinder::reset() {
55   CUs.clear();
56   SPs.clear();
57   GVs.clear();
58   TYs.clear();
59   Scopes.clear();
60   NodesSeen.clear();
61 }
62 
63 void DebugInfoFinder::processModule(const Module &M) {
64   for (auto *CU : M.debug_compile_units())
65     processCompileUnit(CU);
66   for (auto &F : M.functions()) {
67     if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
68       processSubprogram(SP);
69     // There could be subprograms from inlined functions referenced from
70     // instructions only. Walk the function to find them.
71     for (const BasicBlock &BB : F)
72       for (const Instruction &I : BB)
73         processInstruction(M, I);
74   }
75 }
76 
77 void DebugInfoFinder::processCompileUnit(DICompileUnit *CU) {
78   if (!addCompileUnit(CU))
79     return;
80   for (auto DIG : CU->getGlobalVariables()) {
81     if (!addGlobalVariable(DIG))
82       continue;
83     auto *GV = DIG->getVariable();
84     processScope(GV->getScope());
85     processType(GV->getType().resolve());
86   }
87   for (auto *ET : CU->getEnumTypes())
88     processType(ET);
89   for (auto *RT : CU->getRetainedTypes())
90     if (auto *T = dyn_cast<DIType>(RT))
91       processType(T);
92     else
93       processSubprogram(cast<DISubprogram>(RT));
94   for (auto *Import : CU->getImportedEntities()) {
95     auto *Entity = Import->getEntity().resolve();
96     if (auto *T = dyn_cast<DIType>(Entity))
97       processType(T);
98     else if (auto *SP = dyn_cast<DISubprogram>(Entity))
99       processSubprogram(SP);
100     else if (auto *NS = dyn_cast<DINamespace>(Entity))
101       processScope(NS->getScope());
102     else if (auto *M = dyn_cast<DIModule>(Entity))
103       processScope(M->getScope());
104     else
105       llvm_unreachable("unexpected imported entity type");
106   }
107 }
108 
109 void DebugInfoFinder::processInstruction(const Module &M,
110                                          const Instruction &I) {
111   if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
112     processDeclare(M, DDI);
113   else if (auto *DVI = dyn_cast<DbgValueInst>(&I))
114     processValue(M, DVI);
115 
116   if (auto DbgLoc = I.getDebugLoc())
117     processLocation(M, DbgLoc.get());
118 }
119 
120 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
121   if (!Loc)
122     return;
123   processScope(Loc->getScope());
124   processLocation(M, Loc->getInlinedAt());
125 }
126 
127 void DebugInfoFinder::processType(DIType *DT) {
128   if (!addType(DT))
129     return;
130   processScope(DT->getScope().resolve());
131   if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
132     for (DITypeRef Ref : ST->getTypeArray())
133       processType(Ref.resolve());
134     return;
135   }
136   if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
137     processType(DCT->getBaseType().resolve());
138     for (Metadata *D : DCT->getElements()) {
139       if (auto *T = dyn_cast<DIType>(D))
140         processType(T);
141       else if (auto *SP = dyn_cast<DISubprogram>(D))
142         processSubprogram(SP);
143     }
144     return;
145   }
146   if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
147     processType(DDT->getBaseType().resolve());
148   }
149 }
150 
151 void DebugInfoFinder::processScope(DIScope *Scope) {
152   if (!Scope)
153     return;
154   if (auto *Ty = dyn_cast<DIType>(Scope)) {
155     processType(Ty);
156     return;
157   }
158   if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
159     addCompileUnit(CU);
160     return;
161   }
162   if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
163     processSubprogram(SP);
164     return;
165   }
166   if (!addScope(Scope))
167     return;
168   if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
169     processScope(LB->getScope());
170   } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
171     processScope(NS->getScope());
172   } else if (auto *M = dyn_cast<DIModule>(Scope)) {
173     processScope(M->getScope());
174   }
175 }
176 
177 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
178   if (!addSubprogram(SP))
179     return;
180   processScope(SP->getScope().resolve());
181   // Some of the users, e.g. CloneFunctionInto / CloneModule, need to set up a
182   // ValueMap containing identity mappings for all of the DICompileUnit's, not
183   // just DISubprogram's, referenced from anywhere within the Function being
184   // cloned prior to calling MapMetadata / RemapInstruction to avoid their
185   // duplication later as DICompileUnit's are also directly referenced by
186   // llvm.dbg.cu list. Thefore we need to collect DICompileUnit's here as well.
187   // Also, DICompileUnit's may reference DISubprogram's too and therefore need
188   // to be at least looked through.
189   processCompileUnit(SP->getUnit());
190   processType(SP->getType());
191   for (auto *Element : SP->getTemplateParams()) {
192     if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
193       processType(TType->getType().resolve());
194     } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
195       processType(TVal->getType().resolve());
196     }
197   }
198 }
199 
200 void DebugInfoFinder::processDeclare(const Module &M,
201                                      const DbgDeclareInst *DDI) {
202   auto *N = dyn_cast<MDNode>(DDI->getVariable());
203   if (!N)
204     return;
205 
206   auto *DV = dyn_cast<DILocalVariable>(N);
207   if (!DV)
208     return;
209 
210   if (!NodesSeen.insert(DV).second)
211     return;
212   processScope(DV->getScope());
213   processType(DV->getType().resolve());
214 }
215 
216 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
217   auto *N = dyn_cast<MDNode>(DVI->getVariable());
218   if (!N)
219     return;
220 
221   auto *DV = dyn_cast<DILocalVariable>(N);
222   if (!DV)
223     return;
224 
225   if (!NodesSeen.insert(DV).second)
226     return;
227   processScope(DV->getScope());
228   processType(DV->getType().resolve());
229 }
230 
231 bool DebugInfoFinder::addType(DIType *DT) {
232   if (!DT)
233     return false;
234 
235   if (!NodesSeen.insert(DT).second)
236     return false;
237 
238   TYs.push_back(const_cast<DIType *>(DT));
239   return true;
240 }
241 
242 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
243   if (!CU)
244     return false;
245   if (!NodesSeen.insert(CU).second)
246     return false;
247 
248   CUs.push_back(CU);
249   return true;
250 }
251 
252 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
253   if (!NodesSeen.insert(DIG).second)
254     return false;
255 
256   GVs.push_back(DIG);
257   return true;
258 }
259 
260 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
261   if (!SP)
262     return false;
263 
264   if (!NodesSeen.insert(SP).second)
265     return false;
266 
267   SPs.push_back(SP);
268   return true;
269 }
270 
271 bool DebugInfoFinder::addScope(DIScope *Scope) {
272   if (!Scope)
273     return false;
274   // FIXME: Ocaml binding generates a scope with no content, we treat it
275   // as null for now.
276   if (Scope->getNumOperands() == 0)
277     return false;
278   if (!NodesSeen.insert(Scope).second)
279     return false;
280   Scopes.push_back(Scope);
281   return true;
282 }
283 
284 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
285   assert(N->op_begin() != N->op_end() && "Missing self reference?");
286 
287   // if there is no debug location, we do not have to rewrite this MDNode.
288   if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
289         return isa<DILocation>(Op.get());
290       }))
291     return N;
292 
293   // If there is only the debug location without any actual loop metadata, we
294   // can remove the metadata.
295   if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
296         return !isa<DILocation>(Op.get());
297       }))
298     return nullptr;
299 
300   SmallVector<Metadata *, 4> Args;
301   // Reserve operand 0 for loop id self reference.
302   auto TempNode = MDNode::getTemporary(N->getContext(), None);
303   Args.push_back(TempNode.get());
304   // Add all non-debug location operands back.
305   for (auto Op = N->op_begin() + 1; Op != N->op_end(); Op++) {
306     if (!isa<DILocation>(*Op))
307       Args.push_back(*Op);
308   }
309 
310   // Set the first operand to itself.
311   MDNode *LoopID = MDNode::get(N->getContext(), Args);
312   LoopID->replaceOperandWith(0, LoopID);
313   return LoopID;
314 }
315 
316 bool llvm::stripDebugInfo(Function &F) {
317   bool Changed = false;
318   if (F.getMetadata(LLVMContext::MD_dbg)) {
319     Changed = true;
320     F.setSubprogram(nullptr);
321   }
322 
323   DenseMap<MDNode*, MDNode*> LoopIDsMap;
324   for (BasicBlock &BB : F) {
325     for (auto II = BB.begin(), End = BB.end(); II != End;) {
326       Instruction &I = *II++; // We may delete the instruction, increment now.
327       if (isa<DbgInfoIntrinsic>(&I)) {
328         I.eraseFromParent();
329         Changed = true;
330         continue;
331       }
332       if (I.getDebugLoc()) {
333         Changed = true;
334         I.setDebugLoc(DebugLoc());
335       }
336     }
337 
338     auto *TermInst = BB.getTerminator();
339     if (!TermInst)
340       // This is invalid IR, but we may not have run the verifier yet
341       continue;
342     if (auto *LoopID = TermInst->getMetadata(LLVMContext::MD_loop)) {
343       auto *NewLoopID = LoopIDsMap.lookup(LoopID);
344       if (!NewLoopID)
345         NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
346       if (NewLoopID != LoopID)
347         TermInst->setMetadata(LLVMContext::MD_loop, NewLoopID);
348     }
349   }
350   return Changed;
351 }
352 
353 bool llvm::StripDebugInfo(Module &M) {
354   bool Changed = false;
355 
356   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
357          NME = M.named_metadata_end(); NMI != NME;) {
358     NamedMDNode *NMD = &*NMI;
359     ++NMI;
360 
361     // We're stripping debug info, and without them, coverage information
362     // doesn't quite make sense.
363     if (NMD->getName().startswith("llvm.dbg.") ||
364         NMD->getName() == "llvm.gcov") {
365       NMD->eraseFromParent();
366       Changed = true;
367     }
368   }
369 
370   for (Function &F : M)
371     Changed |= stripDebugInfo(F);
372 
373   for (auto &GV : M.globals()) {
374     SmallVector<MDNode *, 1> MDs;
375     GV.getMetadata(LLVMContext::MD_dbg, MDs);
376     if (!MDs.empty()) {
377       GV.eraseMetadata(LLVMContext::MD_dbg);
378       Changed = true;
379     }
380   }
381 
382   if (GVMaterializer *Materializer = M.getMaterializer())
383     Materializer->setStripDebugInfo();
384 
385   return Changed;
386 }
387 
388 namespace {
389 
390 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
391 class DebugTypeInfoRemoval {
392   DenseMap<Metadata *, Metadata *> Replacements;
393 
394 public:
395   /// The (void)() type.
396   MDNode *EmptySubroutineType;
397 
398 private:
399   /// Remember what linkage name we originally had before stripping. If we end
400   /// up making two subprograms identical who originally had different linkage
401   /// names, then we need to make one of them distinct, to avoid them getting
402   /// uniqued. Maps the new node to the old linkage name.
403   DenseMap<DISubprogram *, StringRef> NewToLinkageName;
404 
405   // TODO: Remember the distinct subprogram we created for a given linkage name,
406   // so that we can continue to unique whenever possible. Map <newly created
407   // node, old linkage name> to the first (possibly distinct) mdsubprogram
408   // created for that combination. This is not strictly needed for correctness,
409   // but can cut down on the number of MDNodes and let us diff cleanly with the
410   // output of -gline-tables-only.
411 
412 public:
413   DebugTypeInfoRemoval(LLVMContext &C)
414       : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
415                                                   MDNode::get(C, {}))) {}
416 
417   Metadata *map(Metadata *M) {
418     if (!M)
419       return nullptr;
420     auto Replacement = Replacements.find(M);
421     if (Replacement != Replacements.end())
422       return Replacement->second;
423 
424     return M;
425   }
426   MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
427 
428   /// Recursively remap N and all its referenced children. Does a DF post-order
429   /// traversal, so as to remap bottoms up.
430   void traverseAndRemap(MDNode *N) { traverse(N); }
431 
432 private:
433   // Create a new DISubprogram, to replace the one given.
434   DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
435     auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
436     StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
437     DISubprogram *Declaration = nullptr;
438     auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
439     DITypeRef ContainingType(map(MDS->getContainingType()));
440     auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
441     auto Variables = nullptr;
442     auto TemplateParams = nullptr;
443 
444     // Make a distinct DISubprogram, for situations that warrent it.
445     auto distinctMDSubprogram = [&]() {
446       return DISubprogram::getDistinct(
447           MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
448           FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
449           MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
450           MDS->getVirtuality(), MDS->getVirtualIndex(),
451           MDS->getThisAdjustment(), MDS->getFlags(), MDS->isOptimized(), Unit,
452           TemplateParams, Declaration, Variables);
453     };
454 
455     if (MDS->isDistinct())
456       return distinctMDSubprogram();
457 
458     auto *NewMDS = DISubprogram::get(
459         MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
460         FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
461         MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
462         MDS->getVirtuality(), MDS->getVirtualIndex(), MDS->getThisAdjustment(),
463         MDS->getFlags(), MDS->isOptimized(), Unit, TemplateParams, Declaration,
464         Variables);
465 
466     StringRef OldLinkageName = MDS->getLinkageName();
467 
468     // See if we need to make a distinct one.
469     auto OrigLinkage = NewToLinkageName.find(NewMDS);
470     if (OrigLinkage != NewToLinkageName.end()) {
471       if (OrigLinkage->second == OldLinkageName)
472         // We're good.
473         return NewMDS;
474 
475       // Otherwise, need to make a distinct one.
476       // TODO: Query the map to see if we already have one.
477       return distinctMDSubprogram();
478     }
479 
480     NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
481     return NewMDS;
482   }
483 
484   /// Create a new compile unit, to replace the one given
485   DICompileUnit *getReplacementCU(DICompileUnit *CU) {
486     // Drop skeleton CUs.
487     if (CU->getDWOId())
488       return nullptr;
489 
490     auto *File = cast_or_null<DIFile>(map(CU->getFile()));
491     MDTuple *EnumTypes = nullptr;
492     MDTuple *RetainedTypes = nullptr;
493     MDTuple *GlobalVariables = nullptr;
494     MDTuple *ImportedEntities = nullptr;
495     return DICompileUnit::getDistinct(
496         CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
497         CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
498         CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
499         RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
500         CU->getDWOId(), CU->getSplitDebugInlining(),
501         CU->getDebugInfoForProfiling(), CU->getGnuPubnames());
502   }
503 
504   DILocation *getReplacementMDLocation(DILocation *MLD) {
505     auto *Scope = map(MLD->getScope());
506     auto *InlinedAt = map(MLD->getInlinedAt());
507     if (MLD->isDistinct())
508       return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
509                                      MLD->getColumn(), Scope, InlinedAt);
510     return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
511                            Scope, InlinedAt);
512   }
513 
514   /// Create a new generic MDNode, to replace the one given
515   MDNode *getReplacementMDNode(MDNode *N) {
516     SmallVector<Metadata *, 8> Ops;
517     Ops.reserve(N->getNumOperands());
518     for (auto &I : N->operands())
519       if (I)
520         Ops.push_back(map(I));
521     auto *Ret = MDNode::get(N->getContext(), Ops);
522     return Ret;
523   }
524 
525   /// Attempt to re-map N to a newly created node.
526   void remap(MDNode *N) {
527     if (Replacements.count(N))
528       return;
529 
530     auto doRemap = [&](MDNode *N) -> MDNode * {
531       if (!N)
532         return nullptr;
533       if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
534         remap(MDSub->getUnit());
535         return getReplacementSubprogram(MDSub);
536       }
537       if (isa<DISubroutineType>(N))
538         return EmptySubroutineType;
539       if (auto *CU = dyn_cast<DICompileUnit>(N))
540         return getReplacementCU(CU);
541       if (isa<DIFile>(N))
542         return N;
543       if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
544         // Remap to our referenced scope (recursively).
545         return mapNode(MDLB->getScope());
546       if (auto *MLD = dyn_cast<DILocation>(N))
547         return getReplacementMDLocation(MLD);
548 
549       // Otherwise, if we see these, just drop them now. Not strictly necessary,
550       // but this speeds things up a little.
551       if (isa<DINode>(N))
552         return nullptr;
553 
554       return getReplacementMDNode(N);
555     };
556     Replacements[N] = doRemap(N);
557   }
558 
559   /// Do the remapping traversal.
560   void traverse(MDNode *);
561 };
562 
563 } // end anonymous namespace
564 
565 void DebugTypeInfoRemoval::traverse(MDNode *N) {
566   if (!N || Replacements.count(N))
567     return;
568 
569   // To avoid cycles, as well as for efficiency sake, we will sometimes prune
570   // parts of the graph.
571   auto prune = [](MDNode *Parent, MDNode *Child) {
572     if (auto *MDS = dyn_cast<DISubprogram>(Parent))
573       return Child == MDS->getVariables().get();
574     return false;
575   };
576 
577   SmallVector<MDNode *, 16> ToVisit;
578   DenseSet<MDNode *> Opened;
579 
580   // Visit each node starting at N in post order, and map them.
581   ToVisit.push_back(N);
582   while (!ToVisit.empty()) {
583     auto *N = ToVisit.back();
584     if (!Opened.insert(N).second) {
585       // Close it.
586       remap(N);
587       ToVisit.pop_back();
588       continue;
589     }
590     for (auto &I : N->operands())
591       if (auto *MDN = dyn_cast_or_null<MDNode>(I))
592         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
593             !isa<DICompileUnit>(MDN))
594           ToVisit.push_back(MDN);
595   }
596 }
597 
598 bool llvm::stripNonLineTableDebugInfo(Module &M) {
599   bool Changed = false;
600 
601   // First off, delete the debug intrinsics.
602   auto RemoveUses = [&](StringRef Name) {
603     if (auto *DbgVal = M.getFunction(Name)) {
604       while (!DbgVal->use_empty())
605         cast<Instruction>(DbgVal->user_back())->eraseFromParent();
606       DbgVal->eraseFromParent();
607       Changed = true;
608     }
609   };
610   RemoveUses("llvm.dbg.declare");
611   RemoveUses("llvm.dbg.value");
612 
613   // Delete non-CU debug info named metadata nodes.
614   for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
615        NMI != NME;) {
616     NamedMDNode *NMD = &*NMI;
617     ++NMI;
618     // Specifically keep dbg.cu around.
619     if (NMD->getName() == "llvm.dbg.cu")
620       continue;
621   }
622 
623   // Drop all dbg attachments from global variables.
624   for (auto &GV : M.globals())
625     GV.eraseMetadata(LLVMContext::MD_dbg);
626 
627   DebugTypeInfoRemoval Mapper(M.getContext());
628   auto remap = [&](MDNode *Node) -> MDNode * {
629     if (!Node)
630       return nullptr;
631     Mapper.traverseAndRemap(Node);
632     auto *NewNode = Mapper.mapNode(Node);
633     Changed |= Node != NewNode;
634     Node = NewNode;
635     return NewNode;
636   };
637 
638   // Rewrite the DebugLocs to be equivalent to what
639   // -gline-tables-only would have created.
640   for (auto &F : M) {
641     if (auto *SP = F.getSubprogram()) {
642       Mapper.traverseAndRemap(SP);
643       auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
644       Changed |= SP != NewSP;
645       F.setSubprogram(NewSP);
646     }
647     for (auto &BB : F) {
648       for (auto &I : BB) {
649         auto remapDebugLoc = [&](DebugLoc DL) -> DebugLoc {
650           auto *Scope = DL.getScope();
651           MDNode *InlinedAt = DL.getInlinedAt();
652           Scope = remap(Scope);
653           InlinedAt = remap(InlinedAt);
654           return DebugLoc::get(DL.getLine(), DL.getCol(), Scope, InlinedAt);
655         };
656 
657         if (I.getDebugLoc() != DebugLoc())
658           I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
659 
660         // Remap DILocations in untyped MDNodes (e.g., llvm.loop).
661         SmallVector<std::pair<unsigned, MDNode *>, 2> MDs;
662         I.getAllMetadata(MDs);
663         for (auto Attachment : MDs)
664           if (auto *T = dyn_cast_or_null<MDTuple>(Attachment.second))
665             for (unsigned N = 0; N < T->getNumOperands(); ++N)
666               if (auto *Loc = dyn_cast_or_null<DILocation>(T->getOperand(N)))
667                 if (Loc != DebugLoc())
668                   T->replaceOperandWith(N, remapDebugLoc(Loc));
669       }
670     }
671   }
672 
673   // Create a new llvm.dbg.cu, which is equivalent to the one
674   // -gline-tables-only would have created.
675   for (auto &NMD : M.getNamedMDList()) {
676     SmallVector<MDNode *, 8> Ops;
677     for (MDNode *Op : NMD.operands())
678       Ops.push_back(remap(Op));
679 
680     if (!Changed)
681       continue;
682 
683     NMD.clearOperands();
684     for (auto *Op : Ops)
685       if (Op)
686         NMD.addOperand(Op);
687   }
688   return Changed;
689 }
690 
691 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
692   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
693           M.getModuleFlag("Debug Info Version")))
694     return Val->getZExtValue();
695   return 0;
696 }
697 
698 void Instruction::applyMergedLocation(const DILocation *LocA,
699                                       const DILocation *LocB) {
700   setDebugLoc(DILocation::getMergedLocation(LocA, LocB,
701                                             DILocation::WithGeneratedLocation));
702 }
703 
704 //===----------------------------------------------------------------------===//
705 // LLVM C API implementations.
706 //===----------------------------------------------------------------------===//
707 
708 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
709   switch (lang) {
710 #define HANDLE_DW_LANG(ID, NAME, VERSION, VENDOR) \
711 case LLVMDWARFSourceLanguage##NAME: return ID;
712 #include "llvm/BinaryFormat/Dwarf.def"
713 #undef HANDLE_DW_LANG
714   }
715   llvm_unreachable("Unhandled Tag");
716 }
717 
718 template <typename DIT> DIT *unwrapDI(LLVMMetadataRef Ref) {
719   return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
720 }
721 
722 static DINode::DIFlags map_from_llvmDIFlags(LLVMDIFlags Flags) {
723   return static_cast<DINode::DIFlags>(Flags);
724 }
725 
726 unsigned LLVMDebugMetadataVersion() {
727   return DEBUG_METADATA_VERSION;
728 }
729 
730 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
731   return wrap(new DIBuilder(*unwrap(M), false));
732 }
733 
734 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
735   return wrap(new DIBuilder(*unwrap(M)));
736 }
737 
738 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
739   return getDebugMetadataVersionFromModule(*unwrap(M));
740 }
741 
742 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
743   return StripDebugInfo(*unwrap(M));
744 }
745 
746 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
747   delete unwrap(Builder);
748 }
749 
750 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
751   unwrap(Builder)->finalize();
752 }
753 
754 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
755     LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
756     LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
757     LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
758     unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
759     LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
760     LLVMBool DebugInfoForProfiling) {
761   auto File = unwrapDI<DIFile>(FileRef);
762 
763   return wrap(unwrap(Builder)->createCompileUnit(
764                  map_from_llvmDWARFsourcelanguage(Lang), File,
765                  StringRef(Producer, ProducerLen), isOptimized,
766                  StringRef(Flags, FlagsLen), RuntimeVer,
767                  StringRef(SplitName, SplitNameLen),
768                  static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
769                  SplitDebugInlining, DebugInfoForProfiling));
770 }
771 
772 LLVMMetadataRef
773 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
774                         size_t FilenameLen, const char *Directory,
775                         size_t DirectoryLen) {
776   return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
777                                           StringRef(Directory, DirectoryLen)));
778 }
779 
780 LLVMMetadataRef LLVMDIBuilderCreateFunction(
781     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
782     size_t NameLen, const char *LinkageName, size_t LinkageNameLen,
783     LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty,
784     LLVMBool IsLocalToUnit, LLVMBool IsDefinition,
785     unsigned ScopeLine, LLVMDIFlags Flags, LLVMBool IsOptimized) {
786   return wrap(unwrap(Builder)->createFunction(
787       unwrapDI<DIScope>(Scope), {Name, NameLen}, {LinkageName, LinkageNameLen},
788       unwrapDI<DIFile>(File), LineNo, unwrapDI<DISubroutineType>(Ty),
789       IsLocalToUnit, IsDefinition, ScopeLine, map_from_llvmDIFlags(Flags),
790       IsOptimized, nullptr, nullptr, nullptr));
791 }
792 
793 
794 LLVMMetadataRef LLVMDIBuilderCreateLexicalBlock(
795     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope,
796     LLVMMetadataRef File, unsigned Line, unsigned Col) {
797   return wrap(unwrap(Builder)->createLexicalBlock(unwrapDI<DIScope>(Scope),
798                                                   unwrapDI<DIFile>(File),
799                                                   Line, Col));
800 }
801 
802 LLVMMetadataRef
803 LLVMDIBuilderCreateLexicalBlockFile(LLVMDIBuilderRef Builder,
804                                     LLVMMetadataRef Scope,
805                                     LLVMMetadataRef File,
806                                     unsigned Discriminator) {
807   return wrap(unwrap(Builder)->createLexicalBlockFile(unwrapDI<DIScope>(Scope),
808                                                       unwrapDI<DIFile>(File),
809                                                       Discriminator));
810 }
811 
812 LLVMMetadataRef
813 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
814                                  unsigned Column, LLVMMetadataRef Scope,
815                                  LLVMMetadataRef InlinedAt) {
816   return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
817                               unwrap(InlinedAt)));
818 }
819 
820 LLVMMetadataRef LLVMDIBuilderCreateEnumerationType(
821   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
822   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
823   unsigned SizeInBits, unsigned AlignInBits, LLVMMetadataRef *Elements,
824   unsigned NumElements, LLVMMetadataRef ClassTy) {
825 auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
826                                                NumElements});
827 return wrap(unwrap(Builder)->createEnumerationType(
828     unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
829     LineNumber, SizeInBits, AlignInBits, Elts, unwrapDI<DIType>(ClassTy)));
830 }
831 
832 LLVMMetadataRef LLVMDIBuilderCreateUnionType(
833   LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
834   size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
835   unsigned SizeInBits, unsigned AlignInBits, LLVMDIFlags Flags,
836   LLVMMetadataRef *Elements, unsigned NumElements, unsigned RunTimeLang,
837   const char *UniqueId, size_t UniqueIdLen) {
838   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
839                                                  NumElements});
840   return wrap(unwrap(Builder)->createUnionType(
841      unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
842      LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
843      Elts, RunTimeLang, {UniqueId, UniqueIdLen}));
844 }
845 
846 
847 LLVMMetadataRef
848 LLVMDIBuilderCreateArrayType(LLVMDIBuilderRef Builder, unsigned Size,
849                              unsigned AlignInBits, LLVMMetadataRef Ty,
850                              LLVMMetadataRef *Subscripts,
851                              unsigned NumSubscripts) {
852   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
853                                                  NumSubscripts});
854   return wrap(unwrap(Builder)->createArrayType(Size, AlignInBits,
855                                                unwrapDI<DIType>(Ty), Subs));
856 }
857 
858 LLVMMetadataRef
859 LLVMDIBuilderCreateVectorType(LLVMDIBuilderRef Builder, unsigned Size,
860                               unsigned AlignInBits, LLVMMetadataRef Ty,
861                               LLVMMetadataRef *Subscripts,
862                               unsigned NumSubscripts) {
863   auto Subs = unwrap(Builder)->getOrCreateArray({unwrap(Subscripts),
864                                                  NumSubscripts});
865   return wrap(unwrap(Builder)->createVectorType(Size, AlignInBits,
866                                                 unwrapDI<DIType>(Ty), Subs));
867 }
868 
869 LLVMMetadataRef
870 LLVMDIBuilderCreateBasicType(LLVMDIBuilderRef Builder, const char *Name,
871                              size_t NameLen, unsigned SizeInBits,
872                              LLVMDWARFTypeEncoding Encoding) {
873   return wrap(unwrap(Builder)->createBasicType({Name, NameLen},
874                                                SizeInBits, Encoding));
875 }
876 
877 LLVMMetadataRef LLVMDIBuilderCreatePointerType(
878     LLVMDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
879     unsigned SizeInBits, unsigned AlignInBits, unsigned AddressSpace,
880     const char *Name, size_t NameLen) {
881   return wrap(unwrap(Builder)->createPointerType(unwrapDI<DIType>(PointeeTy),
882                                          SizeInBits, AlignInBits,
883                                          AddressSpace, {Name, NameLen}));
884 }
885 
886 LLVMMetadataRef LLVMDIBuilderCreateStructType(
887     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
888     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
889     unsigned SizeInBits, unsigned AlignInBits, LLVMDIFlags Flags,
890     LLVMMetadataRef DerivedFrom, LLVMMetadataRef *Elements,
891     unsigned NumElements, unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
892     const char *UniqueId, size_t UniqueIdLen) {
893   auto Elts = unwrap(Builder)->getOrCreateArray({unwrap(Elements),
894                                                  NumElements});
895   return wrap(unwrap(Builder)->createStructType(
896       unwrapDI<DIScope>(Scope), {Name, NameLen}, unwrapDI<DIFile>(File),
897       LineNumber, SizeInBits, AlignInBits, map_from_llvmDIFlags(Flags),
898       unwrapDI<DIType>(DerivedFrom), Elts, RunTimeLang,
899       unwrapDI<DIType>(VTableHolder), {UniqueId, UniqueIdLen}));
900 }
901 
902 LLVMMetadataRef LLVMDIBuilderCreateMemberType(
903     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
904     size_t NameLen, LLVMMetadataRef File, unsigned LineNo, unsigned SizeInBits,
905     unsigned AlignInBits, unsigned OffsetInBits, LLVMDIFlags Flags,
906     LLVMMetadataRef Ty) {
907   return wrap(unwrap(Builder)->createMemberType(unwrapDI<DIScope>(Scope),
908       {Name, NameLen}, unwrapDI<DIFile>(File), LineNo, SizeInBits, AlignInBits,
909       OffsetInBits, map_from_llvmDIFlags(Flags), unwrapDI<DIType>(Ty)));
910 }
911 
912 LLVMMetadataRef
913 LLVMDIBuilderCreateUnspecifiedType(LLVMDIBuilderRef Builder, const char *Name,
914                                    size_t NameLen) {
915   return wrap(unwrap(Builder)->createUnspecifiedType({Name, NameLen}));
916 }
917 
918 LLVMMetadataRef
919 LLVMDIBuilderCreateStaticMemberType(
920     LLVMDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
921     size_t NameLen, LLVMMetadataRef File, unsigned LineNumber,
922     LLVMMetadataRef Type, LLVMDIFlags Flags, LLVMValueRef ConstantVal,
923     unsigned AlignInBits) {
924   return wrap(unwrap(Builder)->createStaticMemberType(
925                   unwrapDI<DIScope>(Scope), {Name, NameLen},
926                   unwrapDI<DIFile>(File), LineNumber, unwrapDI<DIType>(Type),
927                   map_from_llvmDIFlags(Flags), unwrap<Constant>(ConstantVal),
928                   AlignInBits));
929 }
930 
931 LLVMMetadataRef
932 LLVMDIBuilderCreateObjectPointerType(LLVMDIBuilderRef Builder,
933                                      LLVMMetadataRef Type) {
934   return wrap(unwrap(Builder)->createObjectPointerType(unwrapDI<DIType>(Type)));
935 }
936 
937 LLVMMetadataRef
938 LLVMDIBuilderCreateReplaceableCompositeType(
939     LLVMDIBuilderRef Builder, unsigned Tag, const char *Name,
940     size_t NameLen, LLVMMetadataRef Scope, LLVMMetadataRef File, unsigned Line,
941     unsigned RuntimeLang, unsigned SizeInBits, unsigned AlignInBits,
942     LLVMDIFlags Flags, const char *UniqueIdentifier,
943     size_t UniqueIdentifierLen) {
944   return wrap(unwrap(Builder)->createReplaceableCompositeType(
945                   Tag, {Name, NameLen}, unwrapDI<DIScope>(Scope),
946                   unwrapDI<DIFile>(File), Line, RuntimeLang, SizeInBits,
947                   AlignInBits, map_from_llvmDIFlags(Flags),
948                   {UniqueIdentifier, UniqueIdentifierLen}));
949 }
950 
951 LLVMMetadataRef
952 LLVMDIBuilderCreateQualifiedType(LLVMDIBuilderRef Builder, unsigned Tag,
953                                  LLVMMetadataRef Type) {
954   return wrap(unwrap(Builder)->createQualifiedType(Tag,
955                                                    unwrapDI<DIType>(Type)));
956 }
957 
958 LLVMMetadataRef
959 LLVMDIBuilderCreateReferenceType(LLVMDIBuilderRef Builder, unsigned Tag,
960                                  LLVMMetadataRef Type) {
961   return wrap(unwrap(Builder)->createReferenceType(Tag,
962                                                    unwrapDI<DIType>(Type)));
963 }
964 
965 LLVMMetadataRef
966 LLVMDIBuilderCreateNullPtrType(LLVMDIBuilderRef Builder) {
967   return wrap(unwrap(Builder)->createNullPtrType());
968 }
969 
970 LLVMMetadataRef
971 LLVMDIBuilderCreateMemberPointerType(LLVMDIBuilderRef Builder,
972                                      LLVMMetadataRef PointeeType,
973                                      LLVMMetadataRef ClassType,
974                                      unsigned SizeInBits,
975                                      unsigned AlignInBits,
976                                      LLVMDIFlags Flags) {
977   return wrap(unwrap(Builder)->createMemberPointerType(
978                   unwrapDI<DIType>(PointeeType),
979                   unwrapDI<DIType>(ClassType), AlignInBits, SizeInBits,
980                   map_from_llvmDIFlags(Flags)));
981 }
982 
983 LLVMMetadataRef
984 LLVMDIBuilderCreateArtificialType(LLVMDIBuilderRef Builder,
985                                   LLVMMetadataRef Type) {
986   return wrap(unwrap(Builder)->createArtificialType(unwrapDI<DIType>(Type)));
987 }
988 
989 LLVMMetadataRef
990 LLVMDIBuilderCreateSubroutineType(LLVMDIBuilderRef Builder,
991                                   LLVMMetadataRef File,
992                                   LLVMMetadataRef *ParameterTypes,
993                                   unsigned NumParameterTypes,
994                                   LLVMDIFlags Flags) {
995   auto Elts = unwrap(Builder)->getOrCreateTypeArray({unwrap(ParameterTypes),
996                                                      NumParameterTypes});
997   return wrap(unwrap(Builder)->createSubroutineType(
998     Elts, map_from_llvmDIFlags(Flags)));
999 }
1000 
1001 LLVMMetadataRef LLVMGetSubprogram(LLVMValueRef Func) {
1002   return wrap(unwrap<Function>(Func)->getSubprogram());
1003 }
1004 
1005 void LLVMSetSubprogram(LLVMValueRef Func, LLVMMetadataRef SP) {
1006   unwrap<Function>(Func)->setSubprogram(unwrap<DISubprogram>(SP));
1007 }
1008