1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 coordinates the debug information generation while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "CGBlocks.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Target/TargetData.h"
38 using namespace clang;
39 using namespace clang::CodeGen;
40 
41 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
42   : CGM(CGM), DBuilder(CGM.getModule()),
43     BlockLiteralGenericSet(false) {
44   CreateCompileUnit();
45 }
46 
47 CGDebugInfo::~CGDebugInfo() {
48   assert(LexicalBlockStack.empty() &&
49          "Region stack mismatch, stack not empty!");
50 }
51 
52 void CGDebugInfo::setLocation(SourceLocation Loc) {
53   // If the new location isn't valid return.
54   if (!Loc.isValid()) return;
55 
56   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
57 
58   // If we've changed files in the middle of a lexical scope go ahead
59   // and create a new lexical scope with file node if it's different
60   // from the one in the scope.
61   if (LexicalBlockStack.empty()) return;
62 
63   SourceManager &SM = CGM.getContext().getSourceManager();
64   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
65   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
66 
67   if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
68       !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
69     return;
70 
71   llvm::MDNode *LB = LexicalBlockStack.back();
72   llvm::DIScope Scope = llvm::DIScope(LB);
73   if (Scope.isLexicalBlockFile()) {
74     llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
75     llvm::DIDescriptor D
76       = DBuilder.createLexicalBlockFile(LBF.getScope(),
77                                         getOrCreateFile(CurLoc));
78     llvm::MDNode *N = D;
79     LexicalBlockStack.pop_back();
80     LexicalBlockStack.push_back(N);
81   } else if (Scope.isLexicalBlock()) {
82     llvm::DIDescriptor D
83       = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
84     llvm::MDNode *N = D;
85     LexicalBlockStack.pop_back();
86     LexicalBlockStack.push_back(N);
87   }
88 }
89 
90 /// getContextDescriptor - Get context info for the decl.
91 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
92   if (!Context)
93     return TheCU;
94 
95   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
96     I = RegionMap.find(Context);
97   if (I != RegionMap.end())
98     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
99 
100   // Check namespace.
101   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
102     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
103 
104   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
105     if (!RDecl->isDependentType()) {
106       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
107                                         getOrCreateMainFile());
108       return llvm::DIDescriptor(Ty);
109     }
110   }
111   return TheCU;
112 }
113 
114 /// getFunctionName - Get function name for the given FunctionDecl. If the
115 /// name is constructred on demand (e.g. C++ destructor) then the name
116 /// is stored on the side.
117 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
118   assert (FD && "Invalid FunctionDecl!");
119   IdentifierInfo *FII = FD->getIdentifier();
120   if (FII)
121     return FII->getName();
122 
123   // Otherwise construct human readable name for debug info.
124   std::string NS = FD->getNameAsString();
125 
126   // Copy this name on the side and use its reference.
127   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
128   memcpy(StrPtr, NS.data(), NS.length());
129   return StringRef(StrPtr, NS.length());
130 }
131 
132 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
133   SmallString<256> MethodName;
134   llvm::raw_svector_ostream OS(MethodName);
135   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
136   const DeclContext *DC = OMD->getDeclContext();
137   if (const ObjCImplementationDecl *OID =
138       dyn_cast<const ObjCImplementationDecl>(DC)) {
139      OS << OID->getName();
140   } else if (const ObjCInterfaceDecl *OID =
141              dyn_cast<const ObjCInterfaceDecl>(DC)) {
142       OS << OID->getName();
143   } else if (const ObjCCategoryImplDecl *OCD =
144              dyn_cast<const ObjCCategoryImplDecl>(DC)){
145       OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
146           OCD->getIdentifier()->getNameStart() << ')';
147   }
148   OS << ' ' << OMD->getSelector().getAsString() << ']';
149 
150   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
151   memcpy(StrPtr, MethodName.begin(), OS.tell());
152   return StringRef(StrPtr, OS.tell());
153 }
154 
155 /// getSelectorName - Return selector name. This is used for debugging
156 /// info.
157 StringRef CGDebugInfo::getSelectorName(Selector S) {
158   const std::string &SName = S.getAsString();
159   char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
160   memcpy(StrPtr, SName.data(), SName.size());
161   return StringRef(StrPtr, SName.size());
162 }
163 
164 /// getClassName - Get class name including template argument list.
165 StringRef
166 CGDebugInfo::getClassName(const RecordDecl *RD) {
167   const ClassTemplateSpecializationDecl *Spec
168     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
169   if (!Spec)
170     return RD->getName();
171 
172   const TemplateArgument *Args;
173   unsigned NumArgs;
174   std::string Buffer;
175   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
176     const TemplateSpecializationType *TST =
177       cast<TemplateSpecializationType>(TAW->getType());
178     Args = TST->getArgs();
179     NumArgs = TST->getNumArgs();
180   } else {
181     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
182     Args = TemplateArgs.data();
183     NumArgs = TemplateArgs.size();
184   }
185   Buffer = RD->getIdentifier()->getNameStart();
186   PrintingPolicy Policy(CGM.getLangOptions());
187   Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
188                                                                   NumArgs,
189                                                                   Policy);
190 
191   // Copy this name on the side and use its reference.
192   char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
193   memcpy(StrPtr, Buffer.data(), Buffer.length());
194   return StringRef(StrPtr, Buffer.length());
195 }
196 
197 /// getOrCreateFile - Get the file debug info descriptor for the input location.
198 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
199   if (!Loc.isValid())
200     // If Location is not valid then use main input file.
201     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
202 
203   SourceManager &SM = CGM.getContext().getSourceManager();
204   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
205 
206   if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
207     // If the location is not valid then use main input file.
208     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
209 
210   // Cache the results.
211   const char *fname = PLoc.getFilename();
212   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
213     DIFileCache.find(fname);
214 
215   if (it != DIFileCache.end()) {
216     // Verify that the information still exists.
217     if (&*it->second)
218       return llvm::DIFile(cast<llvm::MDNode>(it->second));
219   }
220 
221   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
222 
223   DIFileCache[fname] = F;
224   return F;
225 }
226 
227 /// getOrCreateMainFile - Get the file info for main compile unit.
228 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
229   return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
230 }
231 
232 /// getLineNumber - Get line number for the location. If location is invalid
233 /// then use current location.
234 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
235   if (Loc.isInvalid() && CurLoc.isInvalid())
236     return 0;
237   SourceManager &SM = CGM.getContext().getSourceManager();
238   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
239   return PLoc.isValid()? PLoc.getLine() : 0;
240 }
241 
242 /// getColumnNumber - Get column number for the location. If location is
243 /// invalid then use current location.
244 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
245   if (Loc.isInvalid() && CurLoc.isInvalid())
246     return 0;
247   SourceManager &SM = CGM.getContext().getSourceManager();
248   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
249   return PLoc.isValid()? PLoc.getColumn() : 0;
250 }
251 
252 StringRef CGDebugInfo::getCurrentDirname() {
253   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
254     return CGM.getCodeGenOpts().DebugCompilationDir;
255 
256   if (!CWDName.empty())
257     return CWDName;
258   SmallString<256> CWD;
259   llvm::sys::fs::current_path(CWD);
260   char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
261   memcpy(CompDirnamePtr, CWD.data(), CWD.size());
262   return CWDName = StringRef(CompDirnamePtr, CWD.size());
263 }
264 
265 /// CreateCompileUnit - Create new compile unit.
266 void CGDebugInfo::CreateCompileUnit() {
267 
268   // Get absolute path name.
269   SourceManager &SM = CGM.getContext().getSourceManager();
270   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
271   if (MainFileName.empty())
272     MainFileName = "<unknown>";
273 
274   // The main file name provided via the "-main-file-name" option contains just
275   // the file name itself with no path information. This file name may have had
276   // a relative path, so we look into the actual file entry for the main
277   // file to determine the real absolute path for the file.
278   std::string MainFileDir;
279   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
280     MainFileDir = MainFile->getDir()->getName();
281     if (MainFileDir != ".")
282       MainFileName = MainFileDir + "/" + MainFileName;
283   }
284 
285   // Save filename string.
286   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
287   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
288   StringRef Filename(FilenamePtr, MainFileName.length());
289 
290   unsigned LangTag;
291   const LangOptions &LO = CGM.getLangOptions();
292   if (LO.CPlusPlus) {
293     if (LO.ObjC1)
294       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
295     else
296       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
297   } else if (LO.ObjC1) {
298     LangTag = llvm::dwarf::DW_LANG_ObjC;
299   } else if (LO.C99) {
300     LangTag = llvm::dwarf::DW_LANG_C99;
301   } else {
302     LangTag = llvm::dwarf::DW_LANG_C89;
303   }
304 
305   std::string Producer = getClangFullVersion();
306 
307   // Figure out which version of the ObjC runtime we have.
308   unsigned RuntimeVers = 0;
309   if (LO.ObjC1)
310     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
311 
312   // Create new compile unit.
313   DBuilder.createCompileUnit(
314     LangTag, Filename, getCurrentDirname(),
315     Producer,
316     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
317   // FIXME - Eliminate TheCU.
318   TheCU = llvm::DICompileUnit(DBuilder.getCU());
319 }
320 
321 /// CreateType - Get the Basic type from the cache or create a new
322 /// one if necessary.
323 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
324   unsigned Encoding = 0;
325   const char *BTName = NULL;
326   switch (BT->getKind()) {
327 #define BUILTIN_TYPE(Id, SingletonId)
328 #define PLACEHOLDER_TYPE(Id, SingletonId) \
329   case BuiltinType::Id:
330 #include "clang/AST/BuiltinTypes.def"
331   case BuiltinType::Dependent:
332     llvm_unreachable("Unexpected builtin type");
333   case BuiltinType::NullPtr:
334     return DBuilder.
335       createNullPtrType(BT->getName(CGM.getContext().getLangOptions()));
336   case BuiltinType::Void:
337     return llvm::DIType();
338   case BuiltinType::ObjCClass:
339     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
340                                       "objc_class", getOrCreateMainFile(),
341                                       0);
342   case BuiltinType::ObjCId: {
343     // typedef struct objc_class *Class;
344     // typedef struct objc_object {
345     //  Class isa;
346     // } *id;
347 
348     // TODO: Cache these two types to avoid duplicates.
349     llvm::DIType OCTy =
350       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
351                                  "objc_class", getOrCreateMainFile(),
352                                  0);
353     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
354 
355     llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
356 
357     SmallVector<llvm::Value *, 16> EltTys;
358     llvm::DIType FieldTy =
359       DBuilder.createMemberType(getOrCreateMainFile(), "isa",
360                                 getOrCreateMainFile(), 0, Size,
361                                 0, 0, 0, ISATy);
362     EltTys.push_back(FieldTy);
363     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
364 
365     return DBuilder.createStructType(TheCU, "objc_object",
366                                      getOrCreateMainFile(),
367                                      0, 0, 0, 0, Elements);
368   }
369   case BuiltinType::ObjCSel: {
370     return
371       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
372                                  "objc_selector", getOrCreateMainFile(),
373                                  0);
374   }
375   case BuiltinType::UChar:
376   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
377   case BuiltinType::Char_S:
378   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
379   case BuiltinType::Char16:
380   case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
381   case BuiltinType::UShort:
382   case BuiltinType::UInt:
383   case BuiltinType::UInt128:
384   case BuiltinType::ULong:
385   case BuiltinType::WChar_U:
386   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
387   case BuiltinType::Short:
388   case BuiltinType::Int:
389   case BuiltinType::Int128:
390   case BuiltinType::Long:
391   case BuiltinType::WChar_S:
392   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
393   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
394   case BuiltinType::Half:
395   case BuiltinType::Float:
396   case BuiltinType::LongDouble:
397   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
398   }
399 
400   switch (BT->getKind()) {
401   case BuiltinType::Long:      BTName = "long int"; break;
402   case BuiltinType::LongLong:  BTName = "long long int"; break;
403   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
404   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
405   default:
406     BTName = BT->getName(CGM.getContext().getLangOptions());
407     break;
408   }
409   // Bit size, align and offset of the type.
410   uint64_t Size = CGM.getContext().getTypeSize(BT);
411   uint64_t Align = CGM.getContext().getTypeAlign(BT);
412   llvm::DIType DbgTy =
413     DBuilder.createBasicType(BTName, Size, Align, Encoding);
414   return DbgTy;
415 }
416 
417 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
418   // Bit size, align and offset of the type.
419   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
420   if (Ty->isComplexIntegerType())
421     Encoding = llvm::dwarf::DW_ATE_lo_user;
422 
423   uint64_t Size = CGM.getContext().getTypeSize(Ty);
424   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
425   llvm::DIType DbgTy =
426     DBuilder.createBasicType("complex", Size, Align, Encoding);
427 
428   return DbgTy;
429 }
430 
431 /// CreateCVRType - Get the qualified type from the cache or create
432 /// a new one if necessary.
433 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
434   QualifierCollector Qc;
435   const Type *T = Qc.strip(Ty);
436 
437   // Ignore these qualifiers for now.
438   Qc.removeObjCGCAttr();
439   Qc.removeAddressSpace();
440   Qc.removeObjCLifetime();
441 
442   // We will create one Derived type for one qualifier and recurse to handle any
443   // additional ones.
444   unsigned Tag;
445   if (Qc.hasConst()) {
446     Tag = llvm::dwarf::DW_TAG_const_type;
447     Qc.removeConst();
448   } else if (Qc.hasVolatile()) {
449     Tag = llvm::dwarf::DW_TAG_volatile_type;
450     Qc.removeVolatile();
451   } else if (Qc.hasRestrict()) {
452     Tag = llvm::dwarf::DW_TAG_restrict_type;
453     Qc.removeRestrict();
454   } else {
455     assert(Qc.empty() && "Unknown type qualifier for debug info");
456     return getOrCreateType(QualType(T, 0), Unit);
457   }
458 
459   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
460 
461   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
462   // CVR derived types.
463   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
464 
465   return DbgTy;
466 }
467 
468 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
469                                      llvm::DIFile Unit) {
470   llvm::DIType DbgTy =
471     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
472                           Ty->getPointeeType(), Unit);
473   return DbgTy;
474 }
475 
476 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
477                                      llvm::DIFile Unit) {
478   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
479                                Ty->getPointeeType(), Unit);
480 }
481 
482 // Creates a forward declaration for a RecordDecl in the given context.
483 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
484                                               llvm::DIDescriptor Ctx) {
485   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
486   unsigned Line = getLineNumber(RD->getLocation());
487   StringRef RDName = RD->getName();
488 
489   // Get the tag.
490   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
491   unsigned Tag = 0;
492   if (CXXDecl) {
493     RDName = getClassName(RD);
494     Tag = llvm::dwarf::DW_TAG_class_type;
495   }
496   else if (RD->isStruct())
497     Tag = llvm::dwarf::DW_TAG_structure_type;
498   else if (RD->isUnion())
499     Tag = llvm::dwarf::DW_TAG_union_type;
500   else
501     llvm_unreachable("Unknown RecordDecl type!");
502 
503   // Create the type.
504   return DBuilder.createForwardDecl(Tag, RDName, DefUnit, Line);
505 }
506 
507 // Walk up the context chain and create forward decls for record decls,
508 // and normal descriptors for namespaces.
509 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
510   if (!Context)
511     return TheCU;
512 
513   // See if we already have the parent.
514   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
515     I = RegionMap.find(Context);
516   if (I != RegionMap.end())
517     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
518 
519   // Check namespace.
520   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
521     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
522 
523   if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
524     if (!RD->isDependentType()) {
525       llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
526 					       getOrCreateMainFile());
527       return llvm::DIDescriptor(Ty);
528     }
529   }
530   return TheCU;
531 }
532 
533 /// CreatePointeeType - Create Pointee type. If Pointee is a record
534 /// then emit record's fwd if debug info size reduction is enabled.
535 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
536                                             llvm::DIFile Unit) {
537   if (!CGM.getCodeGenOpts().LimitDebugInfo)
538     return getOrCreateType(PointeeTy, Unit);
539 
540   // Limit debug info for the pointee type.
541 
542   // If we have an existing type, use that, it's still smaller than creating
543   // a new type.
544   llvm::DIType Ty = getTypeOrNull(PointeeTy);
545   if (Ty.Verify()) return Ty;
546 
547   // Handle qualifiers.
548   if (PointeeTy.hasLocalQualifiers())
549     return CreateQualifiedType(PointeeTy, Unit);
550 
551   if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
552     RecordDecl *RD = RTy->getDecl();
553     llvm::DIDescriptor FDContext =
554       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
555     llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
556     TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
557     return RetTy;
558   }
559   return getOrCreateType(PointeeTy, Unit);
560 
561 }
562 
563 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
564                                                 const Type *Ty,
565                                                 QualType PointeeTy,
566                                                 llvm::DIFile Unit) {
567   if (Tag == llvm::dwarf::DW_TAG_reference_type)
568     return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
569 
570   // Bit size, align and offset of the type.
571   // Size is always the size of a pointer. We can't use getTypeSize here
572   // because that does not return the correct value for references.
573   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
574   uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
575   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
576 
577   return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
578                                     Size, Align);
579 }
580 
581 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
582                                      llvm::DIFile Unit) {
583   if (BlockLiteralGenericSet)
584     return BlockLiteralGeneric;
585 
586   SmallVector<llvm::Value *, 8> EltTys;
587   llvm::DIType FieldTy;
588   QualType FType;
589   uint64_t FieldSize, FieldOffset;
590   unsigned FieldAlign;
591   llvm::DIArray Elements;
592   llvm::DIType EltTy, DescTy;
593 
594   FieldOffset = 0;
595   FType = CGM.getContext().UnsignedLongTy;
596   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
597   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
598 
599   Elements = DBuilder.getOrCreateArray(EltTys);
600   EltTys.clear();
601 
602   unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
603   unsigned LineNo = getLineNumber(CurLoc);
604 
605   EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
606                                     Unit, LineNo, FieldOffset, 0,
607                                     Flags, Elements);
608 
609   // Bit size, align and offset of the type.
610   uint64_t Size = CGM.getContext().getTypeSize(Ty);
611 
612   DescTy = DBuilder.createPointerType(EltTy, Size);
613 
614   FieldOffset = 0;
615   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
616   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
617   FType = CGM.getContext().IntTy;
618   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
619   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
620   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
621   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
622 
623   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
624   FieldTy = DescTy;
625   FieldSize = CGM.getContext().getTypeSize(Ty);
626   FieldAlign = CGM.getContext().getTypeAlign(Ty);
627   FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
628                                       LineNo, FieldSize, FieldAlign,
629                                       FieldOffset, 0, FieldTy);
630   EltTys.push_back(FieldTy);
631 
632   FieldOffset += FieldSize;
633   Elements = DBuilder.getOrCreateArray(EltTys);
634 
635   EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
636                                     Unit, LineNo, FieldOffset, 0,
637                                     Flags, Elements);
638 
639   BlockLiteralGenericSet = true;
640   BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
641   return BlockLiteralGeneric;
642 }
643 
644 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
645   // Typedefs are derived from some other type.  If we have a typedef of a
646   // typedef, make sure to emit the whole chain.
647   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
648   if (!Src.Verify())
649     return llvm::DIType();
650   // We don't set size information, but do specify where the typedef was
651   // declared.
652   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
653   const TypedefNameDecl *TyDecl = Ty->getDecl();
654 
655   llvm::DIDescriptor TypedefContext =
656     getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
657 
658   return
659     DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
660 }
661 
662 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
663                                      llvm::DIFile Unit) {
664   SmallVector<llvm::Value *, 16> EltTys;
665 
666   // Add the result type at least.
667   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
668 
669   // Set up remainder of arguments if there is a prototype.
670   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
671   if (isa<FunctionNoProtoType>(Ty))
672     EltTys.push_back(DBuilder.createUnspecifiedParameter());
673   else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
674     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
675       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
676   }
677 
678   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
679 
680   llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
681   return DbgTy;
682 }
683 
684 
685 void CGDebugInfo::
686 CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) {
687 
688   for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
689        I != E; ++I)
690     if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
691       if (V->getInit()) {
692         const APValue *Value = V->evaluateValue();
693         if (Value && Value->isInt()) {
694           llvm::ConstantInt *CI
695             = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
696 
697           // Create the descriptor for static variable.
698           llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
699           StringRef VName = V->getName();
700           llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
701           // Do not use DIGlobalVariable for enums.
702           if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
703             DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
704                                           getLineNumber(V->getLocation()),
705                                           VTy, true, CI);
706           }
707         }
708       }
709     }
710 }
711 
712 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
713                                           QualType type,
714                                           uint64_t sizeInBitsOverride,
715                                           SourceLocation loc,
716                                           AccessSpecifier AS,
717                                           uint64_t offsetInBits,
718                                           llvm::DIFile tunit,
719                                           llvm::DIDescriptor scope) {
720   llvm::DIType debugType = getOrCreateType(type, tunit);
721 
722   // Get the location for the field.
723   llvm::DIFile file = getOrCreateFile(loc);
724   unsigned line = getLineNumber(loc);
725 
726   uint64_t sizeInBits = 0;
727   unsigned alignInBits = 0;
728   if (!type->isIncompleteArrayType()) {
729     llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
730 
731     if (sizeInBitsOverride)
732       sizeInBits = sizeInBitsOverride;
733   }
734 
735   unsigned flags = 0;
736   if (AS == clang::AS_private)
737     flags |= llvm::DIDescriptor::FlagPrivate;
738   else if (AS == clang::AS_protected)
739     flags |= llvm::DIDescriptor::FlagProtected;
740 
741   return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
742                                    alignInBits, offsetInBits, flags, debugType);
743 }
744 
745 /// CollectRecordFields - A helper function to collect debug info for
746 /// record fields. This is used while creating debug info entry for a Record.
747 void CGDebugInfo::
748 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
749                     SmallVectorImpl<llvm::Value *> &elements,
750                     llvm::DIType RecordTy) {
751   unsigned fieldNo = 0;
752   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
753   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
754 
755   // For C++11 Lambdas a Fields will be the same as a Capture, but the Capture
756   // has the name and the location of the variable so we should iterate over
757   // both concurrently.
758   if (CXXDecl && CXXDecl->isLambda()) {
759     RecordDecl::field_iterator Field = CXXDecl->field_begin();
760     unsigned fieldno = 0;
761     for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
762            E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
763       const LambdaExpr::Capture C = *I;
764       // TODO: Need to handle 'this' in some way by probably renaming the
765       // this of the lambda class and having a field member of 'this'.
766       if (C.capturesVariable()) {
767         VarDecl *V = C.getCapturedVar();
768         llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
769         StringRef VName = V->getName();
770         uint64_t SizeInBitsOverride = 0;
771         if (Field->isBitField()) {
772           SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
773           assert(SizeInBitsOverride && "found named 0-width bitfield");
774         }
775         llvm::DIType fieldType
776           = createFieldType(VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
777                             Field->getAccess(), layout.getFieldOffset(fieldno),
778                             VUnit, RecordTy);
779         elements.push_back(fieldType);
780       }
781     }
782   } else {
783     bool IsMsStruct = record->hasAttr<MsStructAttr>();
784     const FieldDecl *LastFD = 0;
785     for (RecordDecl::field_iterator I = record->field_begin(),
786            E = record->field_end();
787          I != E; ++I, ++fieldNo) {
788       FieldDecl *field = *I;
789 
790       if (IsMsStruct) {
791         // Zero-length bitfields following non-bitfield members are ignored
792         if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
793           --fieldNo;
794           continue;
795         }
796         LastFD = field;
797       }
798 
799       StringRef name = field->getName();
800       QualType type = field->getType();
801 
802       // Ignore unnamed fields unless they're anonymous structs/unions.
803       if (name.empty() && !type->isRecordType()) {
804         LastFD = field;
805         continue;
806       }
807 
808       uint64_t SizeInBitsOverride = 0;
809       if (field->isBitField()) {
810         SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
811         assert(SizeInBitsOverride && "found named 0-width bitfield");
812       }
813 
814       llvm::DIType fieldType
815         = createFieldType(name, type, SizeInBitsOverride,
816                           field->getLocation(), field->getAccess(),
817                           layout.getFieldOffset(fieldNo), tunit, RecordTy);
818 
819       elements.push_back(fieldType);
820     }
821   }
822 }
823 
824 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
825 /// function type is not updated to include implicit "this" pointer. Use this
826 /// routine to get a method type which includes "this" pointer.
827 llvm::DIType
828 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
829                                    llvm::DIFile Unit) {
830   llvm::DIType FnTy
831     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
832                                0),
833                       Unit);
834 
835   // Add "this" pointer.
836   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
837   assert (Args.getNumElements() && "Invalid number of arguments!");
838 
839   SmallVector<llvm::Value *, 16> Elts;
840 
841   // First element is always return type. For 'void' functions it is NULL.
842   Elts.push_back(Args.getElement(0));
843 
844   if (!Method->isStatic()) {
845     // "this" pointer is always first argument.
846     QualType ThisPtr = Method->getThisType(CGM.getContext());
847 
848     const CXXRecordDecl *RD = Method->getParent();
849     if (isa<ClassTemplateSpecializationDecl>(RD)) {
850       // Create pointer type directly in this case.
851       const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
852       QualType PointeeTy = ThisPtrTy->getPointeeType();
853       unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
854       uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
855       uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
856       llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
857       llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
858       TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
859       // TODO: This and the artificial type below are misleading, the
860       // types aren't artificial the argument is, but the current
861       // metadata doesn't represent that.
862       ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
863       Elts.push_back(ThisPtrType);
864     } else {
865       llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
866       TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
867       ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
868       Elts.push_back(ThisPtrType);
869     }
870   }
871 
872   // Copy rest of the arguments.
873   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
874     Elts.push_back(Args.getElement(i));
875 
876   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
877 
878   return DBuilder.createSubroutineType(Unit, EltTypeArray);
879 }
880 
881 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
882 /// inside a function.
883 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
884   if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
885     return isFunctionLocalClass(NRD);
886   if (isa<FunctionDecl>(RD->getDeclContext()))
887     return true;
888   return false;
889 }
890 
891 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
892 /// a single member function GlobalDecl.
893 llvm::DISubprogram
894 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
895                                      llvm::DIFile Unit,
896                                      llvm::DIType RecordTy) {
897   bool IsCtorOrDtor =
898     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
899 
900   StringRef MethodName = getFunctionName(Method);
901   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
902 
903   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
904   // make sense to give a single ctor/dtor a linkage name.
905   StringRef MethodLinkageName;
906   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
907     MethodLinkageName = CGM.getMangledName(Method);
908 
909   // Get the location for the method.
910   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
911   unsigned MethodLine = getLineNumber(Method->getLocation());
912 
913   // Collect virtual method info.
914   llvm::DIType ContainingType;
915   unsigned Virtuality = 0;
916   unsigned VIndex = 0;
917 
918   if (Method->isVirtual()) {
919     if (Method->isPure())
920       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
921     else
922       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
923 
924     // It doesn't make sense to give a virtual destructor a vtable index,
925     // since a single destructor has two entries in the vtable.
926     if (!isa<CXXDestructorDecl>(Method))
927       VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
928     ContainingType = RecordTy;
929   }
930 
931   unsigned Flags = 0;
932   if (Method->isImplicit())
933     Flags |= llvm::DIDescriptor::FlagArtificial;
934   AccessSpecifier Access = Method->getAccess();
935   if (Access == clang::AS_private)
936     Flags |= llvm::DIDescriptor::FlagPrivate;
937   else if (Access == clang::AS_protected)
938     Flags |= llvm::DIDescriptor::FlagProtected;
939   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
940     if (CXXC->isExplicit())
941       Flags |= llvm::DIDescriptor::FlagExplicit;
942   } else if (const CXXConversionDecl *CXXC =
943              dyn_cast<CXXConversionDecl>(Method)) {
944     if (CXXC->isExplicit())
945       Flags |= llvm::DIDescriptor::FlagExplicit;
946   }
947   if (Method->hasPrototype())
948     Flags |= llvm::DIDescriptor::FlagPrototyped;
949 
950   llvm::DISubprogram SP =
951     DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
952                           MethodDefUnit, MethodLine,
953                           MethodTy, /*isLocalToUnit=*/false,
954                           /* isDefinition=*/ false,
955                           Virtuality, VIndex, ContainingType,
956                           Flags, CGM.getLangOptions().Optimize);
957 
958   SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
959 
960   return SP;
961 }
962 
963 /// CollectCXXMemberFunctions - A helper function to collect debug info for
964 /// C++ member functions. This is used while creating debug info entry for
965 /// a Record.
966 void CGDebugInfo::
967 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
968                           SmallVectorImpl<llvm::Value *> &EltTys,
969                           llvm::DIType RecordTy) {
970   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
971         E = RD->method_end(); I != E; ++I) {
972     const CXXMethodDecl *Method = *I;
973 
974     if (Method->isImplicit() && !Method->isUsed())
975       continue;
976 
977     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
978   }
979 }
980 
981 /// CollectCXXFriends - A helper function to collect debug info for
982 /// C++ base classes. This is used while creating debug info entry for
983 /// a Record.
984 void CGDebugInfo::
985 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
986                 SmallVectorImpl<llvm::Value *> &EltTys,
987                 llvm::DIType RecordTy) {
988   for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
989          BE = RD->friend_end(); BI != BE; ++BI) {
990     if ((*BI)->isUnsupportedFriend())
991       continue;
992     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
993       EltTys.push_back(DBuilder.createFriend(RecordTy,
994                                              getOrCreateType(TInfo->getType(),
995                                                              Unit)));
996   }
997 }
998 
999 /// CollectCXXBases - A helper function to collect debug info for
1000 /// C++ base classes. This is used while creating debug info entry for
1001 /// a Record.
1002 void CGDebugInfo::
1003 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1004                 SmallVectorImpl<llvm::Value *> &EltTys,
1005                 llvm::DIType RecordTy) {
1006 
1007   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1008   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1009          BE = RD->bases_end(); BI != BE; ++BI) {
1010     unsigned BFlags = 0;
1011     uint64_t BaseOffset;
1012 
1013     const CXXRecordDecl *Base =
1014       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1015 
1016     if (BI->isVirtual()) {
1017       // virtual base offset offset is -ve. The code generator emits dwarf
1018       // expression where it expects +ve number.
1019       BaseOffset =
1020         0 - CGM.getVTableContext()
1021                .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1022       BFlags = llvm::DIDescriptor::FlagVirtual;
1023     } else
1024       BaseOffset = RL.getBaseClassOffsetInBits(Base);
1025     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1026     // BI->isVirtual() and bits when not.
1027 
1028     AccessSpecifier Access = BI->getAccessSpecifier();
1029     if (Access == clang::AS_private)
1030       BFlags |= llvm::DIDescriptor::FlagPrivate;
1031     else if (Access == clang::AS_protected)
1032       BFlags |= llvm::DIDescriptor::FlagProtected;
1033 
1034     llvm::DIType DTy =
1035       DBuilder.createInheritance(RecordTy,
1036                                  getOrCreateType(BI->getType(), Unit),
1037                                  BaseOffset, BFlags);
1038     EltTys.push_back(DTy);
1039   }
1040 }
1041 
1042 /// CollectTemplateParams - A helper function to collect template parameters.
1043 llvm::DIArray CGDebugInfo::
1044 CollectTemplateParams(const TemplateParameterList *TPList,
1045                       const TemplateArgumentList &TAList,
1046                       llvm::DIFile Unit) {
1047   SmallVector<llvm::Value *, 16> TemplateParams;
1048   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1049     const TemplateArgument &TA = TAList[i];
1050     const NamedDecl *ND = TPList->getParam(i);
1051     if (TA.getKind() == TemplateArgument::Type) {
1052       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1053       llvm::DITemplateTypeParameter TTP =
1054         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1055       TemplateParams.push_back(TTP);
1056     } else if (TA.getKind() == TemplateArgument::Integral) {
1057       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1058       llvm::DITemplateValueParameter TVP =
1059         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1060                                           TA.getAsIntegral()->getZExtValue());
1061       TemplateParams.push_back(TVP);
1062     }
1063   }
1064   return DBuilder.getOrCreateArray(TemplateParams);
1065 }
1066 
1067 /// CollectFunctionTemplateParams - A helper function to collect debug
1068 /// info for function template parameters.
1069 llvm::DIArray CGDebugInfo::
1070 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1071   if (FD->getTemplatedKind() ==
1072       FunctionDecl::TK_FunctionTemplateSpecialization) {
1073     const TemplateParameterList *TList =
1074       FD->getTemplateSpecializationInfo()->getTemplate()
1075       ->getTemplateParameters();
1076     return
1077       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1078   }
1079   return llvm::DIArray();
1080 }
1081 
1082 /// CollectCXXTemplateParams - A helper function to collect debug info for
1083 /// template parameters.
1084 llvm::DIArray CGDebugInfo::
1085 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1086                          llvm::DIFile Unit) {
1087   llvm::PointerUnion<ClassTemplateDecl *,
1088                      ClassTemplatePartialSpecializationDecl *>
1089     PU = TSpecial->getSpecializedTemplateOrPartial();
1090 
1091   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1092     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1093     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1094   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1095   return CollectTemplateParams(TPList, TAList, Unit);
1096 }
1097 
1098 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1099 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1100   if (VTablePtrType.isValid())
1101     return VTablePtrType;
1102 
1103   ASTContext &Context = CGM.getContext();
1104 
1105   /* Function type */
1106   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1107   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1108   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1109   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1110   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1111                                                           "__vtbl_ptr_type");
1112   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1113   return VTablePtrType;
1114 }
1115 
1116 /// getVTableName - Get vtable name for the given Class.
1117 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1118   // Construct gdb compatible name name.
1119   std::string Name = "_vptr$" + RD->getNameAsString();
1120 
1121   // Copy this name on the side and use its reference.
1122   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1123   memcpy(StrPtr, Name.data(), Name.length());
1124   return StringRef(StrPtr, Name.length());
1125 }
1126 
1127 
1128 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1129 /// debug info entry in EltTys vector.
1130 void CGDebugInfo::
1131 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1132                   SmallVectorImpl<llvm::Value *> &EltTys) {
1133   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1134 
1135   // If there is a primary base then it will hold vtable info.
1136   if (RL.getPrimaryBase())
1137     return;
1138 
1139   // If this class is not dynamic then there is not any vtable info to collect.
1140   if (!RD->isDynamicClass())
1141     return;
1142 
1143   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1144   llvm::DIType VPTR
1145     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1146                                 0, Size, 0, 0, 0,
1147                                 getOrCreateVTablePtrType(Unit));
1148   EltTys.push_back(VPTR);
1149 }
1150 
1151 /// getOrCreateRecordType - Emit record type's standalone debug info.
1152 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1153                                                 SourceLocation Loc) {
1154   llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1155   return T;
1156 }
1157 
1158 /// CreateType - get structure or union type.
1159 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1160   RecordDecl *RD = Ty->getDecl();
1161 
1162   // Get overall information about the record type for the debug info.
1163   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1164 
1165   // Records and classes and unions can all be recursive.  To handle them, we
1166   // first generate a debug descriptor for the struct as a forward declaration.
1167   // Then (if it is a definition) we go through and get debug info for all of
1168   // its members.  Finally, we create a descriptor for the complete type (which
1169   // may refer to the forward decl if the struct is recursive) and replace all
1170   // uses of the forward declaration with the final definition.
1171 
1172   llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1173 
1174   if (FwdDecl.isForwardDecl())
1175     return FwdDecl;
1176 
1177   llvm::MDNode *MN = FwdDecl;
1178   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1179 
1180   // Push the struct on region stack.
1181   LexicalBlockStack.push_back(FwdDeclNode);
1182   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1183 
1184   // Add this to the completed types cache since we're completing it.
1185   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1186 
1187   // Convert all the elements.
1188   SmallVector<llvm::Value *, 16> EltTys;
1189 
1190   // Note: The split of CXXDecl information here is intentional, the
1191   // gdb tests will depend on a certain ordering at printout. The debug
1192   // information offsets are still correct if we merge them all together
1193   // though.
1194   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1195   if (CXXDecl) {
1196     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1197     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1198   }
1199 
1200   // Collect static variables with initializers and other fields.
1201   CollectRecordStaticVars(RD, FwdDecl);
1202   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1203   llvm::DIArray TParamsArray;
1204   if (CXXDecl) {
1205     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1206     CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1207     if (const ClassTemplateSpecializationDecl *TSpecial
1208         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1209       TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1210   }
1211 
1212   LexicalBlockStack.pop_back();
1213   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1214     RegionMap.find(Ty->getDecl());
1215   if (RI != RegionMap.end())
1216     RegionMap.erase(RI);
1217 
1218   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1219   // FIXME: Magic numbers ahoy! These should be changed when we
1220   // get some enums in llvm/Analysis/DebugInfo.h to refer to
1221   // them.
1222   if (RD->isUnion())
1223     MN->replaceOperandWith(10, Elements);
1224   else if (CXXDecl) {
1225     MN->replaceOperandWith(10, Elements);
1226     MN->replaceOperandWith(13, TParamsArray);
1227   } else
1228     MN->replaceOperandWith(10, Elements);
1229 
1230   RegionMap[Ty->getDecl()] = llvm::WeakVH(MN);
1231   return llvm::DIType(MN);
1232 }
1233 
1234 /// CreateType - get objective-c object type.
1235 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1236                                      llvm::DIFile Unit) {
1237   // Ignore protocols.
1238   return getOrCreateType(Ty->getBaseType(), Unit);
1239 }
1240 
1241 /// CreateType - get objective-c interface type.
1242 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1243                                      llvm::DIFile Unit) {
1244   ObjCInterfaceDecl *ID = Ty->getDecl();
1245   if (!ID)
1246     return llvm::DIType();
1247 
1248   // Get overall information about the record type for the debug info.
1249   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1250   unsigned Line = getLineNumber(ID->getLocation());
1251   unsigned RuntimeLang = TheCU.getLanguage();
1252 
1253   // If this is just a forward declaration return a special forward-declaration
1254   // debug type since we won't be able to lay out the entire type.
1255   ObjCInterfaceDecl *Def = ID->getDefinition();
1256   if (!Def) {
1257     llvm::DIType FwdDecl =
1258       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1259 				 ID->getName(), DefUnit, Line,
1260 				 RuntimeLang);
1261     return FwdDecl;
1262   }
1263   ID = Def;
1264 
1265   // Bit size, align and offset of the type.
1266   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1267   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1268 
1269   unsigned Flags = 0;
1270   if (ID->getImplementation())
1271     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1272 
1273   llvm::DIType RealDecl =
1274     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1275                               Line, Size, Align, Flags,
1276                               llvm::DIArray(), RuntimeLang);
1277 
1278   // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1279   // will find it and we're emitting the complete type.
1280   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1281   // Push the struct on region stack.
1282   llvm::MDNode *MN = RealDecl;
1283   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1284 
1285   LexicalBlockStack.push_back(FwdDeclNode);
1286   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1287 
1288   // Convert all the elements.
1289   SmallVector<llvm::Value *, 16> EltTys;
1290 
1291   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1292   if (SClass) {
1293     llvm::DIType SClassTy =
1294       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1295     if (!SClassTy.isValid())
1296       return llvm::DIType();
1297 
1298     llvm::DIType InhTag =
1299       DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1300     EltTys.push_back(InhTag);
1301   }
1302 
1303   for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1304          E = ID->prop_end(); I != E; ++I) {
1305     const ObjCPropertyDecl *PD = *I;
1306     llvm::MDNode *PropertyNode =
1307       DBuilder.createObjCProperty(PD->getName(),
1308                                   getSelectorName(PD->getGetterName()),
1309                                   getSelectorName(PD->getSetterName()),
1310                                   PD->getPropertyAttributes());
1311     EltTys.push_back(PropertyNode);
1312   }
1313 
1314   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1315   unsigned FieldNo = 0;
1316   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1317        Field = Field->getNextIvar(), ++FieldNo) {
1318     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1319     if (!FieldTy.isValid())
1320       return llvm::DIType();
1321 
1322     StringRef FieldName = Field->getName();
1323 
1324     // Ignore unnamed fields.
1325     if (FieldName.empty())
1326       continue;
1327 
1328     // Get the location for the field.
1329     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1330     unsigned FieldLine = getLineNumber(Field->getLocation());
1331     QualType FType = Field->getType();
1332     uint64_t FieldSize = 0;
1333     unsigned FieldAlign = 0;
1334 
1335     if (!FType->isIncompleteArrayType()) {
1336 
1337       // Bit size, align and offset of the type.
1338       FieldSize = Field->isBitField()
1339         ? Field->getBitWidthValue(CGM.getContext())
1340         : CGM.getContext().getTypeSize(FType);
1341       FieldAlign = CGM.getContext().getTypeAlign(FType);
1342     }
1343 
1344     // We can't know the offset of our ivar in the structure if we're using
1345     // the non-fragile abi and the debugger should ignore the value anyways.
1346     // Call it the FieldNo+1 due to how debuggers use the information,
1347     // e.g. negating the value when it needs a lookup in the dynamic table.
1348     uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1
1349       : RL.getFieldOffset(FieldNo);
1350 
1351     unsigned Flags = 0;
1352     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1353       Flags = llvm::DIDescriptor::FlagProtected;
1354     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1355       Flags = llvm::DIDescriptor::FlagPrivate;
1356 
1357     llvm::MDNode *PropertyNode = NULL;
1358     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1359       if (ObjCPropertyImplDecl *PImpD =
1360           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1361         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1362           PropertyNode =
1363             DBuilder.createObjCProperty(PD->getName(),
1364                                         getSelectorName(PD->getGetterName()),
1365                                         getSelectorName(PD->getSetterName()),
1366                                         PD->getPropertyAttributes());
1367         }
1368       }
1369     }
1370     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1371                                       FieldLine, FieldSize, FieldAlign,
1372                                       FieldOffset, Flags, FieldTy,
1373                                       PropertyNode);
1374     EltTys.push_back(FieldTy);
1375   }
1376 
1377   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1378   RealDecl->replaceOperandWith(10, Elements);
1379 
1380   LexicalBlockStack.pop_back();
1381   return RealDecl;
1382 }
1383 
1384 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1385   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1386   int64_t NumElems = Ty->getNumElements();
1387   int64_t LowerBound = 0;
1388   if (NumElems == 0)
1389     // If number of elements are not known then this is an unbounded array.
1390     // Use Low = 1, Hi = 0 to express such arrays.
1391     LowerBound = 1;
1392   else
1393     --NumElems;
1394 
1395   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1396   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1397 
1398   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1399   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1400 
1401   return
1402     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1403 }
1404 
1405 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1406                                      llvm::DIFile Unit) {
1407   uint64_t Size;
1408   uint64_t Align;
1409 
1410 
1411   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1412   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1413     Size = 0;
1414     Align =
1415       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1416   } else if (Ty->isIncompleteArrayType()) {
1417     Size = 0;
1418     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1419   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1420     Size = 0;
1421     Align = 0;
1422   } else {
1423     // Size and align of the whole array, not the element type.
1424     Size = CGM.getContext().getTypeSize(Ty);
1425     Align = CGM.getContext().getTypeAlign(Ty);
1426   }
1427 
1428   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1429   // interior arrays, do we care?  Why aren't nested arrays represented the
1430   // obvious/recursive way?
1431   SmallVector<llvm::Value *, 8> Subscripts;
1432   QualType EltTy(Ty, 0);
1433   if (Ty->isIncompleteArrayType())
1434     EltTy = Ty->getElementType();
1435   else {
1436     while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1437       int64_t UpperBound = 0;
1438       int64_t LowerBound = 0;
1439       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1440         if (CAT->getSize().getZExtValue())
1441           UpperBound = CAT->getSize().getZExtValue() - 1;
1442       } else
1443         // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1444         // arrays.
1445         LowerBound = 1;
1446 
1447       // FIXME: Verify this is right for VLAs.
1448       Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1449                                                         UpperBound));
1450       EltTy = Ty->getElementType();
1451     }
1452   }
1453 
1454   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1455 
1456   llvm::DIType DbgTy =
1457     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1458                              SubscriptArray);
1459   return DbgTy;
1460 }
1461 
1462 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1463                                      llvm::DIFile Unit) {
1464   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1465                                Ty, Ty->getPointeeType(), Unit);
1466 }
1467 
1468 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1469                                      llvm::DIFile Unit) {
1470   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1471                                Ty, Ty->getPointeeType(), Unit);
1472 }
1473 
1474 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1475                                      llvm::DIFile U) {
1476   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1477   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1478 
1479   if (!Ty->getPointeeType()->isFunctionType()) {
1480     // We have a data member pointer type.
1481     return PointerDiffDITy;
1482   }
1483 
1484   // We have a member function pointer type. Treat it as a struct with two
1485   // ptrdiff_t members.
1486   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1487 
1488   uint64_t FieldOffset = 0;
1489   llvm::Value *ElementTypes[2];
1490 
1491   // FIXME: This should probably be a function type instead.
1492   ElementTypes[0] =
1493     DBuilder.createMemberType(U, "ptr", U, 0,
1494                               Info.first, Info.second, FieldOffset, 0,
1495                               PointerDiffDITy);
1496   FieldOffset += Info.first;
1497 
1498   ElementTypes[1] =
1499     DBuilder.createMemberType(U, "ptr", U, 0,
1500                               Info.first, Info.second, FieldOffset, 0,
1501                               PointerDiffDITy);
1502 
1503   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1504 
1505   return DBuilder.createStructType(U, StringRef("test"),
1506                                    U, 0, FieldOffset,
1507                                    0, 0, Elements);
1508 }
1509 
1510 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1511                                      llvm::DIFile U) {
1512   // Ignore the atomic wrapping
1513   // FIXME: What is the correct representation?
1514   return getOrCreateType(Ty->getValueType(), U);
1515 }
1516 
1517 /// CreateEnumType - get enumeration type.
1518 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1519   llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1520   SmallVector<llvm::Value *, 16> Enumerators;
1521 
1522   // Create DIEnumerator elements for each enumerator.
1523   for (EnumDecl::enumerator_iterator
1524          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1525        Enum != EnumEnd; ++Enum) {
1526     Enumerators.push_back(
1527       DBuilder.createEnumerator(Enum->getName(),
1528                                 Enum->getInitVal().getZExtValue()));
1529   }
1530 
1531   // Return a CompositeType for the enum itself.
1532   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1533 
1534   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1535   unsigned Line = getLineNumber(ED->getLocation());
1536   uint64_t Size = 0;
1537   uint64_t Align = 0;
1538   if (!ED->getTypeForDecl()->isIncompleteType()) {
1539     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1540     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1541   }
1542   llvm::DIDescriptor EnumContext =
1543     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1544   llvm::DIType DbgTy =
1545     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1546                                    Size, Align, EltArray);
1547   return DbgTy;
1548 }
1549 
1550 static QualType UnwrapTypeForDebugInfo(QualType T) {
1551   do {
1552     QualType LastT = T;
1553     switch (T->getTypeClass()) {
1554     default:
1555       return T;
1556     case Type::TemplateSpecialization:
1557       T = cast<TemplateSpecializationType>(T)->desugar();
1558       break;
1559     case Type::TypeOfExpr:
1560       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1561       break;
1562     case Type::TypeOf:
1563       T = cast<TypeOfType>(T)->getUnderlyingType();
1564       break;
1565     case Type::Decltype:
1566       T = cast<DecltypeType>(T)->getUnderlyingType();
1567       break;
1568     case Type::UnaryTransform:
1569       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1570       break;
1571     case Type::Attributed:
1572       T = cast<AttributedType>(T)->getEquivalentType();
1573       break;
1574     case Type::Elaborated:
1575       T = cast<ElaboratedType>(T)->getNamedType();
1576       break;
1577     case Type::Paren:
1578       T = cast<ParenType>(T)->getInnerType();
1579       break;
1580     case Type::SubstTemplateTypeParm:
1581       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1582       break;
1583     case Type::Auto:
1584       T = cast<AutoType>(T)->getDeducedType();
1585       break;
1586     }
1587 
1588     assert(T != LastT && "Type unwrapping failed to unwrap!");
1589     if (T == LastT)
1590       return T;
1591   } while (true);
1592 }
1593 
1594 /// getType - Get the type from the cache or return null type if it doesn't exist.
1595 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1596 
1597   // Unwrap the type as needed for debug information.
1598   Ty = UnwrapTypeForDebugInfo(Ty);
1599 
1600   // Check for existing entry.
1601   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1602     TypeCache.find(Ty.getAsOpaquePtr());
1603   if (it != TypeCache.end()) {
1604     // Verify that the debug info still exists.
1605     if (&*it->second)
1606       return llvm::DIType(cast<llvm::MDNode>(it->second));
1607   }
1608 
1609   return llvm::DIType();
1610 }
1611 
1612 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1613 /// doesn't exist.
1614 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1615 
1616   // Unwrap the type as needed for debug information.
1617   Ty = UnwrapTypeForDebugInfo(Ty);
1618 
1619   // Check for existing entry.
1620   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1621     CompletedTypeCache.find(Ty.getAsOpaquePtr());
1622   if (it != CompletedTypeCache.end()) {
1623     // Verify that the debug info still exists.
1624     if (&*it->second)
1625       return llvm::DIType(cast<llvm::MDNode>(it->second));
1626   }
1627 
1628   return llvm::DIType();
1629 }
1630 
1631 
1632 /// getOrCreateType - Get the type from the cache or create a new
1633 /// one if necessary.
1634 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1635   if (Ty.isNull())
1636     return llvm::DIType();
1637 
1638   // Unwrap the type as needed for debug information.
1639   Ty = UnwrapTypeForDebugInfo(Ty);
1640 
1641   llvm::DIType T = getCompletedTypeOrNull(Ty);
1642 
1643   if (T.Verify()) return T;
1644 
1645   // Otherwise create the type.
1646   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1647 
1648   llvm::DIType TC = getTypeOrNull(Ty);
1649   if (TC.Verify() && TC.isForwardDecl())
1650     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), TC));
1651 
1652   // And update the type cache.
1653   TypeCache[Ty.getAsOpaquePtr()] = Res;
1654 
1655   if (!Res.isForwardDecl())
1656     CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1657   return Res;
1658 }
1659 
1660 /// CreateTypeNode - Create a new debug type node.
1661 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1662   // Handle qualifiers, which recursively handles what they refer to.
1663   if (Ty.hasLocalQualifiers())
1664     return CreateQualifiedType(Ty, Unit);
1665 
1666   const char *Diag = 0;
1667 
1668   // Work out details of type.
1669   switch (Ty->getTypeClass()) {
1670 #define TYPE(Class, Base)
1671 #define ABSTRACT_TYPE(Class, Base)
1672 #define NON_CANONICAL_TYPE(Class, Base)
1673 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1674 #include "clang/AST/TypeNodes.def"
1675     llvm_unreachable("Dependent types cannot show up in debug information");
1676 
1677   case Type::ExtVector:
1678   case Type::Vector:
1679     return CreateType(cast<VectorType>(Ty), Unit);
1680   case Type::ObjCObjectPointer:
1681     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1682   case Type::ObjCObject:
1683     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1684   case Type::ObjCInterface:
1685     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1686   case Type::Builtin:
1687     return CreateType(cast<BuiltinType>(Ty));
1688   case Type::Complex:
1689     return CreateType(cast<ComplexType>(Ty));
1690   case Type::Pointer:
1691     return CreateType(cast<PointerType>(Ty), Unit);
1692   case Type::BlockPointer:
1693     return CreateType(cast<BlockPointerType>(Ty), Unit);
1694   case Type::Typedef:
1695     return CreateType(cast<TypedefType>(Ty), Unit);
1696   case Type::Record:
1697     return CreateType(cast<RecordType>(Ty));
1698   case Type::Enum:
1699     return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1700   case Type::FunctionProto:
1701   case Type::FunctionNoProto:
1702     return CreateType(cast<FunctionType>(Ty), Unit);
1703   case Type::ConstantArray:
1704   case Type::VariableArray:
1705   case Type::IncompleteArray:
1706     return CreateType(cast<ArrayType>(Ty), Unit);
1707 
1708   case Type::LValueReference:
1709     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1710   case Type::RValueReference:
1711     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1712 
1713   case Type::MemberPointer:
1714     return CreateType(cast<MemberPointerType>(Ty), Unit);
1715 
1716   case Type::Atomic:
1717     return CreateType(cast<AtomicType>(Ty), Unit);
1718 
1719   case Type::Attributed:
1720   case Type::TemplateSpecialization:
1721   case Type::Elaborated:
1722   case Type::Paren:
1723   case Type::SubstTemplateTypeParm:
1724   case Type::TypeOfExpr:
1725   case Type::TypeOf:
1726   case Type::Decltype:
1727   case Type::UnaryTransform:
1728   case Type::Auto:
1729     llvm_unreachable("type should have been unwrapped!");
1730   }
1731 
1732   assert(Diag && "Fall through without a diagnostic?");
1733   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1734                                "debug information for %0 is not yet supported");
1735   CGM.getDiags().Report(DiagID)
1736     << Diag;
1737   return llvm::DIType();
1738 }
1739 
1740 /// getOrCreateLimitedType - Get the type from the cache or create a new
1741 /// limited type if necessary.
1742 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1743 						 llvm::DIFile Unit) {
1744   if (Ty.isNull())
1745     return llvm::DIType();
1746 
1747   // Unwrap the type as needed for debug information.
1748   Ty = UnwrapTypeForDebugInfo(Ty);
1749 
1750   llvm::DIType T = getTypeOrNull(Ty);
1751 
1752   // We may have cached a forward decl when we could have created
1753   // a non-forward decl. Go ahead and create a non-forward decl
1754   // now.
1755   if (T.Verify() && !T.isForwardDecl()) return T;
1756 
1757   // Otherwise create the type.
1758   llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1759 
1760   if (T.Verify() && T.isForwardDecl())
1761     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), T));
1762 
1763   // And update the type cache.
1764   TypeCache[Ty.getAsOpaquePtr()] = Res;
1765   return Res;
1766 }
1767 
1768 // TODO: Currently used for context chains when limiting debug info.
1769 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1770   RecordDecl *RD = Ty->getDecl();
1771 
1772   // Get overall information about the record type for the debug info.
1773   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1774   unsigned Line = getLineNumber(RD->getLocation());
1775   StringRef RDName = RD->getName();
1776 
1777   llvm::DIDescriptor RDContext;
1778   if (CGM.getCodeGenOpts().LimitDebugInfo)
1779     RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1780   else
1781     RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1782 
1783   // If this is just a forward declaration, construct an appropriately
1784   // marked node and just return it.
1785   if (!RD->getDefinition())
1786     return createRecordFwdDecl(RD, RDContext);
1787 
1788   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1789   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1790   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1791   llvm::MDNode *RealDecl = NULL;
1792 
1793   if (RD->isUnion())
1794     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1795 					Size, Align, 0, llvm::DIArray());
1796   else if (CXXDecl) {
1797     RDName = getClassName(RD);
1798 
1799     // FIXME: This could be a struct type giving a default visibility different
1800     // than C++ class type, but needs llvm metadata changes first.
1801     RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1802 					Size, Align, 0, 0, llvm::DIType(),
1803 					llvm::DIArray(), llvm::DIType(),
1804 					llvm::DIArray());
1805   } else
1806     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1807 					 Size, Align, 0, llvm::DIArray());
1808 
1809   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1810   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1811 
1812   if (CXXDecl) {
1813     // A class's primary base or the class itself contains the vtable.
1814     llvm::MDNode *ContainingType = NULL;
1815     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1816     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1817       // Seek non virtual primary base root.
1818       while (1) {
1819 	const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1820 	const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1821 	if (PBT && !BRL.isPrimaryBaseVirtual())
1822 	  PBase = PBT;
1823 	else
1824 	  break;
1825       }
1826       ContainingType =
1827 	getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1828     }
1829     else if (CXXDecl->isDynamicClass())
1830       ContainingType = RealDecl;
1831 
1832     RealDecl->replaceOperandWith(12, ContainingType);
1833   }
1834   return llvm::DIType(RealDecl);
1835 }
1836 
1837 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
1838 /// declare composite types that haven't been processed yet.
1839 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1840 
1841   // Work out details of type.
1842   switch (Ty->getTypeClass()) {
1843 #define TYPE(Class, Base)
1844 #define ABSTRACT_TYPE(Class, Base)
1845 #define NON_CANONICAL_TYPE(Class, Base)
1846 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1847         #include "clang/AST/TypeNodes.def"
1848     llvm_unreachable("Dependent types cannot show up in debug information");
1849 
1850   case Type::Record:
1851     return CreateLimitedType(cast<RecordType>(Ty));
1852   default:
1853     return CreateTypeNode(Ty, Unit);
1854   }
1855 }
1856 
1857 /// CreateMemberType - Create new member and increase Offset by FType's size.
1858 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1859                                            StringRef Name,
1860                                            uint64_t *Offset) {
1861   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1862   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1863   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1864   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1865                                               FieldSize, FieldAlign,
1866                                               *Offset, 0, FieldTy);
1867   *Offset += FieldSize;
1868   return Ty;
1869 }
1870 
1871 /// getFunctionDeclaration - Return debug info descriptor to describe method
1872 /// declaration for the given method definition.
1873 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1874   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1875   if (!FD) return llvm::DISubprogram();
1876 
1877   // Setup context.
1878   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1879 
1880   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1881     MI = SPCache.find(FD->getCanonicalDecl());
1882   if (MI != SPCache.end()) {
1883     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1884     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1885       return SP;
1886   }
1887 
1888   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1889          E = FD->redecls_end(); I != E; ++I) {
1890     const FunctionDecl *NextFD = *I;
1891     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1892       MI = SPCache.find(NextFD->getCanonicalDecl());
1893     if (MI != SPCache.end()) {
1894       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1895       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1896         return SP;
1897     }
1898   }
1899   return llvm::DISubprogram();
1900 }
1901 
1902 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1903 // implicit parameter "this".
1904 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1905                                                   QualType FnType,
1906                                                   llvm::DIFile F) {
1907   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1908     return getOrCreateMethodType(Method, F);
1909   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1910     // Add "self" and "_cmd"
1911     SmallVector<llvm::Value *, 16> Elts;
1912 
1913     // First element is always return type. For 'void' functions it is NULL.
1914     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1915     // "self" pointer is always first argument.
1916     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1917     // "cmd" pointer is always second argument.
1918     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1919     // Get rest of the arguments.
1920     for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1921            PE = OMethod->param_end(); PI != PE; ++PI)
1922       Elts.push_back(getOrCreateType((*PI)->getType(), F));
1923 
1924     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1925     return DBuilder.createSubroutineType(F, EltTypeArray);
1926   }
1927   return getOrCreateType(FnType, F);
1928 }
1929 
1930 /// EmitFunctionStart - Constructs the debug code for entering a function -
1931 /// "llvm.dbg.func.start.".
1932 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1933                                     llvm::Function *Fn,
1934                                     CGBuilderTy &Builder) {
1935 
1936   StringRef Name;
1937   StringRef LinkageName;
1938 
1939   FnBeginRegionCount.push_back(LexicalBlockStack.size());
1940 
1941   const Decl *D = GD.getDecl();
1942 
1943   unsigned Flags = 0;
1944   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1945   llvm::DIDescriptor FDContext(Unit);
1946   llvm::DIArray TParamsArray;
1947   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1948     // If there is a DISubprogram for this function available then use it.
1949     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1950       FI = SPCache.find(FD->getCanonicalDecl());
1951     if (FI != SPCache.end()) {
1952       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1953       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1954         llvm::MDNode *SPN = SP;
1955         LexicalBlockStack.push_back(SPN);
1956         RegionMap[D] = llvm::WeakVH(SP);
1957         return;
1958       }
1959     }
1960     Name = getFunctionName(FD);
1961     // Use mangled name as linkage name for c/c++ functions.
1962     if (!Fn->hasInternalLinkage())
1963       LinkageName = CGM.getMangledName(GD);
1964     if (LinkageName == Name)
1965       LinkageName = StringRef();
1966     if (FD->hasPrototype())
1967       Flags |= llvm::DIDescriptor::FlagPrototyped;
1968     if (const NamespaceDecl *NSDecl =
1969         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1970       FDContext = getOrCreateNameSpace(NSDecl);
1971     else if (const RecordDecl *RDecl =
1972              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1973       FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1974 
1975     // Collect template parameters.
1976     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1977   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1978     Name = getObjCMethodName(OMD);
1979     Flags |= llvm::DIDescriptor::FlagPrototyped;
1980   } else {
1981     // Use llvm function name.
1982     Name = Fn->getName();
1983     Flags |= llvm::DIDescriptor::FlagPrototyped;
1984   }
1985   if (!Name.empty() && Name[0] == '\01')
1986     Name = Name.substr(1);
1987 
1988   // It is expected that CurLoc is set before using EmitFunctionStart.
1989   // Usually, CurLoc points to the left bracket location of compound
1990   // statement representing function body.
1991   unsigned LineNo = getLineNumber(CurLoc);
1992   if (D->isImplicit())
1993     Flags |= llvm::DIDescriptor::FlagArtificial;
1994   llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1995   llvm::DISubprogram SP =
1996     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1997                             LineNo, getOrCreateFunctionType(D, FnType, Unit),
1998                             Fn->hasInternalLinkage(), true/*definition*/,
1999                             Flags, CGM.getLangOptions().Optimize, Fn,
2000                             TParamsArray, SPDecl);
2001 
2002   // Push function on region stack.
2003   llvm::MDNode *SPN = SP;
2004   LexicalBlockStack.push_back(SPN);
2005   RegionMap[D] = llvm::WeakVH(SP);
2006 }
2007 
2008 /// EmitLocation - Emit metadata to indicate a change in line/column
2009 /// information in the source file.
2010 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2011 
2012   // Update our current location
2013   setLocation(Loc);
2014 
2015   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2016 
2017   // Don't bother if things are the same as last time.
2018   SourceManager &SM = CGM.getContext().getSourceManager();
2019   if (CurLoc == PrevLoc ||
2020       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2021     // New Builder may not be in sync with CGDebugInfo.
2022     if (!Builder.getCurrentDebugLocation().isUnknown())
2023       return;
2024 
2025   // Update last state.
2026   PrevLoc = CurLoc;
2027 
2028   llvm::MDNode *Scope = LexicalBlockStack.back();
2029   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2030                                                       getColumnNumber(CurLoc),
2031                                                       Scope));
2032 }
2033 
2034 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2035 /// the stack.
2036 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2037   llvm::DIDescriptor D =
2038     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2039                                 llvm::DIDescriptor() :
2040                                 llvm::DIDescriptor(LexicalBlockStack.back()),
2041                                 getOrCreateFile(CurLoc),
2042                                 getLineNumber(CurLoc),
2043                                 getColumnNumber(CurLoc));
2044   llvm::MDNode *DN = D;
2045   LexicalBlockStack.push_back(DN);
2046 }
2047 
2048 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2049 /// region - beginning of a DW_TAG_lexical_block.
2050 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2051   // Set our current location.
2052   setLocation(Loc);
2053 
2054   // Create a new lexical block and push it on the stack.
2055   CreateLexicalBlock(Loc);
2056 
2057   // Emit a line table change for the current location inside the new scope.
2058   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2059                                   getColumnNumber(Loc),
2060                                   LexicalBlockStack.back()));
2061 }
2062 
2063 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2064 /// region - end of a DW_TAG_lexical_block.
2065 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2066   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2067 
2068   // Provide an entry in the line table for the end of the block.
2069   EmitLocation(Builder, Loc);
2070 
2071   LexicalBlockStack.pop_back();
2072 }
2073 
2074 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2075 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2076   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2077   unsigned RCount = FnBeginRegionCount.back();
2078   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2079 
2080   // Pop all regions for this function.
2081   while (LexicalBlockStack.size() != RCount)
2082     EmitLexicalBlockEnd(Builder, CurLoc);
2083   FnBeginRegionCount.pop_back();
2084 }
2085 
2086 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2087 // See BuildByRefType.
2088 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
2089                                                        uint64_t *XOffset) {
2090 
2091   SmallVector<llvm::Value *, 5> EltTys;
2092   QualType FType;
2093   uint64_t FieldSize, FieldOffset;
2094   unsigned FieldAlign;
2095 
2096   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2097   QualType Type = VD->getType();
2098 
2099   FieldOffset = 0;
2100   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2101   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2102   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2103   FType = CGM.getContext().IntTy;
2104   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2105   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2106 
2107   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
2108   if (HasCopyAndDispose) {
2109     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2110     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2111                                       &FieldOffset));
2112     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2113                                       &FieldOffset));
2114   }
2115 
2116   CharUnits Align = CGM.getContext().getDeclAlign(VD);
2117   if (Align > CGM.getContext().toCharUnitsFromBits(
2118         CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2119     CharUnits FieldOffsetInBytes
2120       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2121     CharUnits AlignedOffsetInBytes
2122       = FieldOffsetInBytes.RoundUpToAlignment(Align);
2123     CharUnits NumPaddingBytes
2124       = AlignedOffsetInBytes - FieldOffsetInBytes;
2125 
2126     if (NumPaddingBytes.isPositive()) {
2127       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2128       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2129                                                     pad, ArrayType::Normal, 0);
2130       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2131     }
2132   }
2133 
2134   FType = Type;
2135   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2136   FieldSize = CGM.getContext().getTypeSize(FType);
2137   FieldAlign = CGM.getContext().toBits(Align);
2138 
2139   *XOffset = FieldOffset;
2140   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2141                                       0, FieldSize, FieldAlign,
2142                                       FieldOffset, 0, FieldTy);
2143   EltTys.push_back(FieldTy);
2144   FieldOffset += FieldSize;
2145 
2146   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2147 
2148   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2149 
2150   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2151                                    Elements);
2152 }
2153 
2154 /// EmitDeclare - Emit local variable declaration debug info.
2155 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2156                               llvm::Value *Storage,
2157                               unsigned ArgNo, CGBuilderTy &Builder) {
2158   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2159 
2160   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2161   llvm::DIType Ty;
2162   uint64_t XOffset = 0;
2163   if (VD->hasAttr<BlocksAttr>())
2164     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2165   else
2166     Ty = getOrCreateType(VD->getType(), Unit);
2167 
2168   // If there is not any debug info for type then do not emit debug info
2169   // for this variable.
2170   if (!Ty)
2171     return;
2172 
2173   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2174     // If Storage is an aggregate returned as 'sret' then let debugger know
2175     // about this.
2176     if (Arg->hasStructRetAttr())
2177       Ty = DBuilder.createReferenceType(Ty);
2178     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2179       // If an aggregate variable has non trivial destructor or non trivial copy
2180       // constructor than it is pass indirectly. Let debug info know about this
2181       // by using reference of the aggregate type as a argument type.
2182       if (!Record->hasTrivialCopyConstructor() ||
2183           !Record->hasTrivialDestructor())
2184         Ty = DBuilder.createReferenceType(Ty);
2185     }
2186   }
2187 
2188   // Get location information.
2189   unsigned Line = getLineNumber(VD->getLocation());
2190   unsigned Column = getColumnNumber(VD->getLocation());
2191   unsigned Flags = 0;
2192   if (VD->isImplicit())
2193     Flags |= llvm::DIDescriptor::FlagArtificial;
2194   llvm::MDNode *Scope = LexicalBlockStack.back();
2195 
2196   StringRef Name = VD->getName();
2197   if (!Name.empty()) {
2198     if (VD->hasAttr<BlocksAttr>()) {
2199       CharUnits offset = CharUnits::fromQuantity(32);
2200       SmallVector<llvm::Value *, 9> addr;
2201       llvm::Type *Int64Ty = CGM.Int64Ty;
2202       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2203       // offset of __forwarding field
2204       offset = CGM.getContext().toCharUnitsFromBits(
2205         CGM.getContext().getTargetInfo().getPointerWidth(0));
2206       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2207       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2208       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2209       // offset of x field
2210       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2211       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2212 
2213       // Create the descriptor for the variable.
2214       llvm::DIVariable D =
2215         DBuilder.createComplexVariable(Tag,
2216                                        llvm::DIDescriptor(Scope),
2217                                        VD->getName(), Unit, Line, Ty,
2218                                        addr, ArgNo);
2219 
2220       // Insert an llvm.dbg.declare into the current block.
2221       llvm::Instruction *Call =
2222         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2223       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2224       return;
2225     }
2226       // Create the descriptor for the variable.
2227     llvm::DIVariable D =
2228       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2229                                    Name, Unit, Line, Ty,
2230                                    CGM.getLangOptions().Optimize, Flags, ArgNo);
2231 
2232     // Insert an llvm.dbg.declare into the current block.
2233     llvm::Instruction *Call =
2234       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2235     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2236     return;
2237   }
2238 
2239   // If VD is an anonymous union then Storage represents value for
2240   // all union fields.
2241   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2242     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2243     if (RD->isUnion()) {
2244       for (RecordDecl::field_iterator I = RD->field_begin(),
2245              E = RD->field_end();
2246            I != E; ++I) {
2247         FieldDecl *Field = *I;
2248         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2249         StringRef FieldName = Field->getName();
2250 
2251         // Ignore unnamed fields. Do not ignore unnamed records.
2252         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2253           continue;
2254 
2255         // Use VarDecl's Tag, Scope and Line number.
2256         llvm::DIVariable D =
2257           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2258                                        FieldName, Unit, Line, FieldTy,
2259                                        CGM.getLangOptions().Optimize, Flags,
2260                                        ArgNo);
2261 
2262         // Insert an llvm.dbg.declare into the current block.
2263         llvm::Instruction *Call =
2264           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2265         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2266       }
2267     }
2268   }
2269 }
2270 
2271 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2272                                             llvm::Value *Storage,
2273                                             CGBuilderTy &Builder) {
2274   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2275 }
2276 
2277 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2278   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2279   const CGBlockInfo &blockInfo) {
2280   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2281 
2282   if (Builder.GetInsertBlock() == 0)
2283     return;
2284 
2285   bool isByRef = VD->hasAttr<BlocksAttr>();
2286 
2287   uint64_t XOffset = 0;
2288   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2289   llvm::DIType Ty;
2290   if (isByRef)
2291     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2292   else
2293     Ty = getOrCreateType(VD->getType(), Unit);
2294 
2295   // Get location information.
2296   unsigned Line = getLineNumber(VD->getLocation());
2297   unsigned Column = getColumnNumber(VD->getLocation());
2298 
2299   const llvm::TargetData &target = CGM.getTargetData();
2300 
2301   CharUnits offset = CharUnits::fromQuantity(
2302     target.getStructLayout(blockInfo.StructureType)
2303           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2304 
2305   SmallVector<llvm::Value *, 9> addr;
2306   llvm::Type *Int64Ty = CGM.Int64Ty;
2307   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2308   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2309   if (isByRef) {
2310     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2311     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2312     // offset of __forwarding field
2313     offset = CGM.getContext()
2314                 .toCharUnitsFromBits(target.getPointerSizeInBits());
2315     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2316     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2317     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2318     // offset of x field
2319     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2320     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2321   }
2322 
2323   // Create the descriptor for the variable.
2324   llvm::DIVariable D =
2325     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2326                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2327                                    VD->getName(), Unit, Line, Ty, addr);
2328   // Insert an llvm.dbg.declare into the current block.
2329   llvm::Instruction *Call =
2330     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2331   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2332                                         LexicalBlockStack.back()));
2333 }
2334 
2335 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2336 /// variable declaration.
2337 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2338                                            unsigned ArgNo,
2339                                            CGBuilderTy &Builder) {
2340   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2341 }
2342 
2343 namespace {
2344   struct BlockLayoutChunk {
2345     uint64_t OffsetInBits;
2346     const BlockDecl::Capture *Capture;
2347   };
2348   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2349     return l.OffsetInBits < r.OffsetInBits;
2350   }
2351 }
2352 
2353 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2354                                                        llvm::Value *addr,
2355                                                        CGBuilderTy &Builder) {
2356   ASTContext &C = CGM.getContext();
2357   const BlockDecl *blockDecl = block.getBlockDecl();
2358 
2359   // Collect some general information about the block's location.
2360   SourceLocation loc = blockDecl->getCaretLocation();
2361   llvm::DIFile tunit = getOrCreateFile(loc);
2362   unsigned line = getLineNumber(loc);
2363   unsigned column = getColumnNumber(loc);
2364 
2365   // Build the debug-info type for the block literal.
2366   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2367 
2368   const llvm::StructLayout *blockLayout =
2369     CGM.getTargetData().getStructLayout(block.StructureType);
2370 
2371   SmallVector<llvm::Value*, 16> fields;
2372   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2373                                    blockLayout->getElementOffsetInBits(0),
2374                                    tunit, tunit));
2375   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2376                                    blockLayout->getElementOffsetInBits(1),
2377                                    tunit, tunit));
2378   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2379                                    blockLayout->getElementOffsetInBits(2),
2380                                    tunit, tunit));
2381   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2382                                    blockLayout->getElementOffsetInBits(3),
2383                                    tunit, tunit));
2384   fields.push_back(createFieldType("__descriptor",
2385                                    C.getPointerType(block.NeedsCopyDispose ?
2386                                         C.getBlockDescriptorExtendedType() :
2387                                         C.getBlockDescriptorType()),
2388                                    0, loc, AS_public,
2389                                    blockLayout->getElementOffsetInBits(4),
2390                                    tunit, tunit));
2391 
2392   // We want to sort the captures by offset, not because DWARF
2393   // requires this, but because we're paranoid about debuggers.
2394   SmallVector<BlockLayoutChunk, 8> chunks;
2395 
2396   // 'this' capture.
2397   if (blockDecl->capturesCXXThis()) {
2398     BlockLayoutChunk chunk;
2399     chunk.OffsetInBits =
2400       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2401     chunk.Capture = 0;
2402     chunks.push_back(chunk);
2403   }
2404 
2405   // Variable captures.
2406   for (BlockDecl::capture_const_iterator
2407          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2408        i != e; ++i) {
2409     const BlockDecl::Capture &capture = *i;
2410     const VarDecl *variable = capture.getVariable();
2411     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2412 
2413     // Ignore constant captures.
2414     if (captureInfo.isConstant())
2415       continue;
2416 
2417     BlockLayoutChunk chunk;
2418     chunk.OffsetInBits =
2419       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2420     chunk.Capture = &capture;
2421     chunks.push_back(chunk);
2422   }
2423 
2424   // Sort by offset.
2425   llvm::array_pod_sort(chunks.begin(), chunks.end());
2426 
2427   for (SmallVectorImpl<BlockLayoutChunk>::iterator
2428          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2429     uint64_t offsetInBits = i->OffsetInBits;
2430     const BlockDecl::Capture *capture = i->Capture;
2431 
2432     // If we have a null capture, this must be the C++ 'this' capture.
2433     if (!capture) {
2434       const CXXMethodDecl *method =
2435         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2436       QualType type = method->getThisType(C);
2437 
2438       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2439                                        offsetInBits, tunit, tunit));
2440       continue;
2441     }
2442 
2443     const VarDecl *variable = capture->getVariable();
2444     StringRef name = variable->getName();
2445 
2446     llvm::DIType fieldType;
2447     if (capture->isByRef()) {
2448       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2449 
2450       // FIXME: this creates a second copy of this type!
2451       uint64_t xoffset;
2452       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2453       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2454       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2455                                             ptrInfo.first, ptrInfo.second,
2456                                             offsetInBits, 0, fieldType);
2457     } else {
2458       fieldType = createFieldType(name, variable->getType(), 0,
2459                                   loc, AS_public, offsetInBits, tunit, tunit);
2460     }
2461     fields.push_back(fieldType);
2462   }
2463 
2464   SmallString<36> typeName;
2465   llvm::raw_svector_ostream(typeName)
2466     << "__block_literal_" << CGM.getUniqueBlockCount();
2467 
2468   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2469 
2470   llvm::DIType type =
2471     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2472                               CGM.getContext().toBits(block.BlockSize),
2473                               CGM.getContext().toBits(block.BlockAlign),
2474                               0, fieldsArray);
2475   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2476 
2477   // Get overall information about the block.
2478   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2479   llvm::MDNode *scope = LexicalBlockStack.back();
2480   StringRef name = ".block_descriptor";
2481 
2482   // Create the descriptor for the parameter.
2483   llvm::DIVariable debugVar =
2484     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2485                                  llvm::DIDescriptor(scope),
2486                                  name, tunit, line, type,
2487                                  CGM.getLangOptions().Optimize, flags,
2488                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2489 
2490   // Insert an llvm.dbg.value into the current block.
2491   llvm::Instruction *declare =
2492     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2493                                      Builder.GetInsertBlock());
2494   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2495 }
2496 
2497 /// EmitGlobalVariable - Emit information about a global variable.
2498 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2499                                      const VarDecl *D) {
2500   // Create global variable debug descriptor.
2501   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2502   unsigned LineNo = getLineNumber(D->getLocation());
2503 
2504   setLocation(D->getLocation());
2505 
2506   QualType T = D->getType();
2507   if (T->isIncompleteArrayType()) {
2508 
2509     // CodeGen turns int[] into int[1] so we'll do the same here.
2510     llvm::APSInt ConstVal(32);
2511 
2512     ConstVal = 1;
2513     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2514 
2515     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2516                                               ArrayType::Normal, 0);
2517   }
2518   StringRef DeclName = D->getName();
2519   StringRef LinkageName;
2520   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2521       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2522     LinkageName = Var->getName();
2523   if (LinkageName == DeclName)
2524     LinkageName = StringRef();
2525   llvm::DIDescriptor DContext =
2526     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2527   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2528                                 Unit, LineNo, getOrCreateType(T, Unit),
2529                                 Var->hasInternalLinkage(), Var);
2530 }
2531 
2532 /// EmitGlobalVariable - Emit information about an objective-c interface.
2533 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2534                                      ObjCInterfaceDecl *ID) {
2535   // Create global variable debug descriptor.
2536   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2537   unsigned LineNo = getLineNumber(ID->getLocation());
2538 
2539   StringRef Name = ID->getName();
2540 
2541   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2542   if (T->isIncompleteArrayType()) {
2543 
2544     // CodeGen turns int[] into int[1] so we'll do the same here.
2545     llvm::APSInt ConstVal(32);
2546 
2547     ConstVal = 1;
2548     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2549 
2550     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2551                                            ArrayType::Normal, 0);
2552   }
2553 
2554   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2555                                 getOrCreateType(T, Unit),
2556                                 Var->hasInternalLinkage(), Var);
2557 }
2558 
2559 /// EmitGlobalVariable - Emit global variable's debug info.
2560 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2561                                      llvm::Constant *Init) {
2562   // Create the descriptor for the variable.
2563   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2564   StringRef Name = VD->getName();
2565   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2566   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2567     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2568       Ty = CreateEnumType(ED);
2569   }
2570   // Do not use DIGlobalVariable for enums.
2571   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2572     return;
2573   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2574                                 getLineNumber(VD->getLocation()),
2575                                 Ty, true, Init);
2576 }
2577 
2578 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2579 /// namespace decl.
2580 llvm::DINameSpace
2581 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2582   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2583     NameSpaceCache.find(NSDecl);
2584   if (I != NameSpaceCache.end())
2585     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2586 
2587   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2588   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2589   llvm::DIDescriptor Context =
2590     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2591   llvm::DINameSpace NS =
2592     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2593   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2594   return NS;
2595 }
2596 
2597 void CGDebugInfo::finalize(void) {
2598   for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2599          = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2600     llvm::DIType Ty, RepTy;
2601     // Verify that the debug info still exists.
2602     if (&*VI->second)
2603       Ty = llvm::DIType(cast<llvm::MDNode>(VI->second));
2604 
2605     llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2606       TypeCache.find(VI->first);
2607     if (it != TypeCache.end()) {
2608       // Verify that the debug info still exists.
2609       if (&*it->second)
2610         RepTy = llvm::DIType(cast<llvm::MDNode>(it->second));
2611     }
2612 
2613     if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2614       Ty.replaceAllUsesWith(RepTy);
2615     }
2616   }
2617   DBuilder.finalize();
2618 }
2619