Decl.cpp revision ff331c15729f7d4439d253c97f4d60f2a7ffd0c6
1//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
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 file implements the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/Stmt.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/PrettyPrinter.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/IdentifierTable.h"
26#include "clang/Basic/Specifiers.h"
27#include "llvm/Support/ErrorHandling.h"
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// NamedDecl Implementation
33//===----------------------------------------------------------------------===//
34
35/// \brief Get the most restrictive linkage for the types in the given
36/// template parameter list.
37static Linkage
38getLinkageForTemplateParameterList(const TemplateParameterList *Params) {
39  Linkage L = ExternalLinkage;
40  for (TemplateParameterList::const_iterator P = Params->begin(),
41                                          PEnd = Params->end();
42       P != PEnd; ++P) {
43    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P))
44      if (!NTTP->getType()->isDependentType()) {
45        L = minLinkage(L, NTTP->getType()->getLinkage());
46        continue;
47      }
48
49    if (TemplateTemplateParmDecl *TTP
50                                   = dyn_cast<TemplateTemplateParmDecl>(*P)) {
51      L = minLinkage(L,
52            getLinkageForTemplateParameterList(TTP->getTemplateParameters()));
53    }
54  }
55
56  return L;
57}
58
59/// \brief Get the most restrictive linkage for the types and
60/// declarations in the given template argument list.
61static Linkage getLinkageForTemplateArgumentList(const TemplateArgument *Args,
62                                                 unsigned NumArgs) {
63  Linkage L = ExternalLinkage;
64
65  for (unsigned I = 0; I != NumArgs; ++I) {
66    switch (Args[I].getKind()) {
67    case TemplateArgument::Null:
68    case TemplateArgument::Integral:
69    case TemplateArgument::Expression:
70      break;
71
72    case TemplateArgument::Type:
73      L = minLinkage(L, Args[I].getAsType()->getLinkage());
74      break;
75
76    case TemplateArgument::Declaration:
77      if (NamedDecl *ND = dyn_cast<NamedDecl>(Args[I].getAsDecl()))
78        L = minLinkage(L, ND->getLinkage());
79      if (ValueDecl *VD = dyn_cast<ValueDecl>(Args[I].getAsDecl()))
80        L = minLinkage(L, VD->getType()->getLinkage());
81      break;
82
83    case TemplateArgument::Template:
84      if (TemplateDecl *Template
85                                = Args[I].getAsTemplate().getAsTemplateDecl())
86        L = minLinkage(L, Template->getLinkage());
87      break;
88
89    case TemplateArgument::Pack:
90      L = minLinkage(L,
91                     getLinkageForTemplateArgumentList(Args[I].pack_begin(),
92                                                       Args[I].pack_size()));
93      break;
94    }
95  }
96
97  return L;
98}
99
100static Linkage getLinkageForNamespaceScopeDecl(const NamedDecl *D) {
101  assert(D->getDeclContext()->getLookupContext()->isFileContext() &&
102         "Not a name having namespace scope");
103  ASTContext &Context = D->getASTContext();
104
105  // C++ [basic.link]p3:
106  //   A name having namespace scope (3.3.6) has internal linkage if it
107  //   is the name of
108  //     - an object, reference, function or function template that is
109  //       explicitly declared static; or,
110  // (This bullet corresponds to C99 6.2.2p3.)
111  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
112    // Explicitly declared static.
113    if (Var->getStorageClass() == VarDecl::Static)
114      return InternalLinkage;
115
116    // - an object or reference that is explicitly declared const
117    //   and neither explicitly declared extern nor previously
118    //   declared to have external linkage; or
119    // (there is no equivalent in C99)
120    if (Context.getLangOptions().CPlusPlus &&
121        Var->getType().isConstant(Context) &&
122        Var->getStorageClass() != VarDecl::Extern &&
123        Var->getStorageClass() != VarDecl::PrivateExtern) {
124      bool FoundExtern = false;
125      for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
126           PrevVar && !FoundExtern;
127           PrevVar = PrevVar->getPreviousDeclaration())
128        if (isExternalLinkage(PrevVar->getLinkage()))
129          FoundExtern = true;
130
131      if (!FoundExtern)
132        return InternalLinkage;
133    }
134  } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
135    // C++ [temp]p4:
136    //   A non-member function template can have internal linkage; any
137    //   other template name shall have external linkage.
138    const FunctionDecl *Function = 0;
139    if (const FunctionTemplateDecl *FunTmpl
140                                        = dyn_cast<FunctionTemplateDecl>(D))
141      Function = FunTmpl->getTemplatedDecl();
142    else
143      Function = cast<FunctionDecl>(D);
144
145    // Explicitly declared static.
146    if (Function->getStorageClass() == FunctionDecl::Static)
147      return InternalLinkage;
148  } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
149    //   - a data member of an anonymous union.
150    if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
151      return InternalLinkage;
152  }
153
154  // C++ [basic.link]p4:
155
156  //   A name having namespace scope has external linkage if it is the
157  //   name of
158  //
159  //     - an object or reference, unless it has internal linkage; or
160  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
161    if (!Context.getLangOptions().CPlusPlus &&
162        (Var->getStorageClass() == VarDecl::Extern ||
163         Var->getStorageClass() == VarDecl::PrivateExtern)) {
164      // C99 6.2.2p4:
165      //   For an identifier declared with the storage-class specifier
166      //   extern in a scope in which a prior declaration of that
167      //   identifier is visible, if the prior declaration specifies
168      //   internal or external linkage, the linkage of the identifier
169      //   at the later declaration is the same as the linkage
170      //   specified at the prior declaration. If no prior declaration
171      //   is visible, or if the prior declaration specifies no
172      //   linkage, then the identifier has external linkage.
173      if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
174        if (Linkage L = PrevVar->getLinkage())
175          return L;
176      }
177    }
178
179    // C99 6.2.2p5:
180    //   If the declaration of an identifier for an object has file
181    //   scope and no storage-class specifier, its linkage is
182    //   external.
183    if (Var->isInAnonymousNamespace())
184      return UniqueExternalLinkage;
185
186    return ExternalLinkage;
187  }
188
189  //     - a function, unless it has internal linkage; or
190  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
191    // C99 6.2.2p5:
192    //   If the declaration of an identifier for a function has no
193    //   storage-class specifier, its linkage is determined exactly
194    //   as if it were declared with the storage-class specifier
195    //   extern.
196    if (!Context.getLangOptions().CPlusPlus &&
197        (Function->getStorageClass() == FunctionDecl::Extern ||
198         Function->getStorageClass() == FunctionDecl::PrivateExtern ||
199         Function->getStorageClass() == FunctionDecl::None)) {
200      // C99 6.2.2p4:
201      //   For an identifier declared with the storage-class specifier
202      //   extern in a scope in which a prior declaration of that
203      //   identifier is visible, if the prior declaration specifies
204      //   internal or external linkage, the linkage of the identifier
205      //   at the later declaration is the same as the linkage
206      //   specified at the prior declaration. If no prior declaration
207      //   is visible, or if the prior declaration specifies no
208      //   linkage, then the identifier has external linkage.
209      if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
210        if (Linkage L = PrevFunc->getLinkage())
211          return L;
212      }
213    }
214
215    if (Function->isInAnonymousNamespace())
216      return UniqueExternalLinkage;
217
218    if (FunctionTemplateSpecializationInfo *SpecInfo
219                               = Function->getTemplateSpecializationInfo()) {
220      Linkage L = SpecInfo->getTemplate()->getLinkage();
221      const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments;
222      L = minLinkage(L,
223                     getLinkageForTemplateArgumentList(
224                                          TemplateArgs.getFlatArgumentList(),
225                                          TemplateArgs.flat_size()));
226      return L;
227    }
228
229    return ExternalLinkage;
230  }
231
232  //     - a named class (Clause 9), or an unnamed class defined in a
233  //       typedef declaration in which the class has the typedef name
234  //       for linkage purposes (7.1.3); or
235  //     - a named enumeration (7.2), or an unnamed enumeration
236  //       defined in a typedef declaration in which the enumeration
237  //       has the typedef name for linkage purposes (7.1.3); or
238  if (const TagDecl *Tag = dyn_cast<TagDecl>(D))
239    if (Tag->getDeclName() || Tag->getTypedefForAnonDecl()) {
240      if (Tag->isInAnonymousNamespace())
241        return UniqueExternalLinkage;
242
243      // If this is a class template specialization, consider the
244      // linkage of the template and template arguments.
245      if (const ClassTemplateSpecializationDecl *Spec
246            = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
247        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
248        Linkage L = getLinkageForTemplateArgumentList(
249                                          TemplateArgs.getFlatArgumentList(),
250                                                 TemplateArgs.flat_size());
251        return minLinkage(L, Spec->getSpecializedTemplate()->getLinkage());
252      }
253
254      return ExternalLinkage;
255    }
256
257  //     - an enumerator belonging to an enumeration with external linkage;
258  if (isa<EnumConstantDecl>(D)) {
259    Linkage L = cast<NamedDecl>(D->getDeclContext())->getLinkage();
260    if (isExternalLinkage(L))
261      return L;
262  }
263
264  //     - a template, unless it is a function template that has
265  //       internal linkage (Clause 14);
266  if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
267    if (D->isInAnonymousNamespace())
268      return UniqueExternalLinkage;
269
270    return getLinkageForTemplateParameterList(
271                                         Template->getTemplateParameters());
272  }
273
274  //     - a namespace (7.3), unless it is declared within an unnamed
275  //       namespace.
276  if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace())
277    return ExternalLinkage;
278
279  return NoLinkage;
280}
281
282Linkage NamedDecl::getLinkage() const {
283
284  // Objective-C: treat all Objective-C declarations as having external
285  // linkage.
286  switch (getKind()) {
287    default:
288      break;
289    case Decl::ObjCAtDefsField:
290    case Decl::ObjCCategory:
291    case Decl::ObjCCategoryImpl:
292    case Decl::ObjCClass:
293    case Decl::ObjCCompatibleAlias:
294    case Decl::ObjCForwardProtocol:
295    case Decl::ObjCImplementation:
296    case Decl::ObjCInterface:
297    case Decl::ObjCIvar:
298    case Decl::ObjCMethod:
299    case Decl::ObjCProperty:
300    case Decl::ObjCPropertyImpl:
301    case Decl::ObjCProtocol:
302      return ExternalLinkage;
303  }
304
305  // Handle linkage for namespace-scope names.
306  if (getDeclContext()->getLookupContext()->isFileContext())
307    if (Linkage L = getLinkageForNamespaceScopeDecl(this))
308      return L;
309
310  // C++ [basic.link]p5:
311  //   In addition, a member function, static data member, a named
312  //   class or enumeration of class scope, or an unnamed class or
313  //   enumeration defined in a class-scope typedef declaration such
314  //   that the class or enumeration has the typedef name for linkage
315  //   purposes (7.1.3), has external linkage if the name of the class
316  //   has external linkage.
317  if (getDeclContext()->isRecord() &&
318      (isa<CXXMethodDecl>(this) || isa<VarDecl>(this) ||
319       (isa<TagDecl>(this) &&
320        (getDeclName() || cast<TagDecl>(this)->getTypedefForAnonDecl())))) {
321    Linkage L = cast<RecordDecl>(getDeclContext())->getLinkage();
322    if (isExternalLinkage(L))
323      return L;
324  }
325
326  // C++ [basic.link]p6:
327  //   The name of a function declared in block scope and the name of
328  //   an object declared by a block scope extern declaration have
329  //   linkage. If there is a visible declaration of an entity with
330  //   linkage having the same name and type, ignoring entities
331  //   declared outside the innermost enclosing namespace scope, the
332  //   block scope declaration declares that same entity and receives
333  //   the linkage of the previous declaration. If there is more than
334  //   one such matching entity, the program is ill-formed. Otherwise,
335  //   if no matching entity is found, the block scope entity receives
336  //   external linkage.
337  if (getLexicalDeclContext()->isFunctionOrMethod()) {
338    if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) {
339      if (Function->getPreviousDeclaration())
340        if (Linkage L = Function->getPreviousDeclaration()->getLinkage())
341          return L;
342
343      if (Function->isInAnonymousNamespace())
344        return UniqueExternalLinkage;
345
346      return ExternalLinkage;
347    }
348
349    if (const VarDecl *Var = dyn_cast<VarDecl>(this))
350      if (Var->getStorageClass() == VarDecl::Extern ||
351          Var->getStorageClass() == VarDecl::PrivateExtern) {
352        if (Var->getPreviousDeclaration())
353          if (Linkage L = Var->getPreviousDeclaration()->getLinkage())
354            return L;
355
356        if (Var->isInAnonymousNamespace())
357          return UniqueExternalLinkage;
358
359        return ExternalLinkage;
360      }
361  }
362
363  // C++ [basic.link]p6:
364  //   Names not covered by these rules have no linkage.
365  return NoLinkage;
366  }
367
368std::string NamedDecl::getQualifiedNameAsString() const {
369  return getQualifiedNameAsString(getASTContext().getLangOptions());
370}
371
372std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
373  const DeclContext *Ctx = getDeclContext();
374
375  if (Ctx->isFunctionOrMethod())
376    return getNameAsString();
377
378  typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy;
379  ContextsTy Contexts;
380
381  // Collect contexts.
382  while (Ctx && isa<NamedDecl>(Ctx)) {
383    Contexts.push_back(Ctx);
384    Ctx = Ctx->getParent();
385  };
386
387  std::string QualName;
388  llvm::raw_string_ostream OS(QualName);
389
390  for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
391       I != E; ++I) {
392    if (const ClassTemplateSpecializationDecl *Spec
393          = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
394      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
395      std::string TemplateArgsStr
396        = TemplateSpecializationType::PrintTemplateArgumentList(
397                                           TemplateArgs.getFlatArgumentList(),
398                                           TemplateArgs.flat_size(),
399                                           P);
400      OS << Spec->getName() << TemplateArgsStr;
401    } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
402      if (ND->isAnonymousNamespace())
403        OS << "<anonymous namespace>";
404      else
405        OS << ND;
406    } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
407      if (!RD->getIdentifier())
408        OS << "<anonymous " << RD->getKindName() << '>';
409      else
410        OS << RD;
411    } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
412      const FunctionProtoType *FT = 0;
413      if (FD->hasWrittenPrototype())
414        FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
415
416      OS << FD << '(';
417      if (FT) {
418        unsigned NumParams = FD->getNumParams();
419        for (unsigned i = 0; i < NumParams; ++i) {
420          if (i)
421            OS << ", ";
422          std::string Param;
423          FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
424          OS << Param;
425        }
426
427        if (FT->isVariadic()) {
428          if (NumParams > 0)
429            OS << ", ";
430          OS << "...";
431        }
432      }
433      OS << ')';
434    } else {
435      OS << cast<NamedDecl>(*I);
436    }
437    OS << "::";
438  }
439
440  if (getDeclName())
441    OS << this;
442  else
443    OS << "<anonymous>";
444
445  return OS.str();
446}
447
448bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
449  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
450
451  // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
452  // We want to keep it, unless it nominates same namespace.
453  if (getKind() == Decl::UsingDirective) {
454    return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() ==
455           cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace();
456  }
457
458  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
459    // For function declarations, we keep track of redeclarations.
460    return FD->getPreviousDeclaration() == OldD;
461
462  // For function templates, the underlying function declarations are linked.
463  if (const FunctionTemplateDecl *FunctionTemplate
464        = dyn_cast<FunctionTemplateDecl>(this))
465    if (const FunctionTemplateDecl *OldFunctionTemplate
466          = dyn_cast<FunctionTemplateDecl>(OldD))
467      return FunctionTemplate->getTemplatedDecl()
468               ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
469
470  // For method declarations, we keep track of redeclarations.
471  if (isa<ObjCMethodDecl>(this))
472    return false;
473
474  if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
475    return true;
476
477  if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
478    return cast<UsingShadowDecl>(this)->getTargetDecl() ==
479           cast<UsingShadowDecl>(OldD)->getTargetDecl();
480
481  // For non-function declarations, if the declarations are of the
482  // same kind then this must be a redeclaration, or semantic analysis
483  // would not have given us the new declaration.
484  return this->getKind() == OldD->getKind();
485}
486
487bool NamedDecl::hasLinkage() const {
488  return getLinkage() != NoLinkage;
489}
490
491NamedDecl *NamedDecl::getUnderlyingDecl() {
492  NamedDecl *ND = this;
493  while (true) {
494    if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
495      ND = UD->getTargetDecl();
496    else if (ObjCCompatibleAliasDecl *AD
497              = dyn_cast<ObjCCompatibleAliasDecl>(ND))
498      return AD->getClassInterface();
499    else
500      return ND;
501  }
502}
503
504bool NamedDecl::isCXXInstanceMember() const {
505  assert(isCXXClassMember() &&
506         "checking whether non-member is instance member");
507
508  const NamedDecl *D = this;
509  if (isa<UsingShadowDecl>(D))
510    D = cast<UsingShadowDecl>(D)->getTargetDecl();
511
512  if (isa<FieldDecl>(D))
513    return true;
514  if (isa<CXXMethodDecl>(D))
515    return cast<CXXMethodDecl>(D)->isInstance();
516  if (isa<FunctionTemplateDecl>(D))
517    return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
518                                 ->getTemplatedDecl())->isInstance();
519  return false;
520}
521
522//===----------------------------------------------------------------------===//
523// DeclaratorDecl Implementation
524//===----------------------------------------------------------------------===//
525
526template <typename DeclT>
527static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
528  if (decl->getNumTemplateParameterLists() > 0)
529    return decl->getTemplateParameterList(0)->getTemplateLoc();
530  else
531    return decl->getInnerLocStart();
532}
533
534DeclaratorDecl::~DeclaratorDecl() {}
535
536SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
537  TypeSourceInfo *TSI = getTypeSourceInfo();
538  if (TSI) return TSI->getTypeLoc().getBeginLoc();
539  return SourceLocation();
540}
541
542void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier,
543                                      SourceRange QualifierRange) {
544  if (Qualifier) {
545    // Make sure the extended decl info is allocated.
546    if (!hasExtInfo()) {
547      // Save (non-extended) type source info pointer.
548      TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
549      // Allocate external info struct.
550      DeclInfo = new (getASTContext()) ExtInfo;
551      // Restore savedTInfo into (extended) decl info.
552      getExtInfo()->TInfo = savedTInfo;
553    }
554    // Set qualifier info.
555    getExtInfo()->NNS = Qualifier;
556    getExtInfo()->NNSRange = QualifierRange;
557  }
558  else {
559    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
560    assert(QualifierRange.isInvalid());
561    if (hasExtInfo()) {
562      // Save type source info pointer.
563      TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
564      // Deallocate the extended decl info.
565      getASTContext().Deallocate(getExtInfo());
566      // Restore savedTInfo into (non-extended) decl info.
567      DeclInfo = savedTInfo;
568    }
569  }
570}
571
572SourceLocation DeclaratorDecl::getOuterLocStart() const {
573  return getTemplateOrInnerLocStart(this);
574}
575
576void
577QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
578                                             unsigned NumTPLists,
579                                             TemplateParameterList **TPLists) {
580  assert((NumTPLists == 0 || TPLists != 0) &&
581         "Empty array of template parameters with positive size!");
582  assert((NumTPLists == 0 || NNS) &&
583         "Nonempty array of template parameters with no qualifier!");
584
585  // Free previous template parameters (if any).
586  if (NumTemplParamLists > 0) {
587    Context.Deallocate(TemplParamLists);
588    TemplParamLists = 0;
589    NumTemplParamLists = 0;
590  }
591  // Set info on matched template parameter lists (if any).
592  if (NumTPLists > 0) {
593    TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
594    NumTemplParamLists = NumTPLists;
595    for (unsigned i = NumTPLists; i-- > 0; )
596      TemplParamLists[i] = TPLists[i];
597  }
598}
599
600//===----------------------------------------------------------------------===//
601// VarDecl Implementation
602//===----------------------------------------------------------------------===//
603
604const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
605  switch (SC) {
606  case VarDecl::None:          break;
607  case VarDecl::Auto:          return "auto"; break;
608  case VarDecl::Extern:        return "extern"; break;
609  case VarDecl::PrivateExtern: return "__private_extern__"; break;
610  case VarDecl::Register:      return "register"; break;
611  case VarDecl::Static:        return "static"; break;
612  }
613
614  assert(0 && "Invalid storage class");
615  return 0;
616}
617
618VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
619                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
620                         StorageClass S, StorageClass SCAsWritten) {
621  return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten);
622}
623
624VarDecl::~VarDecl() {
625}
626
627SourceLocation VarDecl::getInnerLocStart() const {
628  SourceLocation Start = getTypeSpecStartLoc();
629  if (Start.isInvalid())
630    Start = getLocation();
631  return Start;
632}
633
634SourceRange VarDecl::getSourceRange() const {
635  if (getInit())
636    return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
637  return SourceRange(getOuterLocStart(), getLocation());
638}
639
640bool VarDecl::isExternC() const {
641  ASTContext &Context = getASTContext();
642  if (!Context.getLangOptions().CPlusPlus)
643    return (getDeclContext()->isTranslationUnit() &&
644            getStorageClass() != Static) ||
645      (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
646
647  for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
648       DC = DC->getParent()) {
649    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
650      if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
651        return getStorageClass() != Static;
652
653      break;
654    }
655
656    if (DC->isFunctionOrMethod())
657      return false;
658  }
659
660  return false;
661}
662
663VarDecl *VarDecl::getCanonicalDecl() {
664  return getFirstDeclaration();
665}
666
667VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
668  // C++ [basic.def]p2:
669  //   A declaration is a definition unless [...] it contains the 'extern'
670  //   specifier or a linkage-specification and neither an initializer [...],
671  //   it declares a static data member in a class declaration [...].
672  // C++ [temp.expl.spec]p15:
673  //   An explicit specialization of a static data member of a template is a
674  //   definition if the declaration includes an initializer; otherwise, it is
675  //   a declaration.
676  if (isStaticDataMember()) {
677    if (isOutOfLine() && (hasInit() ||
678          getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
679      return Definition;
680    else
681      return DeclarationOnly;
682  }
683  // C99 6.7p5:
684  //   A definition of an identifier is a declaration for that identifier that
685  //   [...] causes storage to be reserved for that object.
686  // Note: that applies for all non-file-scope objects.
687  // C99 6.9.2p1:
688  //   If the declaration of an identifier for an object has file scope and an
689  //   initializer, the declaration is an external definition for the identifier
690  if (hasInit())
691    return Definition;
692  // AST for 'extern "C" int foo;' is annotated with 'extern'.
693  if (hasExternalStorage())
694    return DeclarationOnly;
695
696  if (getStorageClassAsWritten() == Extern ||
697       getStorageClassAsWritten() == PrivateExtern) {
698    for (const VarDecl *PrevVar = getPreviousDeclaration();
699         PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
700      if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
701        return DeclarationOnly;
702    }
703  }
704  // C99 6.9.2p2:
705  //   A declaration of an object that has file scope without an initializer,
706  //   and without a storage class specifier or the scs 'static', constitutes
707  //   a tentative definition.
708  // No such thing in C++.
709  if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
710    return TentativeDefinition;
711
712  // What's left is (in C, block-scope) declarations without initializers or
713  // external storage. These are definitions.
714  return Definition;
715}
716
717VarDecl *VarDecl::getActingDefinition() {
718  DefinitionKind Kind = isThisDeclarationADefinition();
719  if (Kind != TentativeDefinition)
720    return 0;
721
722  VarDecl *LastTentative = 0;
723  VarDecl *First = getFirstDeclaration();
724  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
725       I != E; ++I) {
726    Kind = (*I)->isThisDeclarationADefinition();
727    if (Kind == Definition)
728      return 0;
729    else if (Kind == TentativeDefinition)
730      LastTentative = *I;
731  }
732  return LastTentative;
733}
734
735bool VarDecl::isTentativeDefinitionNow() const {
736  DefinitionKind Kind = isThisDeclarationADefinition();
737  if (Kind != TentativeDefinition)
738    return false;
739
740  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
741    if ((*I)->isThisDeclarationADefinition() == Definition)
742      return false;
743  }
744  return true;
745}
746
747VarDecl *VarDecl::getDefinition() {
748  VarDecl *First = getFirstDeclaration();
749  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
750       I != E; ++I) {
751    if ((*I)->isThisDeclarationADefinition() == Definition)
752      return *I;
753  }
754  return 0;
755}
756
757const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
758  redecl_iterator I = redecls_begin(), E = redecls_end();
759  while (I != E && !I->getInit())
760    ++I;
761
762  if (I != E) {
763    D = *I;
764    return I->getInit();
765  }
766  return 0;
767}
768
769bool VarDecl::isOutOfLine() const {
770  if (Decl::isOutOfLine())
771    return true;
772
773  if (!isStaticDataMember())
774    return false;
775
776  // If this static data member was instantiated from a static data member of
777  // a class template, check whether that static data member was defined
778  // out-of-line.
779  if (VarDecl *VD = getInstantiatedFromStaticDataMember())
780    return VD->isOutOfLine();
781
782  return false;
783}
784
785VarDecl *VarDecl::getOutOfLineDefinition() {
786  if (!isStaticDataMember())
787    return 0;
788
789  for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
790       RD != RDEnd; ++RD) {
791    if (RD->getLexicalDeclContext()->isFileContext())
792      return *RD;
793  }
794
795  return 0;
796}
797
798void VarDecl::setInit(Expr *I) {
799  if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
800    Eval->~EvaluatedStmt();
801    getASTContext().Deallocate(Eval);
802  }
803
804  Init = I;
805}
806
807VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
808  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
809    return cast<VarDecl>(MSI->getInstantiatedFrom());
810
811  return 0;
812}
813
814TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
815  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
816    return MSI->getTemplateSpecializationKind();
817
818  return TSK_Undeclared;
819}
820
821MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
822  return getASTContext().getInstantiatedFromStaticDataMember(this);
823}
824
825void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
826                                         SourceLocation PointOfInstantiation) {
827  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
828  assert(MSI && "Not an instantiated static data member?");
829  MSI->setTemplateSpecializationKind(TSK);
830  if (TSK != TSK_ExplicitSpecialization &&
831      PointOfInstantiation.isValid() &&
832      MSI->getPointOfInstantiation().isInvalid())
833    MSI->setPointOfInstantiation(PointOfInstantiation);
834}
835
836//===----------------------------------------------------------------------===//
837// ParmVarDecl Implementation
838//===----------------------------------------------------------------------===//
839
840ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
841                                 SourceLocation L, IdentifierInfo *Id,
842                                 QualType T, TypeSourceInfo *TInfo,
843                                 StorageClass S, StorageClass SCAsWritten,
844                                 Expr *DefArg) {
845  return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo,
846                             S, SCAsWritten, DefArg);
847}
848
849Expr *ParmVarDecl::getDefaultArg() {
850  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
851  assert(!hasUninstantiatedDefaultArg() &&
852         "Default argument is not yet instantiated!");
853
854  Expr *Arg = getInit();
855  if (CXXExprWithTemporaries *E = dyn_cast_or_null<CXXExprWithTemporaries>(Arg))
856    return E->getSubExpr();
857
858  return Arg;
859}
860
861unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
862  if (const CXXExprWithTemporaries *E =
863        dyn_cast<CXXExprWithTemporaries>(getInit()))
864    return E->getNumTemporaries();
865
866  return 0;
867}
868
869CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
870  assert(getNumDefaultArgTemporaries() &&
871         "Default arguments does not have any temporaries!");
872
873  CXXExprWithTemporaries *E = cast<CXXExprWithTemporaries>(getInit());
874  return E->getTemporary(i);
875}
876
877SourceRange ParmVarDecl::getDefaultArgRange() const {
878  if (const Expr *E = getInit())
879    return E->getSourceRange();
880
881  if (hasUninstantiatedDefaultArg())
882    return getUninstantiatedDefaultArg()->getSourceRange();
883
884  return SourceRange();
885}
886
887//===----------------------------------------------------------------------===//
888// FunctionDecl Implementation
889//===----------------------------------------------------------------------===//
890
891void FunctionDecl::getNameForDiagnostic(std::string &S,
892                                        const PrintingPolicy &Policy,
893                                        bool Qualified) const {
894  NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
895  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
896  if (TemplateArgs)
897    S += TemplateSpecializationType::PrintTemplateArgumentList(
898                                         TemplateArgs->getFlatArgumentList(),
899                                         TemplateArgs->flat_size(),
900                                                               Policy);
901
902}
903
904bool FunctionDecl::isVariadic() const {
905  if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
906    return FT->isVariadic();
907  return false;
908}
909
910bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
911  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
912    if (I->Body) {
913      Definition = *I;
914      return true;
915    }
916  }
917
918  return false;
919}
920
921Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
922  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
923    if (I->Body) {
924      Definition = *I;
925      return I->Body.get(getASTContext().getExternalSource());
926    }
927  }
928
929  return 0;
930}
931
932void FunctionDecl::setBody(Stmt *B) {
933  Body = B;
934  if (B)
935    EndRangeLoc = B->getLocEnd();
936}
937
938bool FunctionDecl::isMain() const {
939  ASTContext &Context = getASTContext();
940  return !Context.getLangOptions().Freestanding &&
941    getDeclContext()->getLookupContext()->isTranslationUnit() &&
942    getIdentifier() && getIdentifier()->isStr("main");
943}
944
945bool FunctionDecl::isExternC() const {
946  ASTContext &Context = getASTContext();
947  // In C, any non-static, non-overloadable function has external
948  // linkage.
949  if (!Context.getLangOptions().CPlusPlus)
950    return getStorageClass() != Static && !getAttr<OverloadableAttr>();
951
952  for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
953       DC = DC->getParent()) {
954    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
955      if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
956        return getStorageClass() != Static &&
957               !getAttr<OverloadableAttr>();
958
959      break;
960    }
961  }
962
963  return false;
964}
965
966bool FunctionDecl::isGlobal() const {
967  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
968    return Method->isStatic();
969
970  if (getStorageClass() == Static)
971    return false;
972
973  for (const DeclContext *DC = getDeclContext();
974       DC->isNamespace();
975       DC = DC->getParent()) {
976    if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
977      if (!Namespace->getDeclName())
978        return false;
979      break;
980    }
981  }
982
983  return true;
984}
985
986void
987FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
988  redeclarable_base::setPreviousDeclaration(PrevDecl);
989
990  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
991    FunctionTemplateDecl *PrevFunTmpl
992      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
993    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
994    FunTmpl->setPreviousDeclaration(PrevFunTmpl);
995  }
996}
997
998const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
999  return getFirstDeclaration();
1000}
1001
1002FunctionDecl *FunctionDecl::getCanonicalDecl() {
1003  return getFirstDeclaration();
1004}
1005
1006/// \brief Returns a value indicating whether this function
1007/// corresponds to a builtin function.
1008///
1009/// The function corresponds to a built-in function if it is
1010/// declared at translation scope or within an extern "C" block and
1011/// its name matches with the name of a builtin. The returned value
1012/// will be 0 for functions that do not correspond to a builtin, a
1013/// value of type \c Builtin::ID if in the target-independent range
1014/// \c [1,Builtin::First), or a target-specific builtin value.
1015unsigned FunctionDecl::getBuiltinID() const {
1016  ASTContext &Context = getASTContext();
1017  if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1018    return 0;
1019
1020  unsigned BuiltinID = getIdentifier()->getBuiltinID();
1021  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1022    return BuiltinID;
1023
1024  // This function has the name of a known C library
1025  // function. Determine whether it actually refers to the C library
1026  // function or whether it just has the same name.
1027
1028  // If this is a static function, it's not a builtin.
1029  if (getStorageClass() == Static)
1030    return 0;
1031
1032  // If this function is at translation-unit scope and we're not in
1033  // C++, it refers to the C library function.
1034  if (!Context.getLangOptions().CPlusPlus &&
1035      getDeclContext()->isTranslationUnit())
1036    return BuiltinID;
1037
1038  // If the function is in an extern "C" linkage specification and is
1039  // not marked "overloadable", it's the real function.
1040  if (isa<LinkageSpecDecl>(getDeclContext()) &&
1041      cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1042        == LinkageSpecDecl::lang_c &&
1043      !getAttr<OverloadableAttr>())
1044    return BuiltinID;
1045
1046  // Not a builtin
1047  return 0;
1048}
1049
1050
1051/// getNumParams - Return the number of parameters this function must have
1052/// based on its FunctionType.  This is the length of the PararmInfo array
1053/// after it has been created.
1054unsigned FunctionDecl::getNumParams() const {
1055  const FunctionType *FT = getType()->getAs<FunctionType>();
1056  if (isa<FunctionNoProtoType>(FT))
1057    return 0;
1058  return cast<FunctionProtoType>(FT)->getNumArgs();
1059
1060}
1061
1062void FunctionDecl::setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) {
1063  assert(ParamInfo == 0 && "Already has param info!");
1064  assert(NumParams == getNumParams() && "Parameter count mismatch!");
1065
1066  // Zero params -> null pointer.
1067  if (NumParams) {
1068    void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams);
1069    ParamInfo = new (Mem) ParmVarDecl*[NumParams];
1070    memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
1071
1072    // Update source range. The check below allows us to set EndRangeLoc before
1073    // setting the parameters.
1074    if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation())
1075      EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd();
1076  }
1077}
1078
1079/// getMinRequiredArguments - Returns the minimum number of arguments
1080/// needed to call this function. This may be fewer than the number of
1081/// function parameters, if some of the parameters have default
1082/// arguments (in C++).
1083unsigned FunctionDecl::getMinRequiredArguments() const {
1084  unsigned NumRequiredArgs = getNumParams();
1085  while (NumRequiredArgs > 0
1086         && getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1087    --NumRequiredArgs;
1088
1089  return NumRequiredArgs;
1090}
1091
1092bool FunctionDecl::isInlined() const {
1093  // FIXME: This is not enough. Consider:
1094  //
1095  // inline void f();
1096  // void f() { }
1097  //
1098  // f is inlined, but does not have inline specified.
1099  // To fix this we should add an 'inline' flag to FunctionDecl.
1100  if (isInlineSpecified())
1101    return true;
1102
1103  if (isa<CXXMethodDecl>(this)) {
1104    if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1105      return true;
1106  }
1107
1108  switch (getTemplateSpecializationKind()) {
1109  case TSK_Undeclared:
1110  case TSK_ExplicitSpecialization:
1111    return false;
1112
1113  case TSK_ImplicitInstantiation:
1114  case TSK_ExplicitInstantiationDeclaration:
1115  case TSK_ExplicitInstantiationDefinition:
1116    // Handle below.
1117    break;
1118  }
1119
1120  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1121  bool HasPattern = false;
1122  if (PatternDecl)
1123    HasPattern = PatternDecl->hasBody(PatternDecl);
1124
1125  if (HasPattern && PatternDecl)
1126    return PatternDecl->isInlined();
1127
1128  return false;
1129}
1130
1131/// \brief For an inline function definition in C or C++, determine whether the
1132/// definition will be externally visible.
1133///
1134/// Inline function definitions are always available for inlining optimizations.
1135/// However, depending on the language dialect, declaration specifiers, and
1136/// attributes, the definition of an inline function may or may not be
1137/// "externally" visible to other translation units in the program.
1138///
1139/// In C99, inline definitions are not externally visible by default. However,
1140/// if even one of the global-scope declarations is marked "extern inline", the
1141/// inline definition becomes externally visible (C99 6.7.4p6).
1142///
1143/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1144/// definition, we use the GNU semantics for inline, which are nearly the
1145/// opposite of C99 semantics. In particular, "inline" by itself will create
1146/// an externally visible symbol, but "extern inline" will not create an
1147/// externally visible symbol.
1148bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
1149  assert(isThisDeclarationADefinition() && "Must have the function definition");
1150  assert(isInlined() && "Function must be inline");
1151  ASTContext &Context = getASTContext();
1152
1153  if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) {
1154    // GNU inline semantics. Based on a number of examples, we came up with the
1155    // following heuristic: if the "inline" keyword is present on a
1156    // declaration of the function but "extern" is not present on that
1157    // declaration, then the symbol is externally visible. Otherwise, the GNU
1158    // "extern inline" semantics applies and the symbol is not externally
1159    // visible.
1160    for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1161         Redecl != RedeclEnd;
1162         ++Redecl) {
1163      if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != Extern)
1164        return true;
1165    }
1166
1167    // GNU "extern inline" semantics; no externally visible symbol.
1168    return false;
1169  }
1170
1171  // C99 6.7.4p6:
1172  //   [...] If all of the file scope declarations for a function in a
1173  //   translation unit include the inline function specifier without extern,
1174  //   then the definition in that translation unit is an inline definition.
1175  for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1176       Redecl != RedeclEnd;
1177       ++Redecl) {
1178    // Only consider file-scope declarations in this test.
1179    if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1180      continue;
1181
1182    if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == Extern)
1183      return true; // Not an inline definition
1184  }
1185
1186  // C99 6.7.4p6:
1187  //   An inline definition does not provide an external definition for the
1188  //   function, and does not forbid an external definition in another
1189  //   translation unit.
1190  return false;
1191}
1192
1193/// getOverloadedOperator - Which C++ overloaded operator this
1194/// function represents, if any.
1195OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
1196  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1197    return getDeclName().getCXXOverloadedOperator();
1198  else
1199    return OO_None;
1200}
1201
1202/// getLiteralIdentifier - The literal suffix identifier this function
1203/// represents, if any.
1204const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1205  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1206    return getDeclName().getCXXLiteralIdentifier();
1207  else
1208    return 0;
1209}
1210
1211FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1212  if (TemplateOrSpecialization.isNull())
1213    return TK_NonTemplate;
1214  if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
1215    return TK_FunctionTemplate;
1216  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
1217    return TK_MemberSpecialization;
1218  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
1219    return TK_FunctionTemplateSpecialization;
1220  if (TemplateOrSpecialization.is
1221                               <DependentFunctionTemplateSpecializationInfo*>())
1222    return TK_DependentFunctionTemplateSpecialization;
1223
1224  assert(false && "Did we miss a TemplateOrSpecialization type?");
1225  return TK_NonTemplate;
1226}
1227
1228FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
1229  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
1230    return cast<FunctionDecl>(Info->getInstantiatedFrom());
1231
1232  return 0;
1233}
1234
1235MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
1236  return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1237}
1238
1239void
1240FunctionDecl::setInstantiationOfMemberFunction(FunctionDecl *FD,
1241                                               TemplateSpecializationKind TSK) {
1242  assert(TemplateOrSpecialization.isNull() &&
1243         "Member function is already a specialization");
1244  MemberSpecializationInfo *Info
1245    = new (getASTContext()) MemberSpecializationInfo(FD, TSK);
1246  TemplateOrSpecialization = Info;
1247}
1248
1249bool FunctionDecl::isImplicitlyInstantiable() const {
1250  // If the function is invalid, it can't be implicitly instantiated.
1251  if (isInvalidDecl())
1252    return false;
1253
1254  switch (getTemplateSpecializationKind()) {
1255  case TSK_Undeclared:
1256  case TSK_ExplicitSpecialization:
1257  case TSK_ExplicitInstantiationDefinition:
1258    return false;
1259
1260  case TSK_ImplicitInstantiation:
1261    return true;
1262
1263  case TSK_ExplicitInstantiationDeclaration:
1264    // Handled below.
1265    break;
1266  }
1267
1268  // Find the actual template from which we will instantiate.
1269  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1270  bool HasPattern = false;
1271  if (PatternDecl)
1272    HasPattern = PatternDecl->hasBody(PatternDecl);
1273
1274  // C++0x [temp.explicit]p9:
1275  //   Except for inline functions, other explicit instantiation declarations
1276  //   have the effect of suppressing the implicit instantiation of the entity
1277  //   to which they refer.
1278  if (!HasPattern || !PatternDecl)
1279    return true;
1280
1281  return PatternDecl->isInlined();
1282}
1283
1284FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
1285  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
1286    while (Primary->getInstantiatedFromMemberTemplate()) {
1287      // If we have hit a point where the user provided a specialization of
1288      // this template, we're done looking.
1289      if (Primary->isMemberSpecialization())
1290        break;
1291
1292      Primary = Primary->getInstantiatedFromMemberTemplate();
1293    }
1294
1295    return Primary->getTemplatedDecl();
1296  }
1297
1298  return getInstantiatedFromMemberFunction();
1299}
1300
1301FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
1302  if (FunctionTemplateSpecializationInfo *Info
1303        = TemplateOrSpecialization
1304            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1305    return Info->Template.getPointer();
1306  }
1307  return 0;
1308}
1309
1310const TemplateArgumentList *
1311FunctionDecl::getTemplateSpecializationArgs() const {
1312  if (FunctionTemplateSpecializationInfo *Info
1313        = TemplateOrSpecialization
1314            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1315    return Info->TemplateArguments;
1316  }
1317  return 0;
1318}
1319
1320const TemplateArgumentListInfo *
1321FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
1322  if (FunctionTemplateSpecializationInfo *Info
1323        = TemplateOrSpecialization
1324            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1325    return Info->TemplateArgumentsAsWritten;
1326  }
1327  return 0;
1328}
1329
1330void
1331FunctionDecl::setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1332                                     const TemplateArgumentList *TemplateArgs,
1333                                                void *InsertPos,
1334                                                TemplateSpecializationKind TSK,
1335                        const TemplateArgumentListInfo *TemplateArgsAsWritten,
1336                                          SourceLocation PointOfInstantiation) {
1337  assert(TSK != TSK_Undeclared &&
1338         "Must specify the type of function template specialization");
1339  FunctionTemplateSpecializationInfo *Info
1340    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1341  if (!Info)
1342    Info = new (getASTContext()) FunctionTemplateSpecializationInfo;
1343
1344  Info->Function = this;
1345  Info->Template.setPointer(Template);
1346  Info->Template.setInt(TSK - 1);
1347  Info->TemplateArguments = TemplateArgs;
1348  Info->TemplateArgumentsAsWritten = TemplateArgsAsWritten;
1349  Info->PointOfInstantiation = PointOfInstantiation;
1350  TemplateOrSpecialization = Info;
1351
1352  // Insert this function template specialization into the set of known
1353  // function template specializations.
1354  if (InsertPos)
1355    Template->getSpecializations().InsertNode(Info, InsertPos);
1356  else {
1357    // Try to insert the new node. If there is an existing node, leave it, the
1358    // set will contain the canonical decls while
1359    // FunctionTemplateDecl::findSpecialization will return
1360    // the most recent redeclarations.
1361    FunctionTemplateSpecializationInfo *Existing
1362      = Template->getSpecializations().GetOrInsertNode(Info);
1363    (void)Existing;
1364    assert((!Existing || Existing->Function->isCanonicalDecl()) &&
1365           "Set is supposed to only contain canonical decls");
1366  }
1367}
1368
1369void
1370FunctionDecl::setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
1371                                                unsigned NumTemplateArgs,
1372                                           const TemplateArgument *TemplateArgs,
1373                                                 TemplateSpecializationKind TSK,
1374                                              unsigned NumTemplateArgsAsWritten,
1375                                   TemplateArgumentLoc *TemplateArgsAsWritten,
1376                                                SourceLocation LAngleLoc,
1377                                                SourceLocation RAngleLoc,
1378                                          SourceLocation PointOfInstantiation) {
1379  ASTContext &Ctx = getASTContext();
1380  TemplateArgumentList *TemplArgs
1381    = new (Ctx) TemplateArgumentList(Ctx, TemplateArgs, NumTemplateArgs);
1382  TemplateArgumentListInfo *TemplArgsInfo
1383    = new (Ctx) TemplateArgumentListInfo(LAngleLoc, RAngleLoc);
1384  for (unsigned i=0; i != NumTemplateArgsAsWritten; ++i)
1385    TemplArgsInfo->addArgument(TemplateArgsAsWritten[i]);
1386
1387  setFunctionTemplateSpecialization(Template, TemplArgs, /*InsertPos=*/0, TSK,
1388                                    TemplArgsInfo, PointOfInstantiation);
1389}
1390
1391void
1392FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
1393                                    const UnresolvedSetImpl &Templates,
1394                             const TemplateArgumentListInfo &TemplateArgs) {
1395  assert(TemplateOrSpecialization.isNull());
1396  size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
1397  Size += Templates.size() * sizeof(FunctionTemplateDecl*);
1398  Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
1399  void *Buffer = Context.Allocate(Size);
1400  DependentFunctionTemplateSpecializationInfo *Info =
1401    new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
1402                                                             TemplateArgs);
1403  TemplateOrSpecialization = Info;
1404}
1405
1406DependentFunctionTemplateSpecializationInfo::
1407DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
1408                                      const TemplateArgumentListInfo &TArgs)
1409  : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
1410
1411  d.NumTemplates = Ts.size();
1412  d.NumArgs = TArgs.size();
1413
1414  FunctionTemplateDecl **TsArray =
1415    const_cast<FunctionTemplateDecl**>(getTemplates());
1416  for (unsigned I = 0, E = Ts.size(); I != E; ++I)
1417    TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
1418
1419  TemplateArgumentLoc *ArgsArray =
1420    const_cast<TemplateArgumentLoc*>(getTemplateArgs());
1421  for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
1422    new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
1423}
1424
1425TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
1426  // For a function template specialization, query the specialization
1427  // information object.
1428  FunctionTemplateSpecializationInfo *FTSInfo
1429    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1430  if (FTSInfo)
1431    return FTSInfo->getTemplateSpecializationKind();
1432
1433  MemberSpecializationInfo *MSInfo
1434    = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1435  if (MSInfo)
1436    return MSInfo->getTemplateSpecializationKind();
1437
1438  return TSK_Undeclared;
1439}
1440
1441void
1442FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1443                                          SourceLocation PointOfInstantiation) {
1444  if (FunctionTemplateSpecializationInfo *FTSInfo
1445        = TemplateOrSpecialization.dyn_cast<
1446                                    FunctionTemplateSpecializationInfo*>()) {
1447    FTSInfo->setTemplateSpecializationKind(TSK);
1448    if (TSK != TSK_ExplicitSpecialization &&
1449        PointOfInstantiation.isValid() &&
1450        FTSInfo->getPointOfInstantiation().isInvalid())
1451      FTSInfo->setPointOfInstantiation(PointOfInstantiation);
1452  } else if (MemberSpecializationInfo *MSInfo
1453             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
1454    MSInfo->setTemplateSpecializationKind(TSK);
1455    if (TSK != TSK_ExplicitSpecialization &&
1456        PointOfInstantiation.isValid() &&
1457        MSInfo->getPointOfInstantiation().isInvalid())
1458      MSInfo->setPointOfInstantiation(PointOfInstantiation);
1459  } else
1460    assert(false && "Function cannot have a template specialization kind");
1461}
1462
1463SourceLocation FunctionDecl::getPointOfInstantiation() const {
1464  if (FunctionTemplateSpecializationInfo *FTSInfo
1465        = TemplateOrSpecialization.dyn_cast<
1466                                        FunctionTemplateSpecializationInfo*>())
1467    return FTSInfo->getPointOfInstantiation();
1468  else if (MemberSpecializationInfo *MSInfo
1469             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
1470    return MSInfo->getPointOfInstantiation();
1471
1472  return SourceLocation();
1473}
1474
1475bool FunctionDecl::isOutOfLine() const {
1476  if (Decl::isOutOfLine())
1477    return true;
1478
1479  // If this function was instantiated from a member function of a
1480  // class template, check whether that member function was defined out-of-line.
1481  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
1482    const FunctionDecl *Definition;
1483    if (FD->hasBody(Definition))
1484      return Definition->isOutOfLine();
1485  }
1486
1487  // If this function was instantiated from a function template,
1488  // check whether that function template was defined out-of-line.
1489  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
1490    const FunctionDecl *Definition;
1491    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
1492      return Definition->isOutOfLine();
1493  }
1494
1495  return false;
1496}
1497
1498//===----------------------------------------------------------------------===//
1499// FieldDecl Implementation
1500//===----------------------------------------------------------------------===//
1501
1502FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1503                             IdentifierInfo *Id, QualType T,
1504                             TypeSourceInfo *TInfo, Expr *BW, bool Mutable) {
1505  return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable);
1506}
1507
1508bool FieldDecl::isAnonymousStructOrUnion() const {
1509  if (!isImplicit() || getDeclName())
1510    return false;
1511
1512  if (const RecordType *Record = getType()->getAs<RecordType>())
1513    return Record->getDecl()->isAnonymousStructOrUnion();
1514
1515  return false;
1516}
1517
1518//===----------------------------------------------------------------------===//
1519// TagDecl Implementation
1520//===----------------------------------------------------------------------===//
1521
1522SourceLocation TagDecl::getOuterLocStart() const {
1523  return getTemplateOrInnerLocStart(this);
1524}
1525
1526SourceRange TagDecl::getSourceRange() const {
1527  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
1528  return SourceRange(getOuterLocStart(), E);
1529}
1530
1531TagDecl* TagDecl::getCanonicalDecl() {
1532  return getFirstDeclaration();
1533}
1534
1535void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) {
1536  TypedefDeclOrQualifier = TDD;
1537  if (TypeForDecl)
1538    TypeForDecl->ClearLinkageCache();
1539}
1540
1541void TagDecl::startDefinition() {
1542  if (TagType *TagT = const_cast<TagType *>(TypeForDecl->getAs<TagType>())) {
1543    TagT->decl.setPointer(this);
1544    TagT->decl.setInt(1);
1545  } else if (InjectedClassNameType *Injected
1546               = const_cast<InjectedClassNameType *>(
1547                                 TypeForDecl->getAs<InjectedClassNameType>())) {
1548    Injected->Decl = cast<CXXRecordDecl>(this);
1549  }
1550
1551  if (isa<CXXRecordDecl>(this)) {
1552    CXXRecordDecl *D = cast<CXXRecordDecl>(this);
1553    struct CXXRecordDecl::DefinitionData *Data =
1554      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
1555    for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
1556      cast<CXXRecordDecl>(*I)->DefinitionData = Data;
1557  }
1558}
1559
1560void TagDecl::completeDefinition() {
1561  assert((!isa<CXXRecordDecl>(this) ||
1562          cast<CXXRecordDecl>(this)->hasDefinition()) &&
1563         "definition completed but not started");
1564
1565  IsDefinition = true;
1566  if (TagType *TagT = const_cast<TagType *>(TypeForDecl->getAs<TagType>())) {
1567    assert(TagT->decl.getPointer() == this &&
1568           "Attempt to redefine a tag definition?");
1569    TagT->decl.setInt(0);
1570  } else if (InjectedClassNameType *Injected
1571               = const_cast<InjectedClassNameType *>(
1572                                TypeForDecl->getAs<InjectedClassNameType>())) {
1573    assert(Injected->Decl == this &&
1574           "Attempt to redefine a class template definition?");
1575    (void)Injected;
1576  }
1577}
1578
1579TagDecl* TagDecl::getDefinition() const {
1580  if (isDefinition())
1581    return const_cast<TagDecl *>(this);
1582
1583  for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
1584       R != REnd; ++R)
1585    if (R->isDefinition())
1586      return *R;
1587
1588  return 0;
1589}
1590
1591void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier,
1592                               SourceRange QualifierRange) {
1593  if (Qualifier) {
1594    // Make sure the extended qualifier info is allocated.
1595    if (!hasExtInfo())
1596      TypedefDeclOrQualifier = new (getASTContext()) ExtInfo;
1597    // Set qualifier info.
1598    getExtInfo()->NNS = Qualifier;
1599    getExtInfo()->NNSRange = QualifierRange;
1600  }
1601  else {
1602    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1603    assert(QualifierRange.isInvalid());
1604    if (hasExtInfo()) {
1605      getASTContext().Deallocate(getExtInfo());
1606      TypedefDeclOrQualifier = (TypedefDecl*) 0;
1607    }
1608  }
1609}
1610
1611//===----------------------------------------------------------------------===//
1612// EnumDecl Implementation
1613//===----------------------------------------------------------------------===//
1614
1615EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1616                           IdentifierInfo *Id, SourceLocation TKL,
1617                           EnumDecl *PrevDecl) {
1618  EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL);
1619  C.getTypeDeclType(Enum, PrevDecl);
1620  return Enum;
1621}
1622
1623EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
1624  return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation());
1625}
1626
1627void EnumDecl::completeDefinition(QualType NewType,
1628                                  QualType NewPromotionType,
1629                                  unsigned NumPositiveBits,
1630                                  unsigned NumNegativeBits) {
1631  assert(!isDefinition() && "Cannot redefine enums!");
1632  IntegerType = NewType;
1633  PromotionType = NewPromotionType;
1634  setNumPositiveBits(NumPositiveBits);
1635  setNumNegativeBits(NumNegativeBits);
1636  TagDecl::completeDefinition();
1637}
1638
1639//===----------------------------------------------------------------------===//
1640// RecordDecl Implementation
1641//===----------------------------------------------------------------------===//
1642
1643RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
1644                       IdentifierInfo *Id, RecordDecl *PrevDecl,
1645                       SourceLocation TKL)
1646  : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) {
1647  HasFlexibleArrayMember = false;
1648  AnonymousStructOrUnion = false;
1649  HasObjectMember = false;
1650  assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
1651}
1652
1653RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
1654                               SourceLocation L, IdentifierInfo *Id,
1655                               SourceLocation TKL, RecordDecl* PrevDecl) {
1656
1657  RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL);
1658  C.getTypeDeclType(R, PrevDecl);
1659  return R;
1660}
1661
1662RecordDecl *RecordDecl::Create(ASTContext &C, EmptyShell Empty) {
1663  return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0,
1664                            SourceLocation());
1665}
1666
1667RecordDecl::~RecordDecl() {
1668}
1669
1670bool RecordDecl::isInjectedClassName() const {
1671  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
1672    cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
1673}
1674
1675/// completeDefinition - Notes that the definition of this type is now
1676/// complete.
1677void RecordDecl::completeDefinition() {
1678  assert(!isDefinition() && "Cannot redefine record!");
1679  TagDecl::completeDefinition();
1680}
1681
1682ValueDecl *RecordDecl::getAnonymousStructOrUnionObject() {
1683  // Force the decl chain to come into existence properly.
1684  if (!getNextDeclInContext()) getParent()->decls_begin();
1685
1686  assert(isAnonymousStructOrUnion());
1687  ValueDecl *D = cast<ValueDecl>(getNextDeclInContext());
1688  assert(D->getType()->isRecordType());
1689  assert(D->getType()->getAs<RecordType>()->getDecl() == this);
1690  return D;
1691}
1692
1693//===----------------------------------------------------------------------===//
1694// BlockDecl Implementation
1695//===----------------------------------------------------------------------===//
1696
1697BlockDecl::~BlockDecl() {
1698}
1699
1700void BlockDecl::setParams(ParmVarDecl **NewParamInfo,
1701                          unsigned NParms) {
1702  assert(ParamInfo == 0 && "Already has param info!");
1703
1704  // Zero params -> null pointer.
1705  if (NParms) {
1706    NumParams = NParms;
1707    void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams);
1708    ParamInfo = new (Mem) ParmVarDecl*[NumParams];
1709    memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
1710  }
1711}
1712
1713unsigned BlockDecl::getNumParams() const {
1714  return NumParams;
1715}
1716
1717
1718//===----------------------------------------------------------------------===//
1719// Other Decl Allocation/Deallocation Method Implementations
1720//===----------------------------------------------------------------------===//
1721
1722TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
1723  return new (C) TranslationUnitDecl(C);
1724}
1725
1726NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1727                                     SourceLocation L, IdentifierInfo *Id) {
1728  return new (C) NamespaceDecl(DC, L, Id);
1729}
1730
1731ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
1732    SourceLocation L, IdentifierInfo *Id, QualType T) {
1733  return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T);
1734}
1735
1736FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
1737                                   SourceLocation L,
1738                                   DeclarationName N, QualType T,
1739                                   TypeSourceInfo *TInfo,
1740                                   StorageClass S, StorageClass SCAsWritten,
1741                                   bool isInline, bool hasWrittenPrototype) {
1742  FunctionDecl *New = new (C) FunctionDecl(Function, DC, L, N, T, TInfo,
1743                                           S, SCAsWritten, isInline);
1744  New->HasWrittenPrototype = hasWrittenPrototype;
1745  return New;
1746}
1747
1748BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
1749  return new (C) BlockDecl(DC, L);
1750}
1751
1752EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
1753                                           SourceLocation L,
1754                                           IdentifierInfo *Id, QualType T,
1755                                           Expr *E, const llvm::APSInt &V) {
1756  return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
1757}
1758
1759TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
1760                                 SourceLocation L, IdentifierInfo *Id,
1761                                 TypeSourceInfo *TInfo) {
1762  return new (C) TypedefDecl(DC, L, Id, TInfo);
1763}
1764
1765// Anchor TypedefDecl's vtable here.
1766TypedefDecl::~TypedefDecl() {}
1767
1768FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
1769                                           SourceLocation L,
1770                                           StringLiteral *Str) {
1771  return new (C) FileScopeAsmDecl(DC, L, Str);
1772}
1773