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