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