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