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