CGDebugInfo.cpp revision aca745b8b2eb58dc149ea7e65dfe133df2b0ab93
10ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
20ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//
30ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//                     The LLVM Compiler Infrastructure
40ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//
50ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong// This file is distributed under the University of Illinois Open Source
60ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong// License. See LICENSE.TXT for details.
70ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//
80ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//===----------------------------------------------------------------------===//
90ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//
100ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong// This coordinates the debug information generation while generating code.
110ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//
120ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong//===----------------------------------------------------------------------===//
130ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
140ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "CGDebugInfo.h"
150ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "CodeGenFunction.h"
160ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "CodeGenModule.h"
170ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/AST/ASTContext.h"
180ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/AST/DeclFriend.h"
190ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/AST/DeclObjC.h"
200ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/AST/DeclTemplate.h"
210ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/AST/Expr.h"
220ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/AST/RecordLayout.h"
230ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/Basic/SourceManager.h"
240ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/Basic/FileManager.h"
250ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/Basic/Version.h"
260ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "clang/Frontend/CodeGenOptions.h"
270ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/Constants.h"
280ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/DerivedTypes.h"
290ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/Instructions.h"
300ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/Intrinsics.h"
310ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/Module.h"
320ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/ADT/StringExtras.h"
330ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/ADT/SmallVector.h"
340ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/Support/Dwarf.h"
350ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/System/Path.h"
360ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong#include "llvm/Target/TargetMachine.h"
370ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongusing namespace clang;
380ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongusing namespace clang::CodeGen;
390ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
400ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus KongCGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
410ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  : CGM(CGM), DebugFactory(CGM.getModule()),
420ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    BlockLiteralGenericSet(false) {
430ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  CreateCompileUnit();
440ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
450ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
460ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus KongCGDebugInfo::~CGDebugInfo() {
470ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
480ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
490ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
500ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongvoid CGDebugInfo::setLocation(SourceLocation Loc) {
510ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (Loc.isValid())
520ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
530ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
540ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
550ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong/// getContextDescriptor - Get context info for the decl.
560ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongllvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
570ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                                              llvm::DIDescriptor &CompileUnit) {
580ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (!Context)
590ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return CompileUnit;
600ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
610ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
620ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    I = RegionMap.find(Context);
630ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (I != RegionMap.end())
640ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
650ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
660ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  // Check namespace.
670ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
680ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
690ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
700ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
710ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    if (!RDecl->isDependentType()) {
720ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong      llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
730ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                                        llvm::DIFile(CompileUnit));
740ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong      return llvm::DIDescriptor(Ty);
750ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    }
760ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  }
770ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  return CompileUnit;
780ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
790ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
800ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong/// getFunctionName - Get function name for the given FunctionDecl. If the
810ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong/// name is constructred on demand (e.g. C++ destructor) then the name
820ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong/// is stored on the side.
830ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongllvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
840ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  assert (FD && "Invalid FunctionDecl!");
850ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  IdentifierInfo *FII = FD->getIdentifier();
860ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (FII)
870ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return FII->getName();
880ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
890ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  // Otherwise construct human readable name for debug info.
900ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  std::string NS = FD->getNameAsString();
910ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
920ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  // Copy this name on the side and use its reference.
930ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
940ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  memcpy(StrPtr, NS.data(), NS.length());
950ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  return llvm::StringRef(StrPtr, NS.length());
960ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
970ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
980ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongllvm::StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
990ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  llvm::SmallString<256> MethodName;
1000ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  llvm::raw_svector_ostream OS(MethodName);
1010ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
1020ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  const DeclContext *DC = OMD->getDeclContext();
1030ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (const ObjCImplementationDecl *OID = dyn_cast<const ObjCImplementationDecl>(DC)) {
1040ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong     OS << OID->getName();
1050ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  } else if (const ObjCCategoryImplDecl *OCD = dyn_cast<const ObjCCategoryImplDecl>(DC)){
1060ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong      OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
1070ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong          OCD->getIdentifier()->getNameStart() << ')';
1080ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  }
1090ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  OS << ' ' << OMD->getSelector().getAsString() << ']';
1100ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1110ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
1120ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  memcpy(StrPtr, MethodName.begin(), OS.tell());
1130ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  return llvm::StringRef(StrPtr, OS.tell());
1140ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong}
1150ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1160ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong/// getClassName - Get class name including template argument list.
1170ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kongllvm::StringRef
1180ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus KongCGDebugInfo::getClassName(RecordDecl *RD) {
1190ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  ClassTemplateSpecializationDecl *Spec
1200ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    = dyn_cast<ClassTemplateSpecializationDecl>(RD);
1210ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (!Spec)
1220ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    return RD->getName();
1230ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong
1240ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  const TemplateArgument *Args;
1250ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  unsigned NumArgs;
1260ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  std::string Buffer;
1270ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
1280ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    const TemplateSpecializationType *TST =
1290ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong      cast<TemplateSpecializationType>(TAW->getType());
1300ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    Args = TST->getArgs();
1310ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    NumArgs = TST->getNumArgs();
1320ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  } else {
1330ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1340ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    Args = TemplateArgs.getFlatArgumentList();
1350ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong    NumArgs = TemplateArgs.flat_size();
1360ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  }
1370ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  Buffer = RD->getIdentifier()->getNameStart();
1380ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  PrintingPolicy Policy(CGM.getLangOptions());
1390ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong  Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
1400ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                                                                  NumArgs,
1410ae28bd5885b5daa526898fcf7c323dc2c3e1963Angus Kong                                                                  Policy);
142
143  // Copy this name on the side and use its reference.
144  char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
145  memcpy(StrPtr, Buffer.data(), Buffer.length());
146  return llvm::StringRef(StrPtr, Buffer.length());
147
148}
149
150/// getOrCreateFile - Get the file debug info descriptor for the input location.
151llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
152  if (!Loc.isValid())
153    // If Location is not valid then use main input file.
154    return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
155                                   TheCU);
156  SourceManager &SM = CGM.getContext().getSourceManager();
157  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
158
159  // Cache the results.
160  const char *fname = PLoc.getFilename();
161  llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
162    DIFileCache.find(fname);
163
164  if (it != DIFileCache.end()) {
165    // Verify that the information still exists.
166    if (&*it->second)
167      return llvm::DIFile(cast<llvm::MDNode>(it->second));
168  }
169
170  llvm::DIFile F = DebugFactory.CreateFile(PLoc.getFilename(),
171                                           getCurrentDirname(), TheCU);
172
173  DIFileCache[fname] = F;
174  return F;
175
176}
177
178/// getLineNumber - Get line number for the location. If location is invalid
179/// then use current location.
180unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
181  assert (CurLoc.isValid() && "Invalid current location!");
182  SourceManager &SM = CGM.getContext().getSourceManager();
183  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
184  return PLoc.getLine();
185}
186
187/// getColumnNumber - Get column number for the location. If location is
188/// invalid then use current location.
189unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
190  assert (CurLoc.isValid() && "Invalid current location!");
191  SourceManager &SM = CGM.getContext().getSourceManager();
192  PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
193  return PLoc.getColumn();
194}
195
196llvm::StringRef CGDebugInfo::getCurrentDirname() {
197  if (!CWDName.empty())
198    return CWDName;
199  char *CompDirnamePtr = NULL;
200  llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
201  CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
202  memcpy(CompDirnamePtr, CWD.c_str(), CWD.size());
203  return CWDName = llvm::StringRef(CompDirnamePtr, CWD.size());
204}
205
206/// CreateCompileUnit - Create new compile unit.
207void CGDebugInfo::CreateCompileUnit() {
208
209  // Get absolute path name.
210  SourceManager &SM = CGM.getContext().getSourceManager();
211  std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
212  if (MainFileName.empty())
213    MainFileName = "<unknown>";
214
215  // The main file name provided via the "-main-file-name" option contains just
216  // the file name itself with no path information. This file name may have had
217  // a relative path, so we look into the actual file entry for the main
218  // file to determine the real absolute path for the file.
219  std::string MainFileDir;
220  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
221    MainFileDir = MainFile->getDir()->getName();
222    if (MainFileDir != ".")
223      MainFileName = MainFileDir + "/" + MainFileName;
224  }
225
226  // Save filename string.
227  char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
228  memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
229  llvm::StringRef Filename(FilenamePtr, MainFileName.length());
230
231  unsigned LangTag;
232  const LangOptions &LO = CGM.getLangOptions();
233  if (LO.CPlusPlus) {
234    if (LO.ObjC1)
235      LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
236    else
237      LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
238  } else if (LO.ObjC1) {
239    LangTag = llvm::dwarf::DW_LANG_ObjC;
240  } else if (LO.C99) {
241    LangTag = llvm::dwarf::DW_LANG_C99;
242  } else {
243    LangTag = llvm::dwarf::DW_LANG_C89;
244  }
245
246  std::string Producer = getClangFullVersion();
247
248  // Figure out which version of the ObjC runtime we have.
249  unsigned RuntimeVers = 0;
250  if (LO.ObjC1)
251    RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
252
253  // Create new compile unit.
254  TheCU = DebugFactory.CreateCompileUnit(
255    LangTag, Filename, getCurrentDirname(),
256    Producer, true,
257    LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
258}
259
260/// CreateType - Get the Basic type from the cache or create a new
261/// one if necessary.
262llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
263                                     llvm::DIFile Unit) {
264  unsigned Encoding = 0;
265  const char *BTName = NULL;
266  switch (BT->getKind()) {
267  default:
268  case BuiltinType::Void:
269    return llvm::DIType();
270  case BuiltinType::ObjCClass:
271    return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
272                                            Unit, "objc_class", Unit, 0, 0, 0, 0,
273                                            llvm::DIDescriptor::FlagFwdDecl,
274                                            llvm::DIType(), llvm::DIArray());
275  case BuiltinType::ObjCId: {
276    // typedef struct objc_class *Class;
277    // typedef struct objc_object {
278    //  Class isa;
279    // } *id;
280
281    llvm::DIType OCTy =
282      DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
283                                       Unit, "objc_class", Unit, 0, 0, 0, 0,
284                                       llvm::DIDescriptor::FlagFwdDecl,
285                                       llvm::DIType(), llvm::DIArray());
286    unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
287
288    llvm::DIType ISATy =
289      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
290                                     Unit, "", Unit,
291                                     0, Size, 0, 0, 0, OCTy);
292
293    llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
294
295    llvm::DIType FieldTy =
296      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
297                                     "isa", Unit,
298                                     0,Size, 0, 0, 0, ISATy);
299    EltTys.push_back(FieldTy);
300    llvm::DIArray Elements =
301      DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
302
303    return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
304                                            Unit, "objc_object", Unit, 0, 0, 0, 0,
305                                            0,
306                                            llvm::DIType(), Elements);
307  }
308  case BuiltinType::UChar:
309  case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
310  case BuiltinType::Char_S:
311  case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
312  case BuiltinType::UShort:
313  case BuiltinType::UInt:
314  case BuiltinType::ULong:
315  case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
316  case BuiltinType::Short:
317  case BuiltinType::Int:
318  case BuiltinType::Long:
319  case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
320  case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
321  case BuiltinType::Float:
322  case BuiltinType::LongDouble:
323  case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
324  }
325
326  switch (BT->getKind()) {
327  case BuiltinType::Long:      BTName = "long int"; break;
328  case BuiltinType::LongLong:  BTName = "long long int"; break;
329  case BuiltinType::ULong:     BTName = "long unsigned int"; break;
330  case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
331  default:
332    BTName = BT->getName(CGM.getContext().getLangOptions());
333    break;
334  }
335  // Bit size, align and offset of the type.
336  uint64_t Size = CGM.getContext().getTypeSize(BT);
337  uint64_t Align = CGM.getContext().getTypeAlign(BT);
338  uint64_t Offset = 0;
339
340  llvm::DIType DbgTy =
341    DebugFactory.CreateBasicType(Unit, BTName,
342                                 Unit, 0, Size, Align,
343                                 Offset, /*flags*/ 0, Encoding);
344  return DbgTy;
345}
346
347llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
348                                     llvm::DIFile Unit) {
349  // Bit size, align and offset of the type.
350  unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
351  if (Ty->isComplexIntegerType())
352    Encoding = llvm::dwarf::DW_ATE_lo_user;
353
354  uint64_t Size = CGM.getContext().getTypeSize(Ty);
355  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
356  uint64_t Offset = 0;
357
358  llvm::DIType DbgTy =
359    DebugFactory.CreateBasicType(Unit, "complex",
360                                 Unit, 0, Size, Align,
361                                 Offset, /*flags*/ 0, Encoding);
362  return DbgTy;
363}
364
365/// CreateCVRType - Get the qualified type from the cache or create
366/// a new one if necessary.
367llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
368  QualifierCollector Qc;
369  const Type *T = Qc.strip(Ty);
370
371  // Ignore these qualifiers for now.
372  Qc.removeObjCGCAttr();
373  Qc.removeAddressSpace();
374
375  // We will create one Derived type for one qualifier and recurse to handle any
376  // additional ones.
377  unsigned Tag;
378  if (Qc.hasConst()) {
379    Tag = llvm::dwarf::DW_TAG_const_type;
380    Qc.removeConst();
381  } else if (Qc.hasVolatile()) {
382    Tag = llvm::dwarf::DW_TAG_volatile_type;
383    Qc.removeVolatile();
384  } else if (Qc.hasRestrict()) {
385    Tag = llvm::dwarf::DW_TAG_restrict_type;
386    Qc.removeRestrict();
387  } else {
388    assert(Qc.empty() && "Unknown type qualifier for debug info");
389    return getOrCreateType(QualType(T, 0), Unit);
390  }
391
392  llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
393
394  // No need to fill in the Name, Line, Size, Alignment, Offset in case of
395  // CVR derived types.
396  llvm::DIType DbgTy =
397    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
398                                   0, 0, 0, 0, 0, FromTy);
399  return DbgTy;
400}
401
402llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
403                                     llvm::DIFile Unit) {
404  llvm::DIType DbgTy =
405    CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
406                          Ty->getPointeeType(), Unit);
407  return DbgTy;
408}
409
410llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
411                                     llvm::DIFile Unit) {
412  return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
413                               Ty->getPointeeType(), Unit);
414}
415
416llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
417                                                const Type *Ty,
418                                                QualType PointeeTy,
419                                                llvm::DIFile Unit) {
420  llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
421
422  // Bit size, align and offset of the type.
423
424  // Size is always the size of a pointer. We can't use getTypeSize here
425  // because that does not return the correct value for references.
426  uint64_t Size =
427    CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
428  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
429
430  return
431    DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
432                                   0, Size, Align, 0, 0, EltTy);
433
434}
435
436llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
437                                     llvm::DIFile Unit) {
438  if (BlockLiteralGenericSet)
439    return BlockLiteralGeneric;
440
441  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
442
443  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
444
445  llvm::DIType FieldTy;
446
447  QualType FType;
448  uint64_t FieldSize, FieldOffset;
449  unsigned FieldAlign;
450
451  llvm::DIArray Elements;
452  llvm::DIType EltTy, DescTy;
453
454  FieldOffset = 0;
455  FType = CGM.getContext().UnsignedLongTy;
456  EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
457  EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
458
459  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
460  EltTys.clear();
461
462  unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
463  unsigned LineNo = getLineNumber(CurLoc);
464
465  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
466                                           Unit, LineNo, FieldOffset, 0, 0,
467                                           Flags, llvm::DIType(), Elements);
468
469  // Bit size, align and offset of the type.
470  uint64_t Size = CGM.getContext().getTypeSize(Ty);
471  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
472
473  DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
474                                          Unit, "", Unit,
475                                          LineNo, Size, Align, 0, 0, EltTy);
476
477  FieldOffset = 0;
478  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
479  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
480  FType = CGM.getContext().IntTy;
481  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
482  EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
483  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
484  EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
485
486  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
487  FieldTy = DescTy;
488  FieldSize = CGM.getContext().getTypeSize(Ty);
489  FieldAlign = CGM.getContext().getTypeAlign(Ty);
490  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
491                                           "__descriptor", Unit,
492                                           LineNo, FieldSize, FieldAlign,
493                                           FieldOffset, 0, FieldTy);
494  EltTys.push_back(FieldTy);
495
496  FieldOffset += FieldSize;
497  Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
498
499  EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
500                                           Unit, LineNo, FieldOffset, 0, 0,
501                                           Flags, llvm::DIType(), Elements);
502
503  BlockLiteralGenericSet = true;
504  BlockLiteralGeneric
505    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
506                                     "", Unit,
507                                     LineNo, Size, Align, 0, 0, EltTy);
508  return BlockLiteralGeneric;
509}
510
511llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
512                                     llvm::DIFile Unit) {
513  // Typedefs are derived from some other type.  If we have a typedef of a
514  // typedef, make sure to emit the whole chain.
515  llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
516
517  // We don't set size information, but do specify where the typedef was
518  // declared.
519  unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
520
521  llvm::DIDescriptor TyContext
522    = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
523                           Unit);
524  llvm::DIType DbgTy =
525    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef,
526                                   TyContext,
527                                   Ty->getDecl()->getName(), Unit,
528                                   Line, 0, 0, 0, 0, Src);
529  return DbgTy;
530}
531
532llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
533                                     llvm::DIFile Unit) {
534  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
535
536  // Add the result type at least.
537  EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
538
539  // Set up remainder of arguments if there is a prototype.
540  // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
541  if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
542    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
543      EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
544  } else {
545    // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
546  }
547
548  llvm::DIArray EltTypeArray =
549    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
550
551  llvm::DIType DbgTy =
552    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
553                                     Unit, "", Unit,
554                                     0, 0, 0, 0, 0,
555                                     llvm::DIType(), EltTypeArray);
556  return DbgTy;
557}
558
559/// CollectRecordFields - A helper function to collect debug info for
560/// record fields. This is used while creating debug info entry for a Record.
561void CGDebugInfo::
562CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
563                    llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
564  unsigned FieldNo = 0;
565  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
566  for (RecordDecl::field_iterator I = RD->field_begin(),
567                                  E = RD->field_end();
568       I != E; ++I, ++FieldNo) {
569    FieldDecl *Field = *I;
570    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
571    llvm::StringRef FieldName = Field->getName();
572
573    // Ignore unnamed fields. Do not ignore unnamed records.
574    if (FieldName.empty() && !isa<RecordType>(Field->getType()))
575      continue;
576
577    // Get the location for the field.
578    llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
579    unsigned FieldLine = getLineNumber(Field->getLocation());
580    QualType FType = Field->getType();
581    uint64_t FieldSize = 0;
582    unsigned FieldAlign = 0;
583    if (!FType->isIncompleteArrayType()) {
584
585      // Bit size, align and offset of the type.
586      FieldSize = CGM.getContext().getTypeSize(FType);
587      Expr *BitWidth = Field->getBitWidth();
588      if (BitWidth)
589        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
590      FieldAlign =  CGM.getContext().getTypeAlign(FType);
591    }
592
593    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
594
595    unsigned Flags = 0;
596    AccessSpecifier Access = I->getAccess();
597    if (Access == clang::AS_private)
598      Flags |= llvm::DIDescriptor::FlagPrivate;
599    else if (Access == clang::AS_protected)
600      Flags |= llvm::DIDescriptor::FlagProtected;
601
602    // Create a DW_TAG_member node to remember the offset of this field in the
603    // struct.  FIXME: This is an absolutely insane way to capture this
604    // information.  When we gut debug info, this should be fixed.
605    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
606                                             FieldName, FieldDefUnit,
607                                             FieldLine, FieldSize, FieldAlign,
608                                             FieldOffset, Flags, FieldTy);
609    EltTys.push_back(FieldTy);
610  }
611}
612
613/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
614/// function type is not updated to include implicit "this" pointer. Use this
615/// routine to get a method type which includes "this" pointer.
616llvm::DIType
617CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
618                                   llvm::DIFile Unit) {
619  llvm::DIType FnTy
620    = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
621                               0),
622                      Unit);
623
624  // Add "this" pointer.
625
626  llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
627  assert (Args.getNumElements() && "Invalid number of arguments!");
628
629  llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
630
631  // First element is always return type. For 'void' functions it is NULL.
632  Elts.push_back(Args.getElement(0));
633
634  if (!Method->isStatic())
635  {
636        // "this" pointer is always first argument.
637        ASTContext &Context = CGM.getContext();
638        QualType ThisPtr =
639          Context.getPointerType(Context.getTagDeclType(Method->getParent()));
640        llvm::DIType ThisPtrType =
641          DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
642
643        TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
644        Elts.push_back(ThisPtrType);
645    }
646
647  // Copy rest of the arguments.
648  for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
649    Elts.push_back(Args.getElement(i));
650
651  llvm::DIArray EltTypeArray =
652    DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
653
654  return
655    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
656                                     Unit, "", Unit,
657                                     0, 0, 0, 0, 0,
658                                     llvm::DIType(), EltTypeArray);
659}
660
661/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
662/// a single member function GlobalDecl.
663llvm::DISubprogram
664CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
665                                     llvm::DIFile Unit,
666                                     llvm::DIType RecordTy) {
667  bool IsCtorOrDtor =
668    isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
669
670  llvm::StringRef MethodName = getFunctionName(Method);
671  llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
672
673  // Since a single ctor/dtor corresponds to multiple functions, it doesn't
674  // make sense to give a single ctor/dtor a linkage name.
675  llvm::StringRef MethodLinkageName;
676  if (!IsCtorOrDtor)
677    MethodLinkageName = CGM.getMangledName(Method);
678
679  // Get the location for the method.
680  llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
681  unsigned MethodLine = getLineNumber(Method->getLocation());
682
683  // Collect virtual method info.
684  llvm::DIType ContainingType;
685  unsigned Virtuality = 0;
686  unsigned VIndex = 0;
687
688  if (Method->isVirtual()) {
689    if (Method->isPure())
690      Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
691    else
692      Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
693
694    // It doesn't make sense to give a virtual destructor a vtable index,
695    // since a single destructor has two entries in the vtable.
696    if (!isa<CXXDestructorDecl>(Method))
697      VIndex = CGM.getVTables().getMethodVTableIndex(Method);
698    ContainingType = RecordTy;
699  }
700
701  unsigned Flags = 0;
702  if (Method->isImplicit())
703    Flags |= llvm::DIDescriptor::FlagArtificial;
704  AccessSpecifier Access = Method->getAccess();
705  if (Access == clang::AS_private)
706    Flags |= llvm::DIDescriptor::FlagPrivate;
707  else if (Access == clang::AS_protected)
708    Flags |= llvm::DIDescriptor::FlagProtected;
709
710  llvm::DISubprogram SP =
711    DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName,
712                                  MethodLinkageName,
713                                  MethodDefUnit, MethodLine,
714                                  MethodTy, /*isLocalToUnit=*/false,
715                                  /* isDefintion=*/ false,
716                                  Virtuality, VIndex, ContainingType,
717                                  Flags,
718                                  CGM.getLangOptions().Optimize);
719
720  // Don't cache ctors or dtors since we have to emit multiple functions for
721  // a single ctor or dtor.
722  if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
723    SPCache[Method] = llvm::WeakVH(SP);
724
725  return SP;
726}
727
728/// CollectCXXMemberFunctions - A helper function to collect debug info for
729/// C++ member functions.This is used while creating debug info entry for
730/// a Record.
731void CGDebugInfo::
732CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
733                          llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
734                          llvm::DIType RecordTy) {
735  for(CXXRecordDecl::method_iterator I = RD->method_begin(),
736        E = RD->method_end(); I != E; ++I) {
737    const CXXMethodDecl *Method = *I;
738
739    if (Method->isImplicit() && !Method->isUsed())
740      continue;
741
742    EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
743  }
744}
745
746/// CollectCXXFriends - A helper function to collect debug info for
747/// C++ base classes. This is used while creating debug info entry for
748/// a Record.
749void CGDebugInfo::
750CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
751                llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
752                llvm::DIType RecordTy) {
753
754  for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
755         BE = RD->friend_end(); BI != BE; ++BI) {
756
757    TypeSourceInfo *TInfo = (*BI)->getFriendType();
758    if(TInfo)
759    {
760        llvm::DIType Ty = getOrCreateType(TInfo->getType(), Unit);
761
762            llvm::DIType DTy =
763          DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_friend,
764                                         RecordTy, llvm::StringRef(),
765                                         Unit, 0, 0, 0,
766                                         0, 0, Ty);
767
768        EltTys.push_back(DTy);
769    }
770
771  }
772}
773
774/// CollectCXXBases - A helper function to collect debug info for
775/// C++ base classes. This is used while creating debug info entry for
776/// a Record.
777void CGDebugInfo::
778CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
779                llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
780                llvm::DIType RecordTy) {
781
782  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
783  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
784         BE = RD->bases_end(); BI != BE; ++BI) {
785    unsigned BFlags = 0;
786    uint64_t BaseOffset;
787
788    const CXXRecordDecl *Base =
789      cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
790
791    if (BI->isVirtual()) {
792      // virtual base offset offset is -ve. The code generator emits dwarf
793      // expression where it expects +ve number.
794      BaseOffset = 0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base);
795      BFlags = llvm::DIDescriptor::FlagVirtual;
796    } else
797      BaseOffset = RL.getBaseClassOffset(Base);
798
799    AccessSpecifier Access = BI->getAccessSpecifier();
800    if (Access == clang::AS_private)
801      BFlags |= llvm::DIDescriptor::FlagPrivate;
802    else if (Access == clang::AS_protected)
803      BFlags |= llvm::DIDescriptor::FlagProtected;
804
805    llvm::DIType DTy =
806      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
807                                     RecordTy, llvm::StringRef(),
808                                     Unit, 0, 0, 0,
809                                     BaseOffset, BFlags,
810                                     getOrCreateType(BI->getType(),
811                                                     Unit));
812    EltTys.push_back(DTy);
813  }
814}
815
816/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
817llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
818  if (VTablePtrType.isValid())
819    return VTablePtrType;
820
821  ASTContext &Context = CGM.getContext();
822
823  /* Function type */
824  llvm::DIDescriptor STy = getOrCreateType(Context.IntTy, Unit);
825  llvm::DIArray SElements = DebugFactory.GetOrCreateArray(&STy, 1);
826  llvm::DIType SubTy =
827    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
828                                     Unit, "", Unit,
829                                     0, 0, 0, 0, 0, llvm::DIType(), SElements);
830
831  unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
832  llvm::DIType vtbl_ptr_type
833    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
834                                     Unit, "__vtbl_ptr_type", Unit,
835                                     0, Size, 0, 0, 0, SubTy);
836
837  VTablePtrType =
838    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
839                                   Unit, "", Unit,
840                                   0, Size, 0, 0, 0, vtbl_ptr_type);
841  return VTablePtrType;
842}
843
844/// getVTableName - Get vtable name for the given Class.
845llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
846  // Otherwise construct gdb compatible name name.
847  std::string Name = "_vptr$" + RD->getNameAsString();
848
849  // Copy this name on the side and use its reference.
850  char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
851  memcpy(StrPtr, Name.data(), Name.length());
852  return llvm::StringRef(StrPtr, Name.length());
853}
854
855
856/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
857/// debug info entry in EltTys vector.
858void CGDebugInfo::
859CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
860                  llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
861  const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
862
863  // If there is a primary base then it will hold vtable info.
864  if (RL.getPrimaryBase())
865    return;
866
867  // If this class is not dynamic then there is not any vtable info to collect.
868  if (!RD->isDynamicClass())
869    return;
870
871  unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
872  llvm::DIType VPTR
873    = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
874                                     getVTableName(RD), Unit,
875                                     0, Size, 0, 0, 0,
876                                     getOrCreateVTablePtrType(Unit));
877  EltTys.push_back(VPTR);
878}
879
880/// CreateType - get structure or union type.
881llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
882                                     llvm::DIFile Unit) {
883  RecordDecl *RD = Ty->getDecl();
884
885  unsigned Tag;
886  if (RD->isStruct())
887    Tag = llvm::dwarf::DW_TAG_structure_type;
888  else if (RD->isUnion())
889    Tag = llvm::dwarf::DW_TAG_union_type;
890  else {
891    assert(RD->isClass() && "Unknown RecordType!");
892    Tag = llvm::dwarf::DW_TAG_class_type;
893  }
894
895  // Get overall information about the record type for the debug info.
896  llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
897  unsigned Line = getLineNumber(RD->getLocation());
898
899  // Records and classes and unions can all be recursive.  To handle them, we
900  // first generate a debug descriptor for the struct as a forward declaration.
901  // Then (if it is a definition) we go through and get debug info for all of
902  // its members.  Finally, we create a descriptor for the complete type (which
903  // may refer to the forward decl if the struct is recursive) and replace all
904  // uses of the forward declaration with the final definition.
905  llvm::DIDescriptor FDContext =
906    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
907
908  // If this is just a forward declaration, construct an appropriately
909  // marked node and just return it.
910  if (!RD->getDefinition()) {
911    llvm::DICompositeType FwdDecl =
912      DebugFactory.CreateCompositeType(Tag, FDContext, RD->getName(),
913                                       DefUnit, Line, 0, 0, 0,
914                                       llvm::DIDescriptor::FlagFwdDecl,
915                                       llvm::DIType(), llvm::DIArray());
916
917      return FwdDecl;
918  }
919
920  llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType();
921
922  llvm::MDNode *MN = FwdDecl;
923  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
924  // Otherwise, insert it into the TypeCache so that recursive uses will find
925  // it.
926  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
927  // Push the struct on region stack.
928  RegionStack.push_back(FwdDeclNode);
929  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
930
931  // Convert all the elements.
932  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
933
934  const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
935  if (CXXDecl) {
936    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
937    CollectVTableInfo(CXXDecl, Unit, EltTys);
938  }
939
940  // Collect static variables with initializers.
941  for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
942       I != E; ++I)
943    if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
944      if (const Expr *Init = V->getInit()) {
945        Expr::EvalResult Result;
946        if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
947          llvm::ConstantInt *CI
948            = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
949
950          // Create the descriptor for static variable.
951          llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
952          llvm::StringRef VName = V->getName();
953          llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
954          // Do not use DIGlobalVariable for enums.
955          if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
956            DebugFactory.CreateGlobalVariable(FwdDecl, VName, VName, VName, VUnit,
957                                              getLineNumber(V->getLocation()),
958                                              VTy, true, true, CI);
959          }
960        }
961      }
962    }
963
964  CollectRecordFields(RD, Unit, EltTys);
965  llvm::MDNode *ContainingType = NULL;
966  if (CXXDecl) {
967    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
968    CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
969
970    // A class's primary base or the class itself contains the vtable.
971    const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
972    if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
973      ContainingType =
974        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
975    else if (CXXDecl->isDynamicClass())
976      ContainingType = FwdDecl;
977  }
978
979  llvm::DIArray Elements =
980    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
981
982  // Bit size, align and offset of the type.
983  uint64_t Size = CGM.getContext().getTypeSize(Ty);
984  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
985
986  RegionStack.pop_back();
987  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
988    RegionMap.find(Ty->getDecl());
989  if (RI != RegionMap.end())
990    RegionMap.erase(RI);
991
992  llvm::DIDescriptor RDContext =
993    getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
994
995  llvm::StringRef RDName = RD->getName();
996  // If this is a class, include the template arguments also.
997  if (Tag == llvm::dwarf::DW_TAG_class_type)
998    RDName = getClassName(RD);
999
1000  llvm::DICompositeType RealDecl =
1001    DebugFactory.CreateCompositeType(Tag, RDContext,
1002                                     RDName,
1003                                     DefUnit, Line, Size, Align, 0, 0,
1004                                     llvm::DIType(), Elements,
1005                                     0, ContainingType);
1006
1007  // Now that we have a real decl for the struct, replace anything using the
1008  // old decl with the new one.  This will recursively update the debug info.
1009  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1010  RegionMap[RD] = llvm::WeakVH(RealDecl);
1011  return RealDecl;
1012}
1013
1014/// CreateType - get objective-c object type.
1015llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1016                                     llvm::DIFile Unit) {
1017  // Ignore protocols.
1018  return getOrCreateType(Ty->getBaseType(), Unit);
1019}
1020
1021/// CreateType - get objective-c interface type.
1022llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1023                                     llvm::DIFile Unit) {
1024  ObjCInterfaceDecl *ID = Ty->getDecl();
1025  unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
1026
1027  // Get overall information about the record type for the debug info.
1028  llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1029  unsigned Line = getLineNumber(ID->getLocation());
1030  unsigned RuntimeLang = TheCU.getLanguage();
1031
1032  // If this is just a forward declaration, return a special forward-declaration
1033  // debug type.
1034  if (ID->isForwardDecl()) {
1035    llvm::DICompositeType FwdDecl =
1036      DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
1037                                       DefUnit, Line, 0, 0, 0, 0,
1038                                       llvm::DIType(), llvm::DIArray(),
1039                                       RuntimeLang);
1040    return FwdDecl;
1041  }
1042
1043  // To handle recursive interface, we
1044  // first generate a debug descriptor for the struct as a forward declaration.
1045  // Then (if it is a definition) we go through and get debug info for all of
1046  // its members.  Finally, we create a descriptor for the complete type (which
1047  // may refer to the forward decl if the struct is recursive) and replace all
1048  // uses of the forward declaration with the final definition.
1049  llvm::DIType FwdDecl = DebugFactory.CreateTemporaryType();
1050
1051  llvm::MDNode *MN = FwdDecl;
1052  llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1053  // Otherwise, insert it into the TypeCache so that recursive uses will find
1054  // it.
1055  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1056  // Push the struct on region stack.
1057  RegionStack.push_back(FwdDeclNode);
1058  RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1059
1060  // Convert all the elements.
1061  llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
1062
1063  ObjCInterfaceDecl *SClass = ID->getSuperClass();
1064  if (SClass) {
1065    llvm::DIType SClassTy =
1066      getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1067    llvm::DIType InhTag =
1068      DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
1069                                     Unit, "", Unit, 0, 0, 0,
1070                                     0 /* offset */, 0, SClassTy);
1071    EltTys.push_back(InhTag);
1072  }
1073
1074  const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1075
1076  unsigned FieldNo = 0;
1077  for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
1078         E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
1079    ObjCIvarDecl *Field = *I;
1080    llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1081
1082    llvm::StringRef FieldName = Field->getName();
1083
1084    // Ignore unnamed fields.
1085    if (FieldName.empty())
1086      continue;
1087
1088    // Get the location for the field.
1089    llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1090    unsigned FieldLine = getLineNumber(Field->getLocation());
1091    QualType FType = Field->getType();
1092    uint64_t FieldSize = 0;
1093    unsigned FieldAlign = 0;
1094
1095    if (!FType->isIncompleteArrayType()) {
1096
1097      // Bit size, align and offset of the type.
1098      FieldSize = CGM.getContext().getTypeSize(FType);
1099      Expr *BitWidth = Field->getBitWidth();
1100      if (BitWidth)
1101        FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
1102
1103      FieldAlign =  CGM.getContext().getTypeAlign(FType);
1104    }
1105
1106    uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
1107
1108    unsigned Flags = 0;
1109    if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1110      Flags = llvm::DIDescriptor::FlagProtected;
1111    else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1112      Flags = llvm::DIDescriptor::FlagPrivate;
1113
1114    // Create a DW_TAG_member node to remember the offset of this field in the
1115    // struct.  FIXME: This is an absolutely insane way to capture this
1116    // information.  When we gut debug info, this should be fixed.
1117    FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1118                                             FieldName, FieldDefUnit,
1119                                             FieldLine, FieldSize, FieldAlign,
1120                                             FieldOffset, Flags, FieldTy);
1121    EltTys.push_back(FieldTy);
1122  }
1123
1124  llvm::DIArray Elements =
1125    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1126
1127  RegionStack.pop_back();
1128  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1129    RegionMap.find(Ty->getDecl());
1130  if (RI != RegionMap.end())
1131    RegionMap.erase(RI);
1132
1133  // Bit size, align and offset of the type.
1134  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1135  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1136
1137  llvm::DICompositeType RealDecl =
1138    DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
1139                                     Line, Size, Align, 0, 0, llvm::DIType(),
1140                                     Elements, RuntimeLang);
1141
1142  // Now that we have a real decl for the struct, replace anything using the
1143  // old decl with the new one.  This will recursively update the debug info.
1144  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1145  RegionMap[ID] = llvm::WeakVH(RealDecl);
1146
1147  return RealDecl;
1148}
1149
1150llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
1151                                     llvm::DIFile Unit) {
1152  return CreateEnumType(Ty->getDecl(), Unit);
1153
1154}
1155
1156llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1157                                     llvm::DIFile Unit) {
1158  if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1159    return CreateType(RT, Unit);
1160  else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1161    return CreateType(ET, Unit);
1162
1163  return llvm::DIType();
1164}
1165
1166llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1167                                     llvm::DIFile Unit) {
1168  llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1169  uint64_t NumElems = Ty->getNumElements();
1170  if (NumElems > 0)
1171    --NumElems;
1172
1173  llvm::DIDescriptor Subscript = DebugFactory.GetOrCreateSubrange(0, NumElems);
1174  llvm::DIArray SubscriptArray = DebugFactory.GetOrCreateArray(&Subscript, 1);
1175
1176  uint64_t Size = CGM.getContext().getTypeSize(Ty);
1177  uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1178
1179  return
1180    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1181                                     Unit, "", Unit,
1182                                     0, Size, Align, 0, 0,
1183                                     ElementTy,  SubscriptArray);
1184}
1185
1186llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1187                                     llvm::DIFile Unit) {
1188  uint64_t Size;
1189  uint64_t Align;
1190
1191
1192  // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1193  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1194    Size = 0;
1195    Align =
1196      CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1197  } else if (Ty->isIncompleteArrayType()) {
1198    Size = 0;
1199    Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1200  } else {
1201    // Size and align of the whole array, not the element type.
1202    Size = CGM.getContext().getTypeSize(Ty);
1203    Align = CGM.getContext().getTypeAlign(Ty);
1204  }
1205
1206  // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1207  // interior arrays, do we care?  Why aren't nested arrays represented the
1208  // obvious/recursive way?
1209  llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1210  QualType EltTy(Ty, 0);
1211  while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1212    uint64_t Upper = 0;
1213    if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1214      if (CAT->getSize().getZExtValue())
1215        Upper = CAT->getSize().getZExtValue() - 1;
1216    // FIXME: Verify this is right for VLAs.
1217    Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1218    EltTy = Ty->getElementType();
1219  }
1220
1221  llvm::DIArray SubscriptArray =
1222    DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1223
1224  llvm::DIType DbgTy =
1225    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1226                                     Unit, "", Unit,
1227                                     0, Size, Align, 0, 0,
1228                                     getOrCreateType(EltTy, Unit),
1229                                     SubscriptArray);
1230  return DbgTy;
1231}
1232
1233llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1234                                     llvm::DIFile Unit) {
1235  return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1236                               Ty, Ty->getPointeeType(), Unit);
1237}
1238
1239llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1240                                     llvm::DIFile U) {
1241  QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1242  llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1243
1244  if (!Ty->getPointeeType()->isFunctionType()) {
1245    // We have a data member pointer type.
1246    return PointerDiffDITy;
1247  }
1248
1249  // We have a member function pointer type. Treat it as a struct with two
1250  // ptrdiff_t members.
1251  std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1252
1253  uint64_t FieldOffset = 0;
1254  llvm::DIDescriptor ElementTypes[2];
1255
1256  // FIXME: This should probably be a function type instead.
1257  ElementTypes[0] =
1258    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1259                                   "ptr", U, 0,
1260                                   Info.first, Info.second, FieldOffset, 0,
1261                                   PointerDiffDITy);
1262  FieldOffset += Info.first;
1263
1264  ElementTypes[1] =
1265    DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1266                                   "ptr", U, 0,
1267                                   Info.first, Info.second, FieldOffset, 0,
1268                                   PointerDiffDITy);
1269
1270  llvm::DIArray Elements =
1271    DebugFactory.GetOrCreateArray(&ElementTypes[0],
1272                                  llvm::array_lengthof(ElementTypes));
1273
1274  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1275                                          U, llvm::StringRef("test"),
1276                                          U, 0, FieldOffset,
1277                                          0, 0, 0, llvm::DIType(), Elements);
1278}
1279
1280/// CreateEnumType - get enumeration type.
1281llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED, llvm::DIFile Unit){
1282  llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
1283
1284  // Create DIEnumerator elements for each enumerator.
1285  for (EnumDecl::enumerator_iterator
1286         Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1287       Enum != EnumEnd; ++Enum) {
1288    Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
1289                                            Enum->getInitVal().getZExtValue()));
1290  }
1291
1292  // Return a CompositeType for the enum itself.
1293  llvm::DIArray EltArray =
1294    DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1295
1296  llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1297  unsigned Line = getLineNumber(ED->getLocation());
1298  uint64_t Size = 0;
1299  uint64_t Align = 0;
1300  if (!ED->getTypeForDecl()->isIncompleteType()) {
1301    Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1302    Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1303  }
1304  llvm::DIType DbgTy =
1305    DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1306                                     Unit, ED->getName(), DefUnit, Line,
1307                                     Size, Align, 0, 0,
1308                                     llvm::DIType(), EltArray);
1309  return DbgTy;
1310}
1311
1312static QualType UnwrapTypeForDebugInfo(QualType T) {
1313  do {
1314    QualType LastT = T;
1315    switch (T->getTypeClass()) {
1316    default:
1317      return T;
1318    case Type::TemplateSpecialization:
1319      T = cast<TemplateSpecializationType>(T)->desugar();
1320      break;
1321    case Type::TypeOfExpr: {
1322      TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1323      T = Ty->getUnderlyingExpr()->getType();
1324      break;
1325    }
1326    case Type::TypeOf:
1327      T = cast<TypeOfType>(T)->getUnderlyingType();
1328      break;
1329    case Type::Decltype:
1330      T = cast<DecltypeType>(T)->getUnderlyingType();
1331      break;
1332    case Type::Elaborated:
1333      T = cast<ElaboratedType>(T)->getNamedType();
1334      break;
1335    case Type::SubstTemplateTypeParm:
1336      T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1337      break;
1338    }
1339
1340    assert(T != LastT && "Type unwrapping failed to unwrap!");
1341    if (T == LastT)
1342      return T;
1343  } while (true);
1344
1345  return T;
1346}
1347
1348/// getOrCreateType - Get the type from the cache or create a new
1349/// one if necessary.
1350llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1351                                          llvm::DIFile Unit) {
1352  if (Ty.isNull())
1353    return llvm::DIType();
1354
1355  // Unwrap the type as needed for debug information.
1356  Ty = UnwrapTypeForDebugInfo(Ty);
1357
1358  // Check for existing entry.
1359  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1360    TypeCache.find(Ty.getAsOpaquePtr());
1361  if (it != TypeCache.end()) {
1362    // Verify that the debug info still exists.
1363    if (&*it->second)
1364      return llvm::DIType(cast<llvm::MDNode>(it->second));
1365  }
1366
1367  // Otherwise create the type.
1368  llvm::DIType Res = CreateTypeNode(Ty, Unit);
1369
1370  // And update the type cache.
1371  TypeCache[Ty.getAsOpaquePtr()] = Res;
1372  return Res;
1373}
1374
1375/// CreateTypeNode - Create a new debug type node.
1376llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1377                                         llvm::DIFile Unit) {
1378  // Handle qualifiers, which recursively handles what they refer to.
1379  if (Ty.hasLocalQualifiers())
1380    return CreateQualifiedType(Ty, Unit);
1381
1382  const char *Diag = 0;
1383
1384  // Work out details of type.
1385  switch (Ty->getTypeClass()) {
1386#define TYPE(Class, Base)
1387#define ABSTRACT_TYPE(Class, Base)
1388#define NON_CANONICAL_TYPE(Class, Base)
1389#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1390#include "clang/AST/TypeNodes.def"
1391    assert(false && "Dependent types cannot show up in debug information");
1392
1393  // FIXME: Handle these.
1394  case Type::ExtVector:
1395    return llvm::DIType();
1396
1397  case Type::Vector:
1398    return CreateType(cast<VectorType>(Ty), Unit);
1399  case Type::ObjCObjectPointer:
1400    return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1401  case Type::ObjCObject:
1402    return CreateType(cast<ObjCObjectType>(Ty), Unit);
1403  case Type::ObjCInterface:
1404    return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1405  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1406  case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1407  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1408  case Type::BlockPointer:
1409    return CreateType(cast<BlockPointerType>(Ty), Unit);
1410  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1411  case Type::Record:
1412  case Type::Enum:
1413    return CreateType(cast<TagType>(Ty), Unit);
1414  case Type::FunctionProto:
1415  case Type::FunctionNoProto:
1416    return CreateType(cast<FunctionType>(Ty), Unit);
1417  case Type::ConstantArray:
1418  case Type::VariableArray:
1419  case Type::IncompleteArray:
1420    return CreateType(cast<ArrayType>(Ty), Unit);
1421
1422  case Type::LValueReference:
1423    return CreateType(cast<LValueReferenceType>(Ty), Unit);
1424
1425  case Type::MemberPointer:
1426    return CreateType(cast<MemberPointerType>(Ty), Unit);
1427
1428  case Type::TemplateSpecialization:
1429  case Type::Elaborated:
1430  case Type::SubstTemplateTypeParm:
1431  case Type::TypeOfExpr:
1432  case Type::TypeOf:
1433  case Type::Decltype:
1434    llvm_unreachable("type should have been unwrapped!");
1435    return llvm::DIType();
1436
1437  case Type::RValueReference:
1438    // FIXME: Implement!
1439    Diag = "rvalue references";
1440    break;
1441  }
1442
1443  assert(Diag && "Fall through without a diagnostic?");
1444  unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1445                               "debug information for %0 is not yet supported");
1446  CGM.getDiags().Report(FullSourceLoc(), DiagID)
1447    << Diag;
1448  return llvm::DIType();
1449}
1450
1451/// CreateMemberType - Create new member and increase Offset by FType's size.
1452llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1453                                           llvm::StringRef Name,
1454                                           uint64_t *Offset) {
1455  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1456  uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1457  unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1458  llvm::DIType Ty = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1459                                                   Unit, Name, Unit, 0,
1460                                                   FieldSize, FieldAlign,
1461                                                   *Offset, 0, FieldTy);
1462  *Offset += FieldSize;
1463  return Ty;
1464}
1465
1466/// EmitFunctionStart - Constructs the debug code for entering a function -
1467/// "llvm.dbg.func.start.".
1468void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1469                                    llvm::Function *Fn,
1470                                    CGBuilderTy &Builder) {
1471
1472  llvm::StringRef Name;
1473  llvm::StringRef LinkageName;
1474
1475  FnBeginRegionCount.push_back(RegionStack.size());
1476
1477  const Decl *D = GD.getDecl();
1478  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1479    // If there is a DISubprogram for  this function available then use it.
1480    llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1481      FI = SPCache.find(FD);
1482    if (FI != SPCache.end()) {
1483      llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1484      if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1485        llvm::MDNode *SPN = SP;
1486        RegionStack.push_back(SPN);
1487        RegionMap[D] = llvm::WeakVH(SP);
1488        return;
1489      }
1490    }
1491    Name = getFunctionName(FD);
1492    // Use mangled name as linkage name for c/c++ functions.
1493    LinkageName = CGM.getMangledName(GD);
1494  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1495    Name = getObjCMethodName(OMD);
1496    LinkageName = Name;
1497  } else {
1498    // Use llvm function name as linkage name.
1499    Name = Fn->getName();
1500    LinkageName = Name;
1501  }
1502  if (!Name.empty() && Name[0] == '\01')
1503    Name = Name.substr(1);
1504
1505  // It is expected that CurLoc is set before using EmitFunctionStart.
1506  // Usually, CurLoc points to the left bracket location of compound
1507  // statement representing function body.
1508  llvm::DIFile Unit = getOrCreateFile(CurLoc);
1509  unsigned LineNo = getLineNumber(CurLoc);
1510  unsigned Flags = 0;
1511  if (D->isImplicit())
1512    Flags |= llvm::DIDescriptor::FlagArtificial;
1513  llvm::DISubprogram SP =
1514    DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1515                                  getOrCreateType(FnType, Unit),
1516                                  Fn->hasInternalLinkage(), true/*definition*/,
1517                                  0, 0, llvm::DIType(),
1518                                  Flags,
1519                                  CGM.getLangOptions().Optimize, Fn);
1520
1521  // Push function on region stack.
1522  llvm::MDNode *SPN = SP;
1523  RegionStack.push_back(SPN);
1524  RegionMap[D] = llvm::WeakVH(SP);
1525
1526  // Clear stack used to keep track of #line directives.
1527  LineDirectiveFiles.clear();
1528}
1529
1530
1531void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1532  if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1533
1534  // Don't bother if things are the same as last time.
1535  SourceManager &SM = CGM.getContext().getSourceManager();
1536  if (CurLoc == PrevLoc
1537       || (SM.getInstantiationLineNumber(CurLoc) ==
1538           SM.getInstantiationLineNumber(PrevLoc)
1539           && SM.isFromSameFile(CurLoc, PrevLoc)))
1540    // New Builder may not be in sync with CGDebugInfo.
1541    if (!Builder.getCurrentDebugLocation().isUnknown())
1542      return;
1543
1544  // Update last state.
1545  PrevLoc = CurLoc;
1546
1547  llvm::MDNode *Scope = RegionStack.back();
1548  Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1549                                                      getColumnNumber(CurLoc),
1550                                                      Scope));
1551}
1552
1553/// UpdateLineDirectiveRegion - Update region stack only if #line directive
1554/// has introduced scope change.
1555void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1556  if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1557      PrevLoc.isInvalid() || PrevLoc.isMacroID())
1558    return;
1559  SourceManager &SM = CGM.getContext().getSourceManager();
1560  PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1561  PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1562
1563  if (!strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1564    return;
1565
1566  // If #line directive stack is empty then we are entering a new scope.
1567  if (LineDirectiveFiles.empty()) {
1568    EmitRegionStart(Builder);
1569    LineDirectiveFiles.push_back(PCLoc.getFilename());
1570    return;
1571  }
1572
1573  assert (RegionStack.size() >= LineDirectiveFiles.size()
1574          && "error handling  #line regions!");
1575
1576  bool SeenThisFile = false;
1577  // Chek if current file is already seen earlier.
1578  for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1579        E = LineDirectiveFiles.end(); I != E; ++I)
1580    if (!strcmp(PCLoc.getFilename(), *I)) {
1581      SeenThisFile = true;
1582      break;
1583    }
1584
1585  // If #line for this file is seen earlier then pop out #line regions.
1586  if (SeenThisFile) {
1587    while (!LineDirectiveFiles.empty()) {
1588      const char *LastFile = LineDirectiveFiles.back();
1589      RegionStack.pop_back();
1590      LineDirectiveFiles.pop_back();
1591      if (!strcmp(PPLoc.getFilename(), LastFile))
1592        break;
1593    }
1594    return;
1595  }
1596
1597  // .. otherwise insert new #line region.
1598  EmitRegionStart(Builder);
1599  LineDirectiveFiles.push_back(PCLoc.getFilename());
1600
1601  return;
1602}
1603/// EmitRegionStart- Constructs the debug code for entering a declarative
1604/// region - "llvm.dbg.region.start.".
1605void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1606  llvm::DIDescriptor D =
1607    DebugFactory.CreateLexicalBlock(RegionStack.empty() ?
1608                                    llvm::DIDescriptor() :
1609                                    llvm::DIDescriptor(RegionStack.back()),
1610                                    getOrCreateFile(CurLoc),
1611                                    getLineNumber(CurLoc),
1612                                    getColumnNumber(CurLoc));
1613  llvm::MDNode *DN = D;
1614  RegionStack.push_back(DN);
1615}
1616
1617/// EmitRegionEnd - Constructs the debug code for exiting a declarative
1618/// region - "llvm.dbg.region.end."
1619void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1620  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1621
1622  // Provide an region stop point.
1623  EmitStopPoint(Builder);
1624
1625  RegionStack.pop_back();
1626}
1627
1628/// EmitFunctionEnd - Constructs the debug code for exiting a function.
1629void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1630  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1631  unsigned RCount = FnBeginRegionCount.back();
1632  assert(RCount <= RegionStack.size() && "Region stack mismatch");
1633
1634  // Pop all regions for this function.
1635  while (RegionStack.size() != RCount)
1636    EmitRegionEnd(Builder);
1637  FnBeginRegionCount.pop_back();
1638}
1639
1640// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1641// See BuildByRefType.
1642llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1643                                                       uint64_t *XOffset) {
1644
1645  llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1646
1647  QualType FType;
1648  uint64_t FieldSize, FieldOffset;
1649  unsigned FieldAlign;
1650
1651  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1652  QualType Type = VD->getType();
1653
1654  FieldOffset = 0;
1655  FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1656  EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1657  EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1658  FType = CGM.getContext().IntTy;
1659  EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1660  EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1661
1662  bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1663  if (HasCopyAndDispose) {
1664    FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1665    EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1666                                      &FieldOffset));
1667    EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1668                                      &FieldOffset));
1669  }
1670
1671  CharUnits Align = CGM.getContext().getDeclAlign(VD);
1672  if (Align > CharUnits::fromQuantity(
1673        CGM.getContext().Target.getPointerAlign(0) / 8)) {
1674    unsigned AlignedOffsetInBytes
1675      = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1676    unsigned NumPaddingBytes
1677      = AlignedOffsetInBytes - FieldOffset/8;
1678
1679    if (NumPaddingBytes > 0) {
1680      llvm::APInt pad(32, NumPaddingBytes);
1681      FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1682                                                    pad, ArrayType::Normal, 0);
1683      EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1684    }
1685  }
1686
1687  FType = Type;
1688  llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1689  FieldSize = CGM.getContext().getTypeSize(FType);
1690  FieldAlign = Align.getQuantity()*8;
1691
1692  *XOffset = FieldOffset;
1693  FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1694                                           VD->getName(), Unit,
1695                                           0, FieldSize, FieldAlign,
1696                                           FieldOffset, 0, FieldTy);
1697  EltTys.push_back(FieldTy);
1698  FieldOffset += FieldSize;
1699
1700  llvm::DIArray Elements =
1701    DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1702
1703  unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1704
1705  return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type,
1706                                          Unit, "", Unit,
1707                                          0, FieldOffset, 0, 0, Flags,
1708                                          llvm::DIType(), Elements);
1709
1710}
1711/// EmitDeclare - Emit local variable declaration debug info.
1712void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1713                              llvm::Value *Storage, CGBuilderTy &Builder) {
1714  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1715
1716  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1717  llvm::DIType Ty;
1718  uint64_t XOffset = 0;
1719  if (VD->hasAttr<BlocksAttr>())
1720    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1721  else
1722    Ty = getOrCreateType(VD->getType(), Unit);
1723
1724  // If there is not any debug info for type then do not emit debug info
1725  // for this variable.
1726  if (!Ty)
1727    return;
1728
1729  // Get location information.
1730  unsigned Line = getLineNumber(VD->getLocation());
1731  unsigned Column = getColumnNumber(VD->getLocation());
1732  unsigned Flags = 0;
1733  if (VD->isImplicit())
1734    Flags |= llvm::DIDescriptor::FlagArtificial;
1735  // Create the descriptor for the variable.
1736  llvm::DIVariable D =
1737    DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1738                                VD->getName(), Unit, Line, Ty,
1739                                CGM.getLangOptions().Optimize, Flags);
1740
1741  // Insert an llvm.dbg.declare into the current block.
1742  llvm::Instruction *Call =
1743    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1744
1745  llvm::MDNode *Scope = RegionStack.back();
1746  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1747}
1748
1749/// EmitDeclare - Emit local variable declaration debug info.
1750void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1751                              llvm::Value *Storage, CGBuilderTy &Builder,
1752                              CodeGenFunction *CGF) {
1753  const ValueDecl *VD = BDRE->getDecl();
1754  assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1755
1756  if (Builder.GetInsertBlock() == 0)
1757    return;
1758
1759  uint64_t XOffset = 0;
1760  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1761  llvm::DIType Ty;
1762  if (VD->hasAttr<BlocksAttr>())
1763    Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1764  else
1765    Ty = getOrCreateType(VD->getType(), Unit);
1766
1767  // Get location information.
1768  unsigned Line = getLineNumber(VD->getLocation());
1769  unsigned Column = getColumnNumber(VD->getLocation());
1770
1771  CharUnits offset = CGF->BlockDecls[VD];
1772  llvm::SmallVector<llvm::Value *, 9> addr;
1773  const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1774  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1775  addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1776  addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1777  if (BDRE->isByRef()) {
1778    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1779    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1780    // offset of __forwarding field
1781    offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1782    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1783    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1784    addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1785    // offset of x field
1786    offset = CharUnits::fromQuantity(XOffset/8);
1787    addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1788  }
1789
1790  // Create the descriptor for the variable.
1791  llvm::DIVariable D =
1792    DebugFactory.CreateComplexVariable(Tag,
1793                                       llvm::DIDescriptor(RegionStack.back()),
1794                                       VD->getName(), Unit, Line, Ty,
1795                                       addr.data(), addr.size());
1796  // Insert an llvm.dbg.declare into the current block.
1797  llvm::Instruction *Call =
1798    DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1799
1800  llvm::MDNode *Scope = RegionStack.back();
1801  Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1802}
1803
1804void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1805                                            llvm::Value *Storage,
1806                                            CGBuilderTy &Builder) {
1807  EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1808}
1809
1810void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1811  const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1812  CodeGenFunction *CGF) {
1813  EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1814}
1815
1816/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1817/// variable declaration.
1818void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1819                                           CGBuilderTy &Builder) {
1820  EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1821}
1822
1823
1824
1825/// EmitGlobalVariable - Emit information about a global variable.
1826void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1827                                     const VarDecl *D) {
1828
1829  // Create global variable debug descriptor.
1830  llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1831  unsigned LineNo = getLineNumber(D->getLocation());
1832
1833  QualType T = D->getType();
1834  if (T->isIncompleteArrayType()) {
1835
1836    // CodeGen turns int[] into int[1] so we'll do the same here.
1837    llvm::APSInt ConstVal(32);
1838
1839    ConstVal = 1;
1840    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1841
1842    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1843                                           ArrayType::Normal, 0);
1844  }
1845  llvm::StringRef DeclName = D->getName();
1846  llvm::StringRef LinkageName;
1847  if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext()))
1848    LinkageName = Var->getName();
1849  llvm::DIDescriptor DContext =
1850    getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1851  DebugFactory.CreateGlobalVariable(DContext, DeclName, DeclName, LinkageName,
1852                                    Unit, LineNo, getOrCreateType(T, Unit),
1853                                    Var->hasInternalLinkage(),
1854                                    true/*definition*/, Var);
1855}
1856
1857/// EmitGlobalVariable - Emit information about an objective-c interface.
1858void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1859                                     ObjCInterfaceDecl *ID) {
1860  // Create global variable debug descriptor.
1861  llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1862  unsigned LineNo = getLineNumber(ID->getLocation());
1863
1864  llvm::StringRef Name = ID->getName();
1865
1866  QualType T = CGM.getContext().getObjCInterfaceType(ID);
1867  if (T->isIncompleteArrayType()) {
1868
1869    // CodeGen turns int[] into int[1] so we'll do the same here.
1870    llvm::APSInt ConstVal(32);
1871
1872    ConstVal = 1;
1873    QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1874
1875    T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1876                                           ArrayType::Normal, 0);
1877  }
1878
1879  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1880                                    getOrCreateType(T, Unit),
1881                                    Var->hasInternalLinkage(),
1882                                    true/*definition*/, Var);
1883}
1884
1885/// EmitGlobalVariable - Emit global variable's debug info.
1886void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
1887                                     llvm::ConstantInt *Init,
1888                                     CGBuilderTy &Builder) {
1889  // Create the descriptor for the variable.
1890  llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1891  llvm::StringRef Name = VD->getName();
1892  llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
1893  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
1894    if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
1895      Ty = CreateEnumType(ED, Unit);
1896  }
1897  // Do not use DIGlobalVariable for enums.
1898  if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
1899    return;
1900  DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit,
1901                                    getLineNumber(VD->getLocation()),
1902                                    Ty, true, true, Init);
1903}
1904
1905/// getOrCreateNamesSpace - Return namespace descriptor for the given
1906/// namespace decl.
1907llvm::DINameSpace
1908CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl,
1909                                  llvm::DIDescriptor Unit) {
1910  llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
1911    NameSpaceCache.find(NSDecl);
1912  if (I != NameSpaceCache.end())
1913    return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1914
1915  unsigned LineNo = getLineNumber(NSDecl->getLocation());
1916
1917  llvm::DIDescriptor Context =
1918    getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1919  llvm::DINameSpace NS =
1920    DebugFactory.CreateNameSpace(Context, NSDecl->getName(),
1921                                 llvm::DIFile(Unit), LineNo);
1922  NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
1923  return NS;
1924}
1925