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