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 "LLVMContextImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GVMaterializer.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Support/Casting.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <utility>
41 
42 using namespace llvm;
43 using namespace llvm::dwarf;
44 
45 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
46   if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
47     return LocalScope->getSubprogram();
48   return nullptr;
49 }
50 
51 //===----------------------------------------------------------------------===//
52 // DebugInfoFinder implementations.
53 //===----------------------------------------------------------------------===//
54 
55 void DebugInfoFinder::reset() {
56   CUs.clear();
57   SPs.clear();
58   GVs.clear();
59   TYs.clear();
60   Scopes.clear();
61   NodesSeen.clear();
62 }
63 
64 void DebugInfoFinder::processModule(const Module &M) {
65   for (auto *CU : M.debug_compile_units()) {
66     addCompileUnit(CU);
67     for (auto DIG : CU->getGlobalVariables()) {
68       if (!addGlobalVariable(DIG))
69         continue;
70       auto *GV = DIG->getVariable();
71       processScope(GV->getScope());
72       processType(GV->getType().resolve());
73     }
74     for (auto *ET : CU->getEnumTypes())
75       processType(ET);
76     for (auto *RT : CU->getRetainedTypes())
77       if (auto *T = dyn_cast<DIType>(RT))
78         processType(T);
79       else
80         processSubprogram(cast<DISubprogram>(RT));
81     for (auto *Import : CU->getImportedEntities()) {
82       auto *Entity = Import->getEntity().resolve();
83       if (auto *T = dyn_cast<DIType>(Entity))
84         processType(T);
85       else if (auto *SP = dyn_cast<DISubprogram>(Entity))
86         processSubprogram(SP);
87       else if (auto *NS = dyn_cast<DINamespace>(Entity))
88         processScope(NS->getScope());
89       else if (auto *M = dyn_cast<DIModule>(Entity))
90         processScope(M->getScope());
91     }
92   }
93   for (auto &F : M.functions()) {
94     if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
95       processSubprogram(SP);
96     // There could be subprograms from inlined functions referenced from
97     // instructions only. Walk the function to find them.
98     for (const BasicBlock &BB : F) {
99       for (const Instruction &I : BB) {
100         if (!I.getDebugLoc())
101           continue;
102         processLocation(M, I.getDebugLoc().get());
103       }
104     }
105   }
106 }
107 
108 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
109   if (!Loc)
110     return;
111   processScope(Loc->getScope());
112   processLocation(M, Loc->getInlinedAt());
113 }
114 
115 void DebugInfoFinder::processType(DIType *DT) {
116   if (!addType(DT))
117     return;
118   processScope(DT->getScope().resolve());
119   if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
120     for (DITypeRef Ref : ST->getTypeArray())
121       processType(Ref.resolve());
122     return;
123   }
124   if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
125     processType(DCT->getBaseType().resolve());
126     for (Metadata *D : DCT->getElements()) {
127       if (auto *T = dyn_cast<DIType>(D))
128         processType(T);
129       else if (auto *SP = dyn_cast<DISubprogram>(D))
130         processSubprogram(SP);
131     }
132     return;
133   }
134   if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
135     processType(DDT->getBaseType().resolve());
136   }
137 }
138 
139 void DebugInfoFinder::processScope(DIScope *Scope) {
140   if (!Scope)
141     return;
142   if (auto *Ty = dyn_cast<DIType>(Scope)) {
143     processType(Ty);
144     return;
145   }
146   if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
147     addCompileUnit(CU);
148     return;
149   }
150   if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
151     processSubprogram(SP);
152     return;
153   }
154   if (!addScope(Scope))
155     return;
156   if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
157     processScope(LB->getScope());
158   } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
159     processScope(NS->getScope());
160   } else if (auto *M = dyn_cast<DIModule>(Scope)) {
161     processScope(M->getScope());
162   }
163 }
164 
165 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
166   if (!addSubprogram(SP))
167     return;
168   processScope(SP->getScope().resolve());
169   processType(SP->getType());
170   for (auto *Element : SP->getTemplateParams()) {
171     if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
172       processType(TType->getType().resolve());
173     } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
174       processType(TVal->getType().resolve());
175     }
176   }
177 }
178 
179 void DebugInfoFinder::processDeclare(const Module &M,
180                                      const DbgDeclareInst *DDI) {
181   auto *N = dyn_cast<MDNode>(DDI->getVariable());
182   if (!N)
183     return;
184 
185   auto *DV = dyn_cast<DILocalVariable>(N);
186   if (!DV)
187     return;
188 
189   if (!NodesSeen.insert(DV).second)
190     return;
191   processScope(DV->getScope());
192   processType(DV->getType().resolve());
193 }
194 
195 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
196   auto *N = dyn_cast<MDNode>(DVI->getVariable());
197   if (!N)
198     return;
199 
200   auto *DV = dyn_cast<DILocalVariable>(N);
201   if (!DV)
202     return;
203 
204   if (!NodesSeen.insert(DV).second)
205     return;
206   processScope(DV->getScope());
207   processType(DV->getType().resolve());
208 }
209 
210 bool DebugInfoFinder::addType(DIType *DT) {
211   if (!DT)
212     return false;
213 
214   if (!NodesSeen.insert(DT).second)
215     return false;
216 
217   TYs.push_back(const_cast<DIType *>(DT));
218   return true;
219 }
220 
221 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
222   if (!CU)
223     return false;
224   if (!NodesSeen.insert(CU).second)
225     return false;
226 
227   CUs.push_back(CU);
228   return true;
229 }
230 
231 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
232   if (!NodesSeen.insert(DIG).second)
233     return false;
234 
235   GVs.push_back(DIG);
236   return true;
237 }
238 
239 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
240   if (!SP)
241     return false;
242 
243   if (!NodesSeen.insert(SP).second)
244     return false;
245 
246   SPs.push_back(SP);
247   return true;
248 }
249 
250 bool DebugInfoFinder::addScope(DIScope *Scope) {
251   if (!Scope)
252     return false;
253   // FIXME: Ocaml binding generates a scope with no content, we treat it
254   // as null for now.
255   if (Scope->getNumOperands() == 0)
256     return false;
257   if (!NodesSeen.insert(Scope).second)
258     return false;
259   Scopes.push_back(Scope);
260   return true;
261 }
262 
263 static MDNode *stripDebugLocFromLoopID(MDNode *N) {
264   assert(N->op_begin() != N->op_end() && "Missing self reference?");
265 
266   // if there is no debug location, we do not have to rewrite this MDNode.
267   if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
268         return isa<DILocation>(Op.get());
269       }))
270     return N;
271 
272   // If there is only the debug location without any actual loop metadata, we
273   // can remove the metadata.
274   if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
275         return !isa<DILocation>(Op.get());
276       }))
277     return nullptr;
278 
279   SmallVector<Metadata *, 4> Args;
280   // Reserve operand 0 for loop id self reference.
281   auto TempNode = MDNode::getTemporary(N->getContext(), None);
282   Args.push_back(TempNode.get());
283   // Add all non-debug location operands back.
284   for (auto Op = N->op_begin() + 1; Op != N->op_end(); Op++) {
285     if (!isa<DILocation>(*Op))
286       Args.push_back(*Op);
287   }
288 
289   // Set the first operand to itself.
290   MDNode *LoopID = MDNode::get(N->getContext(), Args);
291   LoopID->replaceOperandWith(0, LoopID);
292   return LoopID;
293 }
294 
295 bool llvm::stripDebugInfo(Function &F) {
296   bool Changed = false;
297   if (F.getMetadata(LLVMContext::MD_dbg)) {
298     Changed = true;
299     F.setSubprogram(nullptr);
300   }
301 
302   DenseMap<MDNode*, MDNode*> LoopIDsMap;
303   for (BasicBlock &BB : F) {
304     for (auto II = BB.begin(), End = BB.end(); II != End;) {
305       Instruction &I = *II++; // We may delete the instruction, increment now.
306       if (isa<DbgInfoIntrinsic>(&I)) {
307         I.eraseFromParent();
308         Changed = true;
309         continue;
310       }
311       if (I.getDebugLoc()) {
312         Changed = true;
313         I.setDebugLoc(DebugLoc());
314       }
315     }
316 
317     auto *TermInst = BB.getTerminator();
318     if (!TermInst)
319       // This is invalid IR, but we may not have run the verifier yet
320       continue;
321     if (auto *LoopID = TermInst->getMetadata(LLVMContext::MD_loop)) {
322       auto *NewLoopID = LoopIDsMap.lookup(LoopID);
323       if (!NewLoopID)
324         NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
325       if (NewLoopID != LoopID)
326         TermInst->setMetadata(LLVMContext::MD_loop, NewLoopID);
327     }
328   }
329   return Changed;
330 }
331 
332 bool llvm::StripDebugInfo(Module &M) {
333   bool Changed = false;
334 
335   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
336          NME = M.named_metadata_end(); NMI != NME;) {
337     NamedMDNode *NMD = &*NMI;
338     ++NMI;
339 
340     // We're stripping debug info, and without them, coverage information
341     // doesn't quite make sense.
342     if (NMD->getName().startswith("llvm.dbg.") ||
343         NMD->getName() == "llvm.gcov") {
344       NMD->eraseFromParent();
345       Changed = true;
346     }
347   }
348 
349   for (Function &F : M)
350     Changed |= stripDebugInfo(F);
351 
352   for (auto &GV : M.globals()) {
353     SmallVector<MDNode *, 1> MDs;
354     GV.getMetadata(LLVMContext::MD_dbg, MDs);
355     if (!MDs.empty()) {
356       GV.eraseMetadata(LLVMContext::MD_dbg);
357       Changed = true;
358     }
359   }
360 
361   if (GVMaterializer *Materializer = M.getMaterializer())
362     Materializer->setStripDebugInfo();
363 
364   return Changed;
365 }
366 
367 namespace {
368 
369 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
370 class DebugTypeInfoRemoval {
371   DenseMap<Metadata *, Metadata *> Replacements;
372 
373 public:
374   /// The (void)() type.
375   MDNode *EmptySubroutineType;
376 
377 private:
378   /// Remember what linkage name we originally had before stripping. If we end
379   /// up making two subprograms identical who originally had different linkage
380   /// names, then we need to make one of them distinct, to avoid them getting
381   /// uniqued. Maps the new node to the old linkage name.
382   DenseMap<DISubprogram *, StringRef> NewToLinkageName;
383 
384   // TODO: Remember the distinct subprogram we created for a given linkage name,
385   // so that we can continue to unique whenever possible. Map <newly created
386   // node, old linkage name> to the first (possibly distinct) mdsubprogram
387   // created for that combination. This is not strictly needed for correctness,
388   // but can cut down on the number of MDNodes and let us diff cleanly with the
389   // output of -gline-tables-only.
390 
391 public:
392   DebugTypeInfoRemoval(LLVMContext &C)
393       : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
394                                                   MDNode::get(C, {}))) {}
395 
396   Metadata *map(Metadata *M) {
397     if (!M)
398       return nullptr;
399     auto Replacement = Replacements.find(M);
400     if (Replacement != Replacements.end())
401       return Replacement->second;
402 
403     return M;
404   }
405   MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
406 
407   /// Recursively remap N and all its referenced children. Does a DF post-order
408   /// traversal, so as to remap bottoms up.
409   void traverseAndRemap(MDNode *N) { traverse(N); }
410 
411 private:
412   // Create a new DISubprogram, to replace the one given.
413   DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
414     auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
415     StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
416     DISubprogram *Declaration = nullptr;
417     auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
418     DITypeRef ContainingType(map(MDS->getContainingType()));
419     auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
420     auto Variables = nullptr;
421     auto TemplateParams = nullptr;
422 
423     // Make a distinct DISubprogram, for situations that warrent it.
424     auto distinctMDSubprogram = [&]() {
425       return DISubprogram::getDistinct(
426           MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
427           FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
428           MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
429           MDS->getVirtuality(), MDS->getVirtualIndex(),
430           MDS->getThisAdjustment(), MDS->getFlags(), MDS->isOptimized(), Unit,
431           TemplateParams, Declaration, Variables);
432     };
433 
434     if (MDS->isDistinct())
435       return distinctMDSubprogram();
436 
437     auto *NewMDS = DISubprogram::get(
438         MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
439         FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
440         MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
441         MDS->getVirtuality(), MDS->getVirtualIndex(), MDS->getThisAdjustment(),
442         MDS->getFlags(), MDS->isOptimized(), Unit, TemplateParams, Declaration,
443         Variables);
444 
445     StringRef OldLinkageName = MDS->getLinkageName();
446 
447     // See if we need to make a distinct one.
448     auto OrigLinkage = NewToLinkageName.find(NewMDS);
449     if (OrigLinkage != NewToLinkageName.end()) {
450       if (OrigLinkage->second == OldLinkageName)
451         // We're good.
452         return NewMDS;
453 
454       // Otherwise, need to make a distinct one.
455       // TODO: Query the map to see if we already have one.
456       return distinctMDSubprogram();
457     }
458 
459     NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
460     return NewMDS;
461   }
462 
463   /// Create a new compile unit, to replace the one given
464   DICompileUnit *getReplacementCU(DICompileUnit *CU) {
465     // Drop skeleton CUs.
466     if (CU->getDWOId())
467       return nullptr;
468 
469     auto *File = cast_or_null<DIFile>(map(CU->getFile()));
470     MDTuple *EnumTypes = nullptr;
471     MDTuple *RetainedTypes = nullptr;
472     MDTuple *GlobalVariables = nullptr;
473     MDTuple *ImportedEntities = nullptr;
474     return DICompileUnit::getDistinct(
475         CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
476         CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
477         CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
478         RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
479         CU->getDWOId(), CU->getSplitDebugInlining(),
480         CU->getDebugInfoForProfiling(), CU->getGnuPubnames());
481   }
482 
483   DILocation *getReplacementMDLocation(DILocation *MLD) {
484     auto *Scope = map(MLD->getScope());
485     auto *InlinedAt = map(MLD->getInlinedAt());
486     if (MLD->isDistinct())
487       return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
488                                      MLD->getColumn(), Scope, InlinedAt);
489     return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
490                            Scope, InlinedAt);
491   }
492 
493   /// Create a new generic MDNode, to replace the one given
494   MDNode *getReplacementMDNode(MDNode *N) {
495     SmallVector<Metadata *, 8> Ops;
496     Ops.reserve(N->getNumOperands());
497     for (auto &I : N->operands())
498       if (I)
499         Ops.push_back(map(I));
500     auto *Ret = MDNode::get(N->getContext(), Ops);
501     return Ret;
502   }
503 
504   /// Attempt to re-map N to a newly created node.
505   void remap(MDNode *N) {
506     if (Replacements.count(N))
507       return;
508 
509     auto doRemap = [&](MDNode *N) -> MDNode * {
510       if (!N)
511         return nullptr;
512       if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
513         remap(MDSub->getUnit());
514         return getReplacementSubprogram(MDSub);
515       }
516       if (isa<DISubroutineType>(N))
517         return EmptySubroutineType;
518       if (auto *CU = dyn_cast<DICompileUnit>(N))
519         return getReplacementCU(CU);
520       if (isa<DIFile>(N))
521         return N;
522       if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
523         // Remap to our referenced scope (recursively).
524         return mapNode(MDLB->getScope());
525       if (auto *MLD = dyn_cast<DILocation>(N))
526         return getReplacementMDLocation(MLD);
527 
528       // Otherwise, if we see these, just drop them now. Not strictly necessary,
529       // but this speeds things up a little.
530       if (isa<DINode>(N))
531         return nullptr;
532 
533       return getReplacementMDNode(N);
534     };
535     Replacements[N] = doRemap(N);
536   }
537 
538   /// Do the remapping traversal.
539   void traverse(MDNode *);
540 };
541 
542 } // end anonymous namespace
543 
544 void DebugTypeInfoRemoval::traverse(MDNode *N) {
545   if (!N || Replacements.count(N))
546     return;
547 
548   // To avoid cycles, as well as for efficiency sake, we will sometimes prune
549   // parts of the graph.
550   auto prune = [](MDNode *Parent, MDNode *Child) {
551     if (auto *MDS = dyn_cast<DISubprogram>(Parent))
552       return Child == MDS->getVariables().get();
553     return false;
554   };
555 
556   SmallVector<MDNode *, 16> ToVisit;
557   DenseSet<MDNode *> Opened;
558 
559   // Visit each node starting at N in post order, and map them.
560   ToVisit.push_back(N);
561   while (!ToVisit.empty()) {
562     auto *N = ToVisit.back();
563     if (!Opened.insert(N).second) {
564       // Close it.
565       remap(N);
566       ToVisit.pop_back();
567       continue;
568     }
569     for (auto &I : N->operands())
570       if (auto *MDN = dyn_cast_or_null<MDNode>(I))
571         if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
572             !isa<DICompileUnit>(MDN))
573           ToVisit.push_back(MDN);
574   }
575 }
576 
577 bool llvm::stripNonLineTableDebugInfo(Module &M) {
578   bool Changed = false;
579 
580   // First off, delete the debug intrinsics.
581   auto RemoveUses = [&](StringRef Name) {
582     if (auto *DbgVal = M.getFunction(Name)) {
583       while (!DbgVal->use_empty())
584         cast<Instruction>(DbgVal->user_back())->eraseFromParent();
585       DbgVal->eraseFromParent();
586       Changed = true;
587     }
588   };
589   RemoveUses("llvm.dbg.declare");
590   RemoveUses("llvm.dbg.value");
591 
592   // Delete non-CU debug info named metadata nodes.
593   for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
594        NMI != NME;) {
595     NamedMDNode *NMD = &*NMI;
596     ++NMI;
597     // Specifically keep dbg.cu around.
598     if (NMD->getName() == "llvm.dbg.cu")
599       continue;
600   }
601 
602   // Drop all dbg attachments from global variables.
603   for (auto &GV : M.globals())
604     GV.eraseMetadata(LLVMContext::MD_dbg);
605 
606   DebugTypeInfoRemoval Mapper(M.getContext());
607   auto remap = [&](MDNode *Node) -> MDNode * {
608     if (!Node)
609       return nullptr;
610     Mapper.traverseAndRemap(Node);
611     auto *NewNode = Mapper.mapNode(Node);
612     Changed |= Node != NewNode;
613     Node = NewNode;
614     return NewNode;
615   };
616 
617   // Rewrite the DebugLocs to be equivalent to what
618   // -gline-tables-only would have created.
619   for (auto &F : M) {
620     if (auto *SP = F.getSubprogram()) {
621       Mapper.traverseAndRemap(SP);
622       auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
623       Changed |= SP != NewSP;
624       F.setSubprogram(NewSP);
625     }
626     for (auto &BB : F) {
627       for (auto &I : BB) {
628         auto remapDebugLoc = [&](DebugLoc DL) -> DebugLoc {
629           auto *Scope = DL.getScope();
630           MDNode *InlinedAt = DL.getInlinedAt();
631           Scope = remap(Scope);
632           InlinedAt = remap(InlinedAt);
633           return DebugLoc::get(DL.getLine(), DL.getCol(), Scope, InlinedAt);
634         };
635 
636         if (I.getDebugLoc() != DebugLoc())
637           I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
638 
639         // Remap DILocations in untyped MDNodes (e.g., llvm.loop).
640         SmallVector<std::pair<unsigned, MDNode *>, 2> MDs;
641         I.getAllMetadata(MDs);
642         for (auto Attachment : MDs)
643           if (auto *T = dyn_cast_or_null<MDTuple>(Attachment.second))
644             for (unsigned N = 0; N < T->getNumOperands(); ++N)
645               if (auto *Loc = dyn_cast_or_null<DILocation>(T->getOperand(N)))
646                 if (Loc != DebugLoc())
647                   T->replaceOperandWith(N, remapDebugLoc(Loc));
648       }
649     }
650   }
651 
652   // Create a new llvm.dbg.cu, which is equivalent to the one
653   // -gline-tables-only would have created.
654   for (auto &NMD : M.getNamedMDList()) {
655     SmallVector<MDNode *, 8> Ops;
656     for (MDNode *Op : NMD.operands())
657       Ops.push_back(remap(Op));
658 
659     if (!Changed)
660       continue;
661 
662     NMD.clearOperands();
663     for (auto *Op : Ops)
664       if (Op)
665         NMD.addOperand(Op);
666   }
667   return Changed;
668 }
669 
670 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
671   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
672           M.getModuleFlag("Debug Info Version")))
673     return Val->getZExtValue();
674   return 0;
675 }
676 
677 void Instruction::applyMergedLocation(const DILocation *LocA,
678                                       const DILocation *LocB) {
679   setDebugLoc(DILocation::getMergedLocation(LocA, LocB, this));
680 }
681 
682 //===----------------------------------------------------------------------===//
683 // LLVM C API implementations.
684 //===----------------------------------------------------------------------===//
685 
686 static unsigned map_from_llvmDWARFsourcelanguage(LLVMDWARFSourceLanguage lang) {
687   switch (lang) {
688 #define HANDLE_DW_LANG(ID, NAME, VERSION, VENDOR) \
689 case LLVMDWARFSourceLanguage##NAME: return ID;
690 #include "llvm/BinaryFormat/Dwarf.def"
691 #undef HANDLE_DW_LANG
692   }
693   llvm_unreachable("Unhandled Tag");
694 }
695 
696 unsigned LLVMDebugMetadataVersion() {
697   return DEBUG_METADATA_VERSION;
698 }
699 
700 LLVMDIBuilderRef LLVMCreateDIBuilderDisallowUnresolved(LLVMModuleRef M) {
701   return wrap(new DIBuilder(*unwrap(M), false));
702 }
703 
704 LLVMDIBuilderRef LLVMCreateDIBuilder(LLVMModuleRef M) {
705   return wrap(new DIBuilder(*unwrap(M)));
706 }
707 
708 unsigned LLVMGetModuleDebugMetadataVersion(LLVMModuleRef M) {
709   return getDebugMetadataVersionFromModule(*unwrap(M));
710 }
711 
712 LLVMBool LLVMStripModuleDebugInfo(LLVMModuleRef M) {
713   return StripDebugInfo(*unwrap(M));
714 }
715 
716 void LLVMDisposeDIBuilder(LLVMDIBuilderRef Builder) {
717   delete unwrap(Builder);
718 }
719 
720 void LLVMDIBuilderFinalize(LLVMDIBuilderRef Builder) {
721   unwrap(Builder)->finalize();
722 }
723 
724 LLVMMetadataRef LLVMDIBuilderCreateCompileUnit(
725     LLVMDIBuilderRef Builder, LLVMDWARFSourceLanguage Lang,
726     LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen,
727     LLVMBool isOptimized, const char *Flags, size_t FlagsLen,
728     unsigned RuntimeVer, const char *SplitName, size_t SplitNameLen,
729     LLVMDWARFEmissionKind Kind, unsigned DWOId, LLVMBool SplitDebugInlining,
730     LLVMBool DebugInfoForProfiling) {
731   auto File = unwrap<DIFile>(FileRef);
732 
733   return wrap(unwrap(Builder)->createCompileUnit(
734                  map_from_llvmDWARFsourcelanguage(Lang), File,
735                  StringRef(Producer, ProducerLen), isOptimized,
736                  StringRef(Flags, FlagsLen), RuntimeVer,
737                  StringRef(SplitName, SplitNameLen),
738                  static_cast<DICompileUnit::DebugEmissionKind>(Kind), DWOId,
739                  SplitDebugInlining, DebugInfoForProfiling));
740 }
741 
742 LLVMMetadataRef
743 LLVMDIBuilderCreateFile(LLVMDIBuilderRef Builder, const char *Filename,
744                         size_t FilenameLen, const char *Directory,
745                         size_t DirectoryLen) {
746   return wrap(unwrap(Builder)->createFile(StringRef(Filename, FilenameLen),
747                                           StringRef(Directory, DirectoryLen)));
748 }
749 
750 LLVMMetadataRef
751 LLVMDIBuilderCreateDebugLocation(LLVMContextRef Ctx, unsigned Line,
752                                  unsigned Column, LLVMMetadataRef Scope,
753                                  LLVMMetadataRef InlinedAt) {
754   return wrap(DILocation::get(*unwrap(Ctx), Line, Column, unwrap(Scope),
755                               unwrap(InlinedAt)));
756 }
757