Decl.cpp revision 469a1eb996e1cb0be54f9b210f836afbddcbb2cc
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/AST/ASTMutationListener.h"
25#include "clang/Basic/Builtins.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/Specifiers.h"
28#include "llvm/Support/ErrorHandling.h"
29
30using namespace clang;
31
32//===----------------------------------------------------------------------===//
33// NamedDecl Implementation
34//===----------------------------------------------------------------------===//
35
36static const VisibilityAttr *GetExplicitVisibility(const Decl *d) {
37  // Use the most recent declaration of a variable.
38  if (const VarDecl *var = dyn_cast<VarDecl>(d))
39    return var->getMostRecentDeclaration()->getAttr<VisibilityAttr>();
40
41  // Use the most recent declaration of a function, and also handle
42  // function template specializations.
43  if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(d)) {
44    if (const VisibilityAttr *attr
45          = fn->getMostRecentDeclaration()->getAttr<VisibilityAttr>())
46      return attr;
47
48    // If the function is a specialization of a template with an
49    // explicit visibility attribute, use that.
50    if (FunctionTemplateSpecializationInfo *templateInfo
51          = fn->getTemplateSpecializationInfo())
52      return templateInfo->getTemplate()->getTemplatedDecl()
53        ->getAttr<VisibilityAttr>();
54
55    return 0;
56  }
57
58  // Otherwise, just check the declaration itself first.
59  if (const VisibilityAttr *attr = d->getAttr<VisibilityAttr>())
60    return attr;
61
62  // If there wasn't explicit visibility there, and this is a
63  // specialization of a class template, check for visibility
64  // on the pattern.
65  if (const ClassTemplateSpecializationDecl *spec
66        = dyn_cast<ClassTemplateSpecializationDecl>(d))
67    return spec->getSpecializedTemplate()->getTemplatedDecl()
68      ->getAttr<VisibilityAttr>();
69
70  return 0;
71}
72
73static Visibility GetVisibilityFromAttr(const VisibilityAttr *A) {
74  switch (A->getVisibility()) {
75  case VisibilityAttr::Default:
76    return DefaultVisibility;
77  case VisibilityAttr::Hidden:
78    return HiddenVisibility;
79  case VisibilityAttr::Protected:
80    return ProtectedVisibility;
81  }
82  return DefaultVisibility;
83}
84
85typedef NamedDecl::LinkageInfo LinkageInfo;
86typedef std::pair<Linkage,Visibility> LVPair;
87
88static LVPair merge(LVPair L, LVPair R) {
89  return LVPair(minLinkage(L.first, R.first),
90                minVisibility(L.second, R.second));
91}
92
93static LVPair merge(LVPair L, LinkageInfo R) {
94  return LVPair(minLinkage(L.first, R.linkage()),
95                minVisibility(L.second, R.visibility()));
96}
97
98namespace {
99/// Flags controlling the computation of linkage and visibility.
100struct LVFlags {
101  bool ConsiderGlobalVisibility;
102  bool ConsiderVisibilityAttributes;
103
104  LVFlags() : ConsiderGlobalVisibility(true),
105              ConsiderVisibilityAttributes(true) {
106  }
107
108  /// \brief Returns a set of flags that is only useful for computing the
109  /// linkage, not the visibility, of a declaration.
110  static LVFlags CreateOnlyDeclLinkage() {
111    LVFlags F;
112    F.ConsiderGlobalVisibility = false;
113    F.ConsiderVisibilityAttributes = false;
114    return F;
115  }
116
117  /// Returns a set of flags, otherwise based on these, which ignores
118  /// off all sources of visibility except template arguments.
119  LVFlags onlyTemplateVisibility() const {
120    LVFlags F = *this;
121    F.ConsiderGlobalVisibility = false;
122    F.ConsiderVisibilityAttributes = false;
123    return F;
124  }
125};
126} // end anonymous namespace
127
128/// \brief Get the most restrictive linkage for the types in the given
129/// template parameter list.
130static LVPair
131getLVForTemplateParameterList(const TemplateParameterList *Params) {
132  LVPair LV(ExternalLinkage, DefaultVisibility);
133  for (TemplateParameterList::const_iterator P = Params->begin(),
134                                          PEnd = Params->end();
135       P != PEnd; ++P) {
136    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
137      if (NTTP->isExpandedParameterPack()) {
138        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
139          QualType T = NTTP->getExpansionType(I);
140          if (!T->isDependentType())
141            LV = merge(LV, T->getLinkageAndVisibility());
142        }
143        continue;
144      }
145
146      if (!NTTP->getType()->isDependentType()) {
147        LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
148        continue;
149      }
150    }
151
152    if (TemplateTemplateParmDecl *TTP
153                                   = dyn_cast<TemplateTemplateParmDecl>(*P)) {
154      LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
155    }
156  }
157
158  return LV;
159}
160
161/// getLVForDecl - Get the linkage and visibility for the given declaration.
162static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
163
164/// \brief Get the most restrictive linkage for the types and
165/// declarations in the given template argument list.
166static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
167                                           unsigned NumArgs,
168                                           LVFlags &F) {
169  LVPair LV(ExternalLinkage, DefaultVisibility);
170
171  for (unsigned I = 0; I != NumArgs; ++I) {
172    switch (Args[I].getKind()) {
173    case TemplateArgument::Null:
174    case TemplateArgument::Integral:
175    case TemplateArgument::Expression:
176      break;
177
178    case TemplateArgument::Type:
179      LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
180      break;
181
182    case TemplateArgument::Declaration:
183      // The decl can validly be null as the representation of nullptr
184      // arguments, valid only in C++0x.
185      if (Decl *D = Args[I].getAsDecl()) {
186        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
187          LV = merge(LV, getLVForDecl(ND, F));
188      }
189      break;
190
191    case TemplateArgument::Template:
192    case TemplateArgument::TemplateExpansion:
193      if (TemplateDecl *Template
194                = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
195        LV = merge(LV, getLVForDecl(Template, F));
196      break;
197
198    case TemplateArgument::Pack:
199      LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
200                                                  Args[I].pack_size(),
201                                                  F));
202      break;
203    }
204  }
205
206  return LV;
207}
208
209static LVPair
210getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
211                             LVFlags &F) {
212  return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
213}
214
215static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
216  assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
217         "Not a name having namespace scope");
218  ASTContext &Context = D->getASTContext();
219
220  // C++ [basic.link]p3:
221  //   A name having namespace scope (3.3.6) has internal linkage if it
222  //   is the name of
223  //     - an object, reference, function or function template that is
224  //       explicitly declared static; or,
225  // (This bullet corresponds to C99 6.2.2p3.)
226  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
227    // Explicitly declared static.
228    if (Var->getStorageClass() == SC_Static)
229      return LinkageInfo::internal();
230
231    // - an object or reference that is explicitly declared const
232    //   and neither explicitly declared extern nor previously
233    //   declared to have external linkage; or
234    // (there is no equivalent in C99)
235    if (Context.getLangOptions().CPlusPlus &&
236        Var->getType().isConstant(Context) &&
237        Var->getStorageClass() != SC_Extern &&
238        Var->getStorageClass() != SC_PrivateExtern) {
239      bool FoundExtern = false;
240      for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
241           PrevVar && !FoundExtern;
242           PrevVar = PrevVar->getPreviousDeclaration())
243        if (isExternalLinkage(PrevVar->getLinkage()))
244          FoundExtern = true;
245
246      if (!FoundExtern)
247        return LinkageInfo::internal();
248    }
249  } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
250    // C++ [temp]p4:
251    //   A non-member function template can have internal linkage; any
252    //   other template name shall have external linkage.
253    const FunctionDecl *Function = 0;
254    if (const FunctionTemplateDecl *FunTmpl
255                                        = dyn_cast<FunctionTemplateDecl>(D))
256      Function = FunTmpl->getTemplatedDecl();
257    else
258      Function = cast<FunctionDecl>(D);
259
260    // Explicitly declared static.
261    if (Function->getStorageClass() == SC_Static)
262      return LinkageInfo(InternalLinkage, DefaultVisibility, false);
263  } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
264    //   - a data member of an anonymous union.
265    if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
266      return LinkageInfo::internal();
267  }
268
269  if (D->isInAnonymousNamespace())
270    return LinkageInfo::uniqueExternal();
271
272  // Set up the defaults.
273
274  // C99 6.2.2p5:
275  //   If the declaration of an identifier for an object has file
276  //   scope and no storage-class specifier, its linkage is
277  //   external.
278  LinkageInfo LV;
279
280  if (F.ConsiderVisibilityAttributes) {
281    if (const VisibilityAttr *VA = GetExplicitVisibility(D)) {
282      LV.setVisibility(GetVisibilityFromAttr(VA), true);
283      F.ConsiderGlobalVisibility = false;
284    } else {
285      // If we're declared in a namespace with a visibility attribute,
286      // use that namespace's visibility, but don't call it explicit.
287      for (const DeclContext *DC = D->getDeclContext();
288           !isa<TranslationUnitDecl>(DC);
289           DC = DC->getParent()) {
290        if (!isa<NamespaceDecl>(DC)) continue;
291        if (const VisibilityAttr *VA =
292              cast<NamespaceDecl>(DC)->getAttr<VisibilityAttr>()) {
293          LV.setVisibility(GetVisibilityFromAttr(VA), false);
294          F.ConsiderGlobalVisibility = false;
295          break;
296        }
297      }
298    }
299  }
300
301  // C++ [basic.link]p4:
302
303  //   A name having namespace scope has external linkage if it is the
304  //   name of
305  //
306  //     - an object or reference, unless it has internal linkage; or
307  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
308    // GCC applies the following optimization to variables and static
309    // data members, but not to functions:
310    //
311    // Modify the variable's LV by the LV of its type unless this is
312    // C or extern "C".  This follows from [basic.link]p9:
313    //   A type without linkage shall not be used as the type of a
314    //   variable or function with external linkage unless
315    //    - the entity has C language linkage, or
316    //    - the entity is declared within an unnamed namespace, or
317    //    - the entity is not used or is defined in the same
318    //      translation unit.
319    // and [basic.link]p10:
320    //   ...the types specified by all declarations referring to a
321    //   given variable or function shall be identical...
322    // C does not have an equivalent rule.
323    //
324    // Ignore this if we've got an explicit attribute;  the user
325    // probably knows what they're doing.
326    //
327    // Note that we don't want to make the variable non-external
328    // because of this, but unique-external linkage suits us.
329    if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
330      LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
331      if (TypeLV.first != ExternalLinkage)
332        return LinkageInfo::uniqueExternal();
333      if (!LV.visibilityExplicit())
334        LV.mergeVisibility(TypeLV.second);
335    }
336
337    if (Var->getStorageClass() == SC_PrivateExtern)
338      LV.setVisibility(HiddenVisibility, true);
339
340    if (!Context.getLangOptions().CPlusPlus &&
341        (Var->getStorageClass() == SC_Extern ||
342         Var->getStorageClass() == SC_PrivateExtern)) {
343
344      // C99 6.2.2p4:
345      //   For an identifier declared with the storage-class specifier
346      //   extern in a scope in which a prior declaration of that
347      //   identifier is visible, if the prior declaration specifies
348      //   internal or external linkage, the linkage of the identifier
349      //   at the later declaration is the same as the linkage
350      //   specified at the prior declaration. If no prior declaration
351      //   is visible, or if the prior declaration specifies no
352      //   linkage, then the identifier has external linkage.
353      if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
354        LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
355        if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
356        LV.mergeVisibility(PrevLV);
357      }
358    }
359
360  //     - a function, unless it has internal linkage; or
361  } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
362    // In theory, we can modify the function's LV by the LV of its
363    // type unless it has C linkage (see comment above about variables
364    // for justification).  In practice, GCC doesn't do this, so it's
365    // just too painful to make work.
366
367    if (Function->getStorageClass() == SC_PrivateExtern)
368      LV.setVisibility(HiddenVisibility, true);
369
370    // C99 6.2.2p5:
371    //   If the declaration of an identifier for a function has no
372    //   storage-class specifier, its linkage is determined exactly
373    //   as if it were declared with the storage-class specifier
374    //   extern.
375    if (!Context.getLangOptions().CPlusPlus &&
376        (Function->getStorageClass() == SC_Extern ||
377         Function->getStorageClass() == SC_PrivateExtern ||
378         Function->getStorageClass() == SC_None)) {
379      // C99 6.2.2p4:
380      //   For an identifier declared with the storage-class specifier
381      //   extern in a scope in which a prior declaration of that
382      //   identifier is visible, if the prior declaration specifies
383      //   internal or external linkage, the linkage of the identifier
384      //   at the later declaration is the same as the linkage
385      //   specified at the prior declaration. If no prior declaration
386      //   is visible, or if the prior declaration specifies no
387      //   linkage, then the identifier has external linkage.
388      if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
389        LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
390        if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
391        LV.mergeVisibility(PrevLV);
392      }
393    }
394
395    if (FunctionTemplateSpecializationInfo *SpecInfo
396                               = Function->getTemplateSpecializationInfo()) {
397      LV.merge(getLVForDecl(SpecInfo->getTemplate(),
398                            F.onlyTemplateVisibility()));
399      const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments;
400      LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
401    }
402
403  //     - a named class (Clause 9), or an unnamed class defined in a
404  //       typedef declaration in which the class has the typedef name
405  //       for linkage purposes (7.1.3); or
406  //     - a named enumeration (7.2), or an unnamed enumeration
407  //       defined in a typedef declaration in which the enumeration
408  //       has the typedef name for linkage purposes (7.1.3); or
409  } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
410    // Unnamed tags have no linkage.
411    if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl())
412      return LinkageInfo::none();
413
414    // If this is a class template specialization, consider the
415    // linkage of the template and template arguments.
416    if (const ClassTemplateSpecializationDecl *Spec
417          = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
418      // From the template.
419      LV.merge(getLVForDecl(Spec->getSpecializedTemplate(),
420                            F.onlyTemplateVisibility()));
421
422      // The arguments at which the template was instantiated.
423      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
424      LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
425    }
426
427    // Consider -fvisibility unless the type has C linkage.
428    if (F.ConsiderGlobalVisibility)
429      F.ConsiderGlobalVisibility =
430        (Context.getLangOptions().CPlusPlus &&
431         !Tag->getDeclContext()->isExternCContext());
432
433  //     - an enumerator belonging to an enumeration with external linkage;
434  } else if (isa<EnumConstantDecl>(D)) {
435    LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
436    if (!isExternalLinkage(EnumLV.linkage()))
437      return LinkageInfo::none();
438    LV.merge(EnumLV);
439
440  //     - a template, unless it is a function template that has
441  //       internal linkage (Clause 14);
442  } else if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
443    LV.merge(getLVForTemplateParameterList(Template->getTemplateParameters()));
444
445  //     - a namespace (7.3), unless it is declared within an unnamed
446  //       namespace.
447  } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
448    return LV;
449
450  // By extension, we assign external linkage to Objective-C
451  // interfaces.
452  } else if (isa<ObjCInterfaceDecl>(D)) {
453    // fallout
454
455  // Everything not covered here has no linkage.
456  } else {
457    return LinkageInfo::none();
458  }
459
460  // If we ended up with non-external linkage, visibility should
461  // always be default.
462  if (LV.linkage() != ExternalLinkage)
463    return LinkageInfo(LV.linkage(), DefaultVisibility, false);
464
465  // If we didn't end up with hidden visibility, consider attributes
466  // and -fvisibility.
467  if (F.ConsiderGlobalVisibility)
468    LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
469
470  return LV;
471}
472
473static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
474  // Only certain class members have linkage.  Note that fields don't
475  // really have linkage, but it's convenient to say they do for the
476  // purposes of calculating linkage of pointer-to-data-member
477  // template arguments.
478  if (!(isa<CXXMethodDecl>(D) ||
479        isa<VarDecl>(D) ||
480        isa<FieldDecl>(D) ||
481        (isa<TagDecl>(D) &&
482         (D->getDeclName() || cast<TagDecl>(D)->getTypedefForAnonDecl()))))
483    return LinkageInfo::none();
484
485  LinkageInfo LV;
486
487  // The flags we're going to use to compute the class's visibility.
488  LVFlags ClassF = F;
489
490  // If we have an explicit visibility attribute, merge that in.
491  if (F.ConsiderVisibilityAttributes) {
492    if (const VisibilityAttr *VA = GetExplicitVisibility(D)) {
493      LV.mergeVisibility(GetVisibilityFromAttr(VA), true);
494
495      // Ignore global visibility later, but not this attribute.
496      F.ConsiderGlobalVisibility = false;
497
498      // Ignore both global visibility and attributes when computing our
499      // parent's visibility.
500      ClassF = F.onlyTemplateVisibility();
501    }
502  }
503
504  // Class members only have linkage if their class has external
505  // linkage.
506  LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
507  if (!isExternalLinkage(LV.linkage()))
508    return LinkageInfo::none();
509
510  // If the class already has unique-external linkage, we can't improve.
511  if (LV.linkage() == UniqueExternalLinkage)
512    return LinkageInfo::uniqueExternal();
513
514  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
515    TemplateSpecializationKind TSK = TSK_Undeclared;
516
517    // If this is a method template specialization, use the linkage for
518    // the template parameters and arguments.
519    if (FunctionTemplateSpecializationInfo *Spec
520           = MD->getTemplateSpecializationInfo()) {
521      LV.merge(getLVForTemplateArgumentList(*Spec->TemplateArguments, F));
522      LV.merge(getLVForTemplateParameterList(
523                              Spec->getTemplate()->getTemplateParameters()));
524
525      TSK = Spec->getTemplateSpecializationKind();
526    } else if (MemberSpecializationInfo *MSI =
527                 MD->getMemberSpecializationInfo()) {
528      TSK = MSI->getTemplateSpecializationKind();
529    }
530
531    // If we're paying attention to global visibility, apply
532    // -finline-visibility-hidden if this is an inline method.
533    //
534    // Note that ConsiderGlobalVisibility doesn't yet have information
535    // about whether containing classes have visibility attributes,
536    // and that's intentional.
537    if (TSK != TSK_ExplicitInstantiationDeclaration &&
538        F.ConsiderGlobalVisibility &&
539        MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
540      // InlineVisibilityHidden only applies to definitions, and
541      // isInlined() only gives meaningful answers on definitions
542      // anyway.
543      const FunctionDecl *Def = 0;
544      if (MD->hasBody(Def) && Def->isInlined())
545        LV.setVisibility(HiddenVisibility);
546    }
547
548    // Note that in contrast to basically every other situation, we
549    // *do* apply -fvisibility to method declarations.
550
551  } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
552    if (const ClassTemplateSpecializationDecl *Spec
553        = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
554      // Merge template argument/parameter information for member
555      // class template specializations.
556      LV.merge(getLVForTemplateArgumentList(Spec->getTemplateArgs(), F));
557      LV.merge(getLVForTemplateParameterList(
558                    Spec->getSpecializedTemplate()->getTemplateParameters()));
559    }
560
561  // Static data members.
562  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
563    // Modify the variable's linkage by its type, but ignore the
564    // type's visibility unless it's a definition.
565    LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
566    if (TypeLV.first != ExternalLinkage)
567      LV.mergeLinkage(UniqueExternalLinkage);
568    if (!LV.visibilityExplicit())
569      LV.mergeVisibility(TypeLV.second);
570  }
571
572  F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
573
574  // Apply -fvisibility if desired.
575  if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
576    LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
577  }
578
579  return LV;
580}
581
582Linkage NamedDecl::getLinkage() const {
583  if (HasCachedLinkage) {
584    assert(Linkage(CachedLinkage) ==
585             getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
586    return Linkage(CachedLinkage);
587  }
588
589  CachedLinkage = getLVForDecl(this,
590                               LVFlags::CreateOnlyDeclLinkage()).linkage();
591  HasCachedLinkage = 1;
592  return Linkage(CachedLinkage);
593}
594
595LinkageInfo NamedDecl::getLinkageAndVisibility() const {
596  LinkageInfo LI = getLVForDecl(this, LVFlags());
597  assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
598  HasCachedLinkage = 1;
599  CachedLinkage = LI.linkage();
600  return LI;
601}
602
603static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
604  // Objective-C: treat all Objective-C declarations as having external
605  // linkage.
606  switch (D->getKind()) {
607    default:
608      break;
609    case Decl::TemplateTemplateParm: // count these as external
610    case Decl::NonTypeTemplateParm:
611    case Decl::ObjCAtDefsField:
612    case Decl::ObjCCategory:
613    case Decl::ObjCCategoryImpl:
614    case Decl::ObjCCompatibleAlias:
615    case Decl::ObjCForwardProtocol:
616    case Decl::ObjCImplementation:
617    case Decl::ObjCMethod:
618    case Decl::ObjCProperty:
619    case Decl::ObjCPropertyImpl:
620    case Decl::ObjCProtocol:
621      return LinkageInfo::external();
622  }
623
624  // Handle linkage for namespace-scope names.
625  if (D->getDeclContext()->getRedeclContext()->isFileContext())
626    return getLVForNamespaceScopeDecl(D, Flags);
627
628  // C++ [basic.link]p5:
629  //   In addition, a member function, static data member, a named
630  //   class or enumeration of class scope, or an unnamed class or
631  //   enumeration defined in a class-scope typedef declaration such
632  //   that the class or enumeration has the typedef name for linkage
633  //   purposes (7.1.3), has external linkage if the name of the class
634  //   has external linkage.
635  if (D->getDeclContext()->isRecord())
636    return getLVForClassMember(D, Flags);
637
638  // C++ [basic.link]p6:
639  //   The name of a function declared in block scope and the name of
640  //   an object declared by a block scope extern declaration have
641  //   linkage. If there is a visible declaration of an entity with
642  //   linkage having the same name and type, ignoring entities
643  //   declared outside the innermost enclosing namespace scope, the
644  //   block scope declaration declares that same entity and receives
645  //   the linkage of the previous declaration. If there is more than
646  //   one such matching entity, the program is ill-formed. Otherwise,
647  //   if no matching entity is found, the block scope entity receives
648  //   external linkage.
649  if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
650    if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
651      if (Function->isInAnonymousNamespace())
652        return LinkageInfo::uniqueExternal();
653
654      LinkageInfo LV;
655      if (Flags.ConsiderVisibilityAttributes) {
656        if (const VisibilityAttr *VA = GetExplicitVisibility(Function))
657          LV.setVisibility(GetVisibilityFromAttr(VA));
658      }
659
660      if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
661        LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
662        if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
663        LV.mergeVisibility(PrevLV);
664      }
665
666      return LV;
667    }
668
669    if (const VarDecl *Var = dyn_cast<VarDecl>(D))
670      if (Var->getStorageClass() == SC_Extern ||
671          Var->getStorageClass() == SC_PrivateExtern) {
672        if (Var->isInAnonymousNamespace())
673          return LinkageInfo::uniqueExternal();
674
675        LinkageInfo LV;
676        if (Var->getStorageClass() == SC_PrivateExtern)
677          LV.setVisibility(HiddenVisibility);
678        else if (Flags.ConsiderVisibilityAttributes) {
679          if (const VisibilityAttr *VA = GetExplicitVisibility(Var))
680            LV.setVisibility(GetVisibilityFromAttr(VA));
681        }
682
683        if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
684          LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
685          if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
686          LV.mergeVisibility(PrevLV);
687        }
688
689        return LV;
690      }
691  }
692
693  // C++ [basic.link]p6:
694  //   Names not covered by these rules have no linkage.
695  return LinkageInfo::none();
696}
697
698std::string NamedDecl::getQualifiedNameAsString() const {
699  return getQualifiedNameAsString(getASTContext().getLangOptions());
700}
701
702std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
703  const DeclContext *Ctx = getDeclContext();
704
705  if (Ctx->isFunctionOrMethod())
706    return getNameAsString();
707
708  typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy;
709  ContextsTy Contexts;
710
711  // Collect contexts.
712  while (Ctx && isa<NamedDecl>(Ctx)) {
713    Contexts.push_back(Ctx);
714    Ctx = Ctx->getParent();
715  };
716
717  std::string QualName;
718  llvm::raw_string_ostream OS(QualName);
719
720  for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
721       I != E; ++I) {
722    if (const ClassTemplateSpecializationDecl *Spec
723          = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
724      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
725      std::string TemplateArgsStr
726        = TemplateSpecializationType::PrintTemplateArgumentList(
727                                           TemplateArgs.data(),
728                                           TemplateArgs.size(),
729                                           P);
730      OS << Spec->getName() << TemplateArgsStr;
731    } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
732      if (ND->isAnonymousNamespace())
733        OS << "<anonymous namespace>";
734      else
735        OS << ND;
736    } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
737      if (!RD->getIdentifier())
738        OS << "<anonymous " << RD->getKindName() << '>';
739      else
740        OS << RD;
741    } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
742      const FunctionProtoType *FT = 0;
743      if (FD->hasWrittenPrototype())
744        FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
745
746      OS << FD << '(';
747      if (FT) {
748        unsigned NumParams = FD->getNumParams();
749        for (unsigned i = 0; i < NumParams; ++i) {
750          if (i)
751            OS << ", ";
752          std::string Param;
753          FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
754          OS << Param;
755        }
756
757        if (FT->isVariadic()) {
758          if (NumParams > 0)
759            OS << ", ";
760          OS << "...";
761        }
762      }
763      OS << ')';
764    } else {
765      OS << cast<NamedDecl>(*I);
766    }
767    OS << "::";
768  }
769
770  if (getDeclName())
771    OS << this;
772  else
773    OS << "<anonymous>";
774
775  return OS.str();
776}
777
778bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
779  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
780
781  // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
782  // We want to keep it, unless it nominates same namespace.
783  if (getKind() == Decl::UsingDirective) {
784    return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() ==
785           cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace();
786  }
787
788  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
789    // For function declarations, we keep track of redeclarations.
790    return FD->getPreviousDeclaration() == OldD;
791
792  // For function templates, the underlying function declarations are linked.
793  if (const FunctionTemplateDecl *FunctionTemplate
794        = dyn_cast<FunctionTemplateDecl>(this))
795    if (const FunctionTemplateDecl *OldFunctionTemplate
796          = dyn_cast<FunctionTemplateDecl>(OldD))
797      return FunctionTemplate->getTemplatedDecl()
798               ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
799
800  // For method declarations, we keep track of redeclarations.
801  if (isa<ObjCMethodDecl>(this))
802    return false;
803
804  if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
805    return true;
806
807  if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
808    return cast<UsingShadowDecl>(this)->getTargetDecl() ==
809           cast<UsingShadowDecl>(OldD)->getTargetDecl();
810
811  if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD))
812    return cast<UsingDecl>(this)->getTargetNestedNameDecl() ==
813           cast<UsingDecl>(OldD)->getTargetNestedNameDecl();
814
815  // For non-function declarations, if the declarations are of the
816  // same kind then this must be a redeclaration, or semantic analysis
817  // would not have given us the new declaration.
818  return this->getKind() == OldD->getKind();
819}
820
821bool NamedDecl::hasLinkage() const {
822  return getLinkage() != NoLinkage;
823}
824
825NamedDecl *NamedDecl::getUnderlyingDecl() {
826  NamedDecl *ND = this;
827  while (true) {
828    if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
829      ND = UD->getTargetDecl();
830    else if (ObjCCompatibleAliasDecl *AD
831              = dyn_cast<ObjCCompatibleAliasDecl>(ND))
832      return AD->getClassInterface();
833    else
834      return ND;
835  }
836}
837
838bool NamedDecl::isCXXInstanceMember() const {
839  assert(isCXXClassMember() &&
840         "checking whether non-member is instance member");
841
842  const NamedDecl *D = this;
843  if (isa<UsingShadowDecl>(D))
844    D = cast<UsingShadowDecl>(D)->getTargetDecl();
845
846  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
847    return true;
848  if (isa<CXXMethodDecl>(D))
849    return cast<CXXMethodDecl>(D)->isInstance();
850  if (isa<FunctionTemplateDecl>(D))
851    return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
852                                 ->getTemplatedDecl())->isInstance();
853  return false;
854}
855
856//===----------------------------------------------------------------------===//
857// DeclaratorDecl Implementation
858//===----------------------------------------------------------------------===//
859
860template <typename DeclT>
861static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
862  if (decl->getNumTemplateParameterLists() > 0)
863    return decl->getTemplateParameterList(0)->getTemplateLoc();
864  else
865    return decl->getInnerLocStart();
866}
867
868SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
869  TypeSourceInfo *TSI = getTypeSourceInfo();
870  if (TSI) return TSI->getTypeLoc().getBeginLoc();
871  return SourceLocation();
872}
873
874void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier,
875                                      SourceRange QualifierRange) {
876  if (Qualifier) {
877    // Make sure the extended decl info is allocated.
878    if (!hasExtInfo()) {
879      // Save (non-extended) type source info pointer.
880      TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
881      // Allocate external info struct.
882      DeclInfo = new (getASTContext()) ExtInfo;
883      // Restore savedTInfo into (extended) decl info.
884      getExtInfo()->TInfo = savedTInfo;
885    }
886    // Set qualifier info.
887    getExtInfo()->NNS = Qualifier;
888    getExtInfo()->NNSRange = QualifierRange;
889  }
890  else {
891    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
892    assert(QualifierRange.isInvalid());
893    if (hasExtInfo()) {
894      // Save type source info pointer.
895      TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
896      // Deallocate the extended decl info.
897      getASTContext().Deallocate(getExtInfo());
898      // Restore savedTInfo into (non-extended) decl info.
899      DeclInfo = savedTInfo;
900    }
901  }
902}
903
904SourceLocation DeclaratorDecl::getOuterLocStart() const {
905  return getTemplateOrInnerLocStart(this);
906}
907
908void
909QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
910                                             unsigned NumTPLists,
911                                             TemplateParameterList **TPLists) {
912  assert((NumTPLists == 0 || TPLists != 0) &&
913         "Empty array of template parameters with positive size!");
914  assert((NumTPLists == 0 || NNS) &&
915         "Nonempty array of template parameters with no qualifier!");
916
917  // Free previous template parameters (if any).
918  if (NumTemplParamLists > 0) {
919    Context.Deallocate(TemplParamLists);
920    TemplParamLists = 0;
921    NumTemplParamLists = 0;
922  }
923  // Set info on matched template parameter lists (if any).
924  if (NumTPLists > 0) {
925    TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
926    NumTemplParamLists = NumTPLists;
927    for (unsigned i = NumTPLists; i-- > 0; )
928      TemplParamLists[i] = TPLists[i];
929  }
930}
931
932//===----------------------------------------------------------------------===//
933// VarDecl Implementation
934//===----------------------------------------------------------------------===//
935
936const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
937  switch (SC) {
938  case SC_None:          break;
939  case SC_Auto:          return "auto"; break;
940  case SC_Extern:        return "extern"; break;
941  case SC_PrivateExtern: return "__private_extern__"; break;
942  case SC_Register:      return "register"; break;
943  case SC_Static:        return "static"; break;
944  }
945
946  assert(0 && "Invalid storage class");
947  return 0;
948}
949
950VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
951                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
952                         StorageClass S, StorageClass SCAsWritten) {
953  return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten);
954}
955
956void VarDecl::setStorageClass(StorageClass SC) {
957  assert(isLegalForVariable(SC));
958  if (getStorageClass() != SC)
959    ClearLinkageCache();
960
961  SClass = SC;
962}
963
964SourceLocation VarDecl::getInnerLocStart() const {
965  SourceLocation Start = getTypeSpecStartLoc();
966  if (Start.isInvalid())
967    Start = getLocation();
968  return Start;
969}
970
971SourceRange VarDecl::getSourceRange() const {
972  if (getInit())
973    return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
974  return SourceRange(getOuterLocStart(), getLocation());
975}
976
977bool VarDecl::isExternC() const {
978  ASTContext &Context = getASTContext();
979  if (!Context.getLangOptions().CPlusPlus)
980    return (getDeclContext()->isTranslationUnit() &&
981            getStorageClass() != SC_Static) ||
982      (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
983
984  for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
985       DC = DC->getParent()) {
986    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
987      if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
988        return getStorageClass() != SC_Static;
989
990      break;
991    }
992
993    if (DC->isFunctionOrMethod())
994      return false;
995  }
996
997  return false;
998}
999
1000VarDecl *VarDecl::getCanonicalDecl() {
1001  return getFirstDeclaration();
1002}
1003
1004VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1005  // C++ [basic.def]p2:
1006  //   A declaration is a definition unless [...] it contains the 'extern'
1007  //   specifier or a linkage-specification and neither an initializer [...],
1008  //   it declares a static data member in a class declaration [...].
1009  // C++ [temp.expl.spec]p15:
1010  //   An explicit specialization of a static data member of a template is a
1011  //   definition if the declaration includes an initializer; otherwise, it is
1012  //   a declaration.
1013  if (isStaticDataMember()) {
1014    if (isOutOfLine() && (hasInit() ||
1015          getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1016      return Definition;
1017    else
1018      return DeclarationOnly;
1019  }
1020  // C99 6.7p5:
1021  //   A definition of an identifier is a declaration for that identifier that
1022  //   [...] causes storage to be reserved for that object.
1023  // Note: that applies for all non-file-scope objects.
1024  // C99 6.9.2p1:
1025  //   If the declaration of an identifier for an object has file scope and an
1026  //   initializer, the declaration is an external definition for the identifier
1027  if (hasInit())
1028    return Definition;
1029  // AST for 'extern "C" int foo;' is annotated with 'extern'.
1030  if (hasExternalStorage())
1031    return DeclarationOnly;
1032
1033  if (getStorageClassAsWritten() == SC_Extern ||
1034       getStorageClassAsWritten() == SC_PrivateExtern) {
1035    for (const VarDecl *PrevVar = getPreviousDeclaration();
1036         PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
1037      if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1038        return DeclarationOnly;
1039    }
1040  }
1041  // C99 6.9.2p2:
1042  //   A declaration of an object that has file scope without an initializer,
1043  //   and without a storage class specifier or the scs 'static', constitutes
1044  //   a tentative definition.
1045  // No such thing in C++.
1046  if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1047    return TentativeDefinition;
1048
1049  // What's left is (in C, block-scope) declarations without initializers or
1050  // external storage. These are definitions.
1051  return Definition;
1052}
1053
1054VarDecl *VarDecl::getActingDefinition() {
1055  DefinitionKind Kind = isThisDeclarationADefinition();
1056  if (Kind != TentativeDefinition)
1057    return 0;
1058
1059  VarDecl *LastTentative = 0;
1060  VarDecl *First = getFirstDeclaration();
1061  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1062       I != E; ++I) {
1063    Kind = (*I)->isThisDeclarationADefinition();
1064    if (Kind == Definition)
1065      return 0;
1066    else if (Kind == TentativeDefinition)
1067      LastTentative = *I;
1068  }
1069  return LastTentative;
1070}
1071
1072bool VarDecl::isTentativeDefinitionNow() const {
1073  DefinitionKind Kind = isThisDeclarationADefinition();
1074  if (Kind != TentativeDefinition)
1075    return false;
1076
1077  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1078    if ((*I)->isThisDeclarationADefinition() == Definition)
1079      return false;
1080  }
1081  return true;
1082}
1083
1084VarDecl *VarDecl::getDefinition() {
1085  VarDecl *First = getFirstDeclaration();
1086  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1087       I != E; ++I) {
1088    if ((*I)->isThisDeclarationADefinition() == Definition)
1089      return *I;
1090  }
1091  return 0;
1092}
1093
1094VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1095  DefinitionKind Kind = DeclarationOnly;
1096
1097  const VarDecl *First = getFirstDeclaration();
1098  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1099       I != E; ++I)
1100    Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1101
1102  return Kind;
1103}
1104
1105const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1106  redecl_iterator I = redecls_begin(), E = redecls_end();
1107  while (I != E && !I->getInit())
1108    ++I;
1109
1110  if (I != E) {
1111    D = *I;
1112    return I->getInit();
1113  }
1114  return 0;
1115}
1116
1117bool VarDecl::isOutOfLine() const {
1118  if (Decl::isOutOfLine())
1119    return true;
1120
1121  if (!isStaticDataMember())
1122    return false;
1123
1124  // If this static data member was instantiated from a static data member of
1125  // a class template, check whether that static data member was defined
1126  // out-of-line.
1127  if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1128    return VD->isOutOfLine();
1129
1130  return false;
1131}
1132
1133VarDecl *VarDecl::getOutOfLineDefinition() {
1134  if (!isStaticDataMember())
1135    return 0;
1136
1137  for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1138       RD != RDEnd; ++RD) {
1139    if (RD->getLexicalDeclContext()->isFileContext())
1140      return *RD;
1141  }
1142
1143  return 0;
1144}
1145
1146void VarDecl::setInit(Expr *I) {
1147  if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1148    Eval->~EvaluatedStmt();
1149    getASTContext().Deallocate(Eval);
1150  }
1151
1152  Init = I;
1153}
1154
1155VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1156  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1157    return cast<VarDecl>(MSI->getInstantiatedFrom());
1158
1159  return 0;
1160}
1161
1162TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1163  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1164    return MSI->getTemplateSpecializationKind();
1165
1166  return TSK_Undeclared;
1167}
1168
1169MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1170  return getASTContext().getInstantiatedFromStaticDataMember(this);
1171}
1172
1173void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1174                                         SourceLocation PointOfInstantiation) {
1175  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1176  assert(MSI && "Not an instantiated static data member?");
1177  MSI->setTemplateSpecializationKind(TSK);
1178  if (TSK != TSK_ExplicitSpecialization &&
1179      PointOfInstantiation.isValid() &&
1180      MSI->getPointOfInstantiation().isInvalid())
1181    MSI->setPointOfInstantiation(PointOfInstantiation);
1182}
1183
1184//===----------------------------------------------------------------------===//
1185// ParmVarDecl Implementation
1186//===----------------------------------------------------------------------===//
1187
1188ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1189                                 SourceLocation L, IdentifierInfo *Id,
1190                                 QualType T, TypeSourceInfo *TInfo,
1191                                 StorageClass S, StorageClass SCAsWritten,
1192                                 Expr *DefArg) {
1193  return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo,
1194                             S, SCAsWritten, DefArg);
1195}
1196
1197Expr *ParmVarDecl::getDefaultArg() {
1198  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1199  assert(!hasUninstantiatedDefaultArg() &&
1200         "Default argument is not yet instantiated!");
1201
1202  Expr *Arg = getInit();
1203  if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1204    return E->getSubExpr();
1205
1206  return Arg;
1207}
1208
1209unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
1210  if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit()))
1211    return E->getNumTemporaries();
1212
1213  return 0;
1214}
1215
1216CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
1217  assert(getNumDefaultArgTemporaries() &&
1218         "Default arguments does not have any temporaries!");
1219
1220  ExprWithCleanups *E = cast<ExprWithCleanups>(getInit());
1221  return E->getTemporary(i);
1222}
1223
1224SourceRange ParmVarDecl::getDefaultArgRange() const {
1225  if (const Expr *E = getInit())
1226    return E->getSourceRange();
1227
1228  if (hasUninstantiatedDefaultArg())
1229    return getUninstantiatedDefaultArg()->getSourceRange();
1230
1231  return SourceRange();
1232}
1233
1234bool ParmVarDecl::isParameterPack() const {
1235  return isa<PackExpansionType>(getType());
1236}
1237
1238//===----------------------------------------------------------------------===//
1239// FunctionDecl Implementation
1240//===----------------------------------------------------------------------===//
1241
1242void FunctionDecl::getNameForDiagnostic(std::string &S,
1243                                        const PrintingPolicy &Policy,
1244                                        bool Qualified) const {
1245  NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1246  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1247  if (TemplateArgs)
1248    S += TemplateSpecializationType::PrintTemplateArgumentList(
1249                                                         TemplateArgs->data(),
1250                                                         TemplateArgs->size(),
1251                                                               Policy);
1252
1253}
1254
1255bool FunctionDecl::isVariadic() const {
1256  if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1257    return FT->isVariadic();
1258  return false;
1259}
1260
1261bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1262  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1263    if (I->Body) {
1264      Definition = *I;
1265      return true;
1266    }
1267  }
1268
1269  return false;
1270}
1271
1272Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1273  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1274    if (I->Body) {
1275      Definition = *I;
1276      return I->Body.get(getASTContext().getExternalSource());
1277    }
1278  }
1279
1280  return 0;
1281}
1282
1283void FunctionDecl::setBody(Stmt *B) {
1284  Body = B;
1285  if (B)
1286    EndRangeLoc = B->getLocEnd();
1287}
1288
1289void FunctionDecl::setPure(bool P) {
1290  IsPure = P;
1291  if (P)
1292    if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1293      Parent->markedVirtualFunctionPure();
1294}
1295
1296bool FunctionDecl::isMain() const {
1297  ASTContext &Context = getASTContext();
1298  return !Context.getLangOptions().Freestanding &&
1299    getDeclContext()->getRedeclContext()->isTranslationUnit() &&
1300    getIdentifier() && getIdentifier()->isStr("main");
1301}
1302
1303bool FunctionDecl::isExternC() const {
1304  ASTContext &Context = getASTContext();
1305  // In C, any non-static, non-overloadable function has external
1306  // linkage.
1307  if (!Context.getLangOptions().CPlusPlus)
1308    return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
1309
1310  for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
1311       DC = DC->getParent()) {
1312    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
1313      if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
1314        return getStorageClass() != SC_Static &&
1315               !getAttr<OverloadableAttr>();
1316
1317      break;
1318    }
1319
1320    if (DC->isRecord())
1321      break;
1322  }
1323
1324  return isMain();
1325}
1326
1327bool FunctionDecl::isGlobal() const {
1328  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1329    return Method->isStatic();
1330
1331  if (getStorageClass() == SC_Static)
1332    return false;
1333
1334  for (const DeclContext *DC = getDeclContext();
1335       DC->isNamespace();
1336       DC = DC->getParent()) {
1337    if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1338      if (!Namespace->getDeclName())
1339        return false;
1340      break;
1341    }
1342  }
1343
1344  return true;
1345}
1346
1347void
1348FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1349  redeclarable_base::setPreviousDeclaration(PrevDecl);
1350
1351  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1352    FunctionTemplateDecl *PrevFunTmpl
1353      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1354    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1355    FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1356  }
1357
1358  if (PrevDecl->IsInline)
1359    IsInline = true;
1360}
1361
1362const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1363  return getFirstDeclaration();
1364}
1365
1366FunctionDecl *FunctionDecl::getCanonicalDecl() {
1367  return getFirstDeclaration();
1368}
1369
1370void FunctionDecl::setStorageClass(StorageClass SC) {
1371  assert(isLegalForFunction(SC));
1372  if (getStorageClass() != SC)
1373    ClearLinkageCache();
1374
1375  SClass = SC;
1376}
1377
1378/// \brief Returns a value indicating whether this function
1379/// corresponds to a builtin function.
1380///
1381/// The function corresponds to a built-in function if it is
1382/// declared at translation scope or within an extern "C" block and
1383/// its name matches with the name of a builtin. The returned value
1384/// will be 0 for functions that do not correspond to a builtin, a
1385/// value of type \c Builtin::ID if in the target-independent range
1386/// \c [1,Builtin::First), or a target-specific builtin value.
1387unsigned FunctionDecl::getBuiltinID() const {
1388  ASTContext &Context = getASTContext();
1389  if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1390    return 0;
1391
1392  unsigned BuiltinID = getIdentifier()->getBuiltinID();
1393  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1394    return BuiltinID;
1395
1396  // This function has the name of a known C library
1397  // function. Determine whether it actually refers to the C library
1398  // function or whether it just has the same name.
1399
1400  // If this is a static function, it's not a builtin.
1401  if (getStorageClass() == SC_Static)
1402    return 0;
1403
1404  // If this function is at translation-unit scope and we're not in
1405  // C++, it refers to the C library function.
1406  if (!Context.getLangOptions().CPlusPlus &&
1407      getDeclContext()->isTranslationUnit())
1408    return BuiltinID;
1409
1410  // If the function is in an extern "C" linkage specification and is
1411  // not marked "overloadable", it's the real function.
1412  if (isa<LinkageSpecDecl>(getDeclContext()) &&
1413      cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1414        == LinkageSpecDecl::lang_c &&
1415      !getAttr<OverloadableAttr>())
1416    return BuiltinID;
1417
1418  // Not a builtin
1419  return 0;
1420}
1421
1422
1423/// getNumParams - Return the number of parameters this function must have
1424/// based on its FunctionType.  This is the length of the ParamInfo array
1425/// after it has been created.
1426unsigned FunctionDecl::getNumParams() const {
1427  const FunctionType *FT = getType()->getAs<FunctionType>();
1428  if (isa<FunctionNoProtoType>(FT))
1429    return 0;
1430  return cast<FunctionProtoType>(FT)->getNumArgs();
1431
1432}
1433
1434void FunctionDecl::setParams(ASTContext &C,
1435                             ParmVarDecl **NewParamInfo, unsigned NumParams) {
1436  assert(ParamInfo == 0 && "Already has param info!");
1437  assert(NumParams == getNumParams() && "Parameter count mismatch!");
1438
1439  // Zero params -> null pointer.
1440  if (NumParams) {
1441    void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams);
1442    ParamInfo = new (Mem) ParmVarDecl*[NumParams];
1443    memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
1444
1445    // Update source range. The check below allows us to set EndRangeLoc before
1446    // setting the parameters.
1447    if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation())
1448      EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd();
1449  }
1450}
1451
1452/// getMinRequiredArguments - Returns the minimum number of arguments
1453/// needed to call this function. This may be fewer than the number of
1454/// function parameters, if some of the parameters have default
1455/// arguments (in C++) or the last parameter is a parameter pack.
1456unsigned FunctionDecl::getMinRequiredArguments() const {
1457  if (!getASTContext().getLangOptions().CPlusPlus)
1458    return getNumParams();
1459
1460  unsigned NumRequiredArgs = getNumParams();
1461
1462  // If the last parameter is a parameter pack, we don't need an argument for
1463  // it.
1464  if (NumRequiredArgs > 0 &&
1465      getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1466    --NumRequiredArgs;
1467
1468  // If this parameter has a default argument, we don't need an argument for
1469  // it.
1470  while (NumRequiredArgs > 0 &&
1471         getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1472    --NumRequiredArgs;
1473
1474  // We might have parameter packs before the end. These can't be deduced,
1475  // but they can still handle multiple arguments.
1476  unsigned ArgIdx = NumRequiredArgs;
1477  while (ArgIdx > 0) {
1478    if (getParamDecl(ArgIdx - 1)->isParameterPack())
1479      NumRequiredArgs = ArgIdx;
1480
1481    --ArgIdx;
1482  }
1483
1484  return NumRequiredArgs;
1485}
1486
1487bool FunctionDecl::isInlined() const {
1488  if (IsInline)
1489    return true;
1490
1491  if (isa<CXXMethodDecl>(this)) {
1492    if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1493      return true;
1494  }
1495
1496  switch (getTemplateSpecializationKind()) {
1497  case TSK_Undeclared:
1498  case TSK_ExplicitSpecialization:
1499    return false;
1500
1501  case TSK_ImplicitInstantiation:
1502  case TSK_ExplicitInstantiationDeclaration:
1503  case TSK_ExplicitInstantiationDefinition:
1504    // Handle below.
1505    break;
1506  }
1507
1508  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1509  bool HasPattern = false;
1510  if (PatternDecl)
1511    HasPattern = PatternDecl->hasBody(PatternDecl);
1512
1513  if (HasPattern && PatternDecl)
1514    return PatternDecl->isInlined();
1515
1516  return false;
1517}
1518
1519/// \brief For an inline function definition in C or C++, determine whether the
1520/// definition will be externally visible.
1521///
1522/// Inline function definitions are always available for inlining optimizations.
1523/// However, depending on the language dialect, declaration specifiers, and
1524/// attributes, the definition of an inline function may or may not be
1525/// "externally" visible to other translation units in the program.
1526///
1527/// In C99, inline definitions are not externally visible by default. However,
1528/// if even one of the global-scope declarations is marked "extern inline", the
1529/// inline definition becomes externally visible (C99 6.7.4p6).
1530///
1531/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1532/// definition, we use the GNU semantics for inline, which are nearly the
1533/// opposite of C99 semantics. In particular, "inline" by itself will create
1534/// an externally visible symbol, but "extern inline" will not create an
1535/// externally visible symbol.
1536bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
1537  assert(isThisDeclarationADefinition() && "Must have the function definition");
1538  assert(isInlined() && "Function must be inline");
1539  ASTContext &Context = getASTContext();
1540
1541  if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) {
1542    // If it's not the case that both 'inline' and 'extern' are
1543    // specified on the definition, then this inline definition is
1544    // externally visible.
1545    if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1546      return true;
1547
1548    // If any declaration is 'inline' but not 'extern', then this definition
1549    // is externally visible.
1550    for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1551         Redecl != RedeclEnd;
1552         ++Redecl) {
1553      if (Redecl->isInlineSpecified() &&
1554          Redecl->getStorageClassAsWritten() != SC_Extern)
1555        return true;
1556    }
1557
1558    return false;
1559  }
1560
1561  // C99 6.7.4p6:
1562  //   [...] If all of the file scope declarations for a function in a
1563  //   translation unit include the inline function specifier without extern,
1564  //   then the definition in that translation unit is an inline definition.
1565  for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1566       Redecl != RedeclEnd;
1567       ++Redecl) {
1568    // Only consider file-scope declarations in this test.
1569    if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1570      continue;
1571
1572    if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1573      return true; // Not an inline definition
1574  }
1575
1576  // C99 6.7.4p6:
1577  //   An inline definition does not provide an external definition for the
1578  //   function, and does not forbid an external definition in another
1579  //   translation unit.
1580  return false;
1581}
1582
1583/// getOverloadedOperator - Which C++ overloaded operator this
1584/// function represents, if any.
1585OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
1586  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1587    return getDeclName().getCXXOverloadedOperator();
1588  else
1589    return OO_None;
1590}
1591
1592/// getLiteralIdentifier - The literal suffix identifier this function
1593/// represents, if any.
1594const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1595  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1596    return getDeclName().getCXXLiteralIdentifier();
1597  else
1598    return 0;
1599}
1600
1601FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1602  if (TemplateOrSpecialization.isNull())
1603    return TK_NonTemplate;
1604  if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
1605    return TK_FunctionTemplate;
1606  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
1607    return TK_MemberSpecialization;
1608  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
1609    return TK_FunctionTemplateSpecialization;
1610  if (TemplateOrSpecialization.is
1611                               <DependentFunctionTemplateSpecializationInfo*>())
1612    return TK_DependentFunctionTemplateSpecialization;
1613
1614  assert(false && "Did we miss a TemplateOrSpecialization type?");
1615  return TK_NonTemplate;
1616}
1617
1618FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
1619  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
1620    return cast<FunctionDecl>(Info->getInstantiatedFrom());
1621
1622  return 0;
1623}
1624
1625MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
1626  return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1627}
1628
1629void
1630FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
1631                                               FunctionDecl *FD,
1632                                               TemplateSpecializationKind TSK) {
1633  assert(TemplateOrSpecialization.isNull() &&
1634         "Member function is already a specialization");
1635  MemberSpecializationInfo *Info
1636    = new (C) MemberSpecializationInfo(FD, TSK);
1637  TemplateOrSpecialization = Info;
1638}
1639
1640bool FunctionDecl::isImplicitlyInstantiable() const {
1641  // If the function is invalid, it can't be implicitly instantiated.
1642  if (isInvalidDecl())
1643    return false;
1644
1645  switch (getTemplateSpecializationKind()) {
1646  case TSK_Undeclared:
1647  case TSK_ExplicitSpecialization:
1648  case TSK_ExplicitInstantiationDefinition:
1649    return false;
1650
1651  case TSK_ImplicitInstantiation:
1652    return true;
1653
1654  case TSK_ExplicitInstantiationDeclaration:
1655    // Handled below.
1656    break;
1657  }
1658
1659  // Find the actual template from which we will instantiate.
1660  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1661  bool HasPattern = false;
1662  if (PatternDecl)
1663    HasPattern = PatternDecl->hasBody(PatternDecl);
1664
1665  // C++0x [temp.explicit]p9:
1666  //   Except for inline functions, other explicit instantiation declarations
1667  //   have the effect of suppressing the implicit instantiation of the entity
1668  //   to which they refer.
1669  if (!HasPattern || !PatternDecl)
1670    return true;
1671
1672  return PatternDecl->isInlined();
1673}
1674
1675FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
1676  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
1677    while (Primary->getInstantiatedFromMemberTemplate()) {
1678      // If we have hit a point where the user provided a specialization of
1679      // this template, we're done looking.
1680      if (Primary->isMemberSpecialization())
1681        break;
1682
1683      Primary = Primary->getInstantiatedFromMemberTemplate();
1684    }
1685
1686    return Primary->getTemplatedDecl();
1687  }
1688
1689  return getInstantiatedFromMemberFunction();
1690}
1691
1692FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
1693  if (FunctionTemplateSpecializationInfo *Info
1694        = TemplateOrSpecialization
1695            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1696    return Info->Template.getPointer();
1697  }
1698  return 0;
1699}
1700
1701const TemplateArgumentList *
1702FunctionDecl::getTemplateSpecializationArgs() const {
1703  if (FunctionTemplateSpecializationInfo *Info
1704        = TemplateOrSpecialization
1705            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1706    return Info->TemplateArguments;
1707  }
1708  return 0;
1709}
1710
1711const TemplateArgumentListInfo *
1712FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
1713  if (FunctionTemplateSpecializationInfo *Info
1714        = TemplateOrSpecialization
1715            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1716    return Info->TemplateArgumentsAsWritten;
1717  }
1718  return 0;
1719}
1720
1721void
1722FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
1723                                                FunctionTemplateDecl *Template,
1724                                     const TemplateArgumentList *TemplateArgs,
1725                                                void *InsertPos,
1726                                                TemplateSpecializationKind TSK,
1727                        const TemplateArgumentListInfo *TemplateArgsAsWritten,
1728                                          SourceLocation PointOfInstantiation) {
1729  assert(TSK != TSK_Undeclared &&
1730         "Must specify the type of function template specialization");
1731  FunctionTemplateSpecializationInfo *Info
1732    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1733  if (!Info)
1734    Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
1735                                                      TemplateArgs,
1736                                                      TemplateArgsAsWritten,
1737                                                      PointOfInstantiation);
1738  TemplateOrSpecialization = Info;
1739
1740  // Insert this function template specialization into the set of known
1741  // function template specializations.
1742  if (InsertPos)
1743    Template->getSpecializations().InsertNode(Info, InsertPos);
1744  else {
1745    // Try to insert the new node. If there is an existing node, leave it, the
1746    // set will contain the canonical decls while
1747    // FunctionTemplateDecl::findSpecialization will return
1748    // the most recent redeclarations.
1749    FunctionTemplateSpecializationInfo *Existing
1750      = Template->getSpecializations().GetOrInsertNode(Info);
1751    (void)Existing;
1752    assert((!Existing || Existing->Function->isCanonicalDecl()) &&
1753           "Set is supposed to only contain canonical decls");
1754  }
1755}
1756
1757void
1758FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
1759                                    const UnresolvedSetImpl &Templates,
1760                             const TemplateArgumentListInfo &TemplateArgs) {
1761  assert(TemplateOrSpecialization.isNull());
1762  size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
1763  Size += Templates.size() * sizeof(FunctionTemplateDecl*);
1764  Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
1765  void *Buffer = Context.Allocate(Size);
1766  DependentFunctionTemplateSpecializationInfo *Info =
1767    new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
1768                                                             TemplateArgs);
1769  TemplateOrSpecialization = Info;
1770}
1771
1772DependentFunctionTemplateSpecializationInfo::
1773DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
1774                                      const TemplateArgumentListInfo &TArgs)
1775  : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
1776
1777  d.NumTemplates = Ts.size();
1778  d.NumArgs = TArgs.size();
1779
1780  FunctionTemplateDecl **TsArray =
1781    const_cast<FunctionTemplateDecl**>(getTemplates());
1782  for (unsigned I = 0, E = Ts.size(); I != E; ++I)
1783    TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
1784
1785  TemplateArgumentLoc *ArgsArray =
1786    const_cast<TemplateArgumentLoc*>(getTemplateArgs());
1787  for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
1788    new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
1789}
1790
1791TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
1792  // For a function template specialization, query the specialization
1793  // information object.
1794  FunctionTemplateSpecializationInfo *FTSInfo
1795    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1796  if (FTSInfo)
1797    return FTSInfo->getTemplateSpecializationKind();
1798
1799  MemberSpecializationInfo *MSInfo
1800    = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1801  if (MSInfo)
1802    return MSInfo->getTemplateSpecializationKind();
1803
1804  return TSK_Undeclared;
1805}
1806
1807void
1808FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1809                                          SourceLocation PointOfInstantiation) {
1810  if (FunctionTemplateSpecializationInfo *FTSInfo
1811        = TemplateOrSpecialization.dyn_cast<
1812                                    FunctionTemplateSpecializationInfo*>()) {
1813    FTSInfo->setTemplateSpecializationKind(TSK);
1814    if (TSK != TSK_ExplicitSpecialization &&
1815        PointOfInstantiation.isValid() &&
1816        FTSInfo->getPointOfInstantiation().isInvalid())
1817      FTSInfo->setPointOfInstantiation(PointOfInstantiation);
1818  } else if (MemberSpecializationInfo *MSInfo
1819             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
1820    MSInfo->setTemplateSpecializationKind(TSK);
1821    if (TSK != TSK_ExplicitSpecialization &&
1822        PointOfInstantiation.isValid() &&
1823        MSInfo->getPointOfInstantiation().isInvalid())
1824      MSInfo->setPointOfInstantiation(PointOfInstantiation);
1825  } else
1826    assert(false && "Function cannot have a template specialization kind");
1827}
1828
1829SourceLocation FunctionDecl::getPointOfInstantiation() const {
1830  if (FunctionTemplateSpecializationInfo *FTSInfo
1831        = TemplateOrSpecialization.dyn_cast<
1832                                        FunctionTemplateSpecializationInfo*>())
1833    return FTSInfo->getPointOfInstantiation();
1834  else if (MemberSpecializationInfo *MSInfo
1835             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
1836    return MSInfo->getPointOfInstantiation();
1837
1838  return SourceLocation();
1839}
1840
1841bool FunctionDecl::isOutOfLine() const {
1842  if (Decl::isOutOfLine())
1843    return true;
1844
1845  // If this function was instantiated from a member function of a
1846  // class template, check whether that member function was defined out-of-line.
1847  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
1848    const FunctionDecl *Definition;
1849    if (FD->hasBody(Definition))
1850      return Definition->isOutOfLine();
1851  }
1852
1853  // If this function was instantiated from a function template,
1854  // check whether that function template was defined out-of-line.
1855  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
1856    const FunctionDecl *Definition;
1857    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
1858      return Definition->isOutOfLine();
1859  }
1860
1861  return false;
1862}
1863
1864//===----------------------------------------------------------------------===//
1865// FieldDecl Implementation
1866//===----------------------------------------------------------------------===//
1867
1868FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
1869                             SourceLocation L, IdentifierInfo *Id, QualType T,
1870                             TypeSourceInfo *TInfo, Expr *BW, bool Mutable) {
1871  return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable);
1872}
1873
1874bool FieldDecl::isAnonymousStructOrUnion() const {
1875  if (!isImplicit() || getDeclName())
1876    return false;
1877
1878  if (const RecordType *Record = getType()->getAs<RecordType>())
1879    return Record->getDecl()->isAnonymousStructOrUnion();
1880
1881  return false;
1882}
1883
1884unsigned FieldDecl::getFieldIndex() const {
1885  if (CachedFieldIndex) return CachedFieldIndex - 1;
1886
1887  unsigned index = 0;
1888  RecordDecl::field_iterator
1889    i = getParent()->field_begin(), e = getParent()->field_end();
1890  while (true) {
1891    assert(i != e && "failed to find field in parent!");
1892    if (*i == this)
1893      break;
1894
1895    ++i;
1896    ++index;
1897  }
1898
1899  CachedFieldIndex = index + 1;
1900  return index;
1901}
1902
1903//===----------------------------------------------------------------------===//
1904// TagDecl Implementation
1905//===----------------------------------------------------------------------===//
1906
1907SourceLocation TagDecl::getOuterLocStart() const {
1908  return getTemplateOrInnerLocStart(this);
1909}
1910
1911SourceRange TagDecl::getSourceRange() const {
1912  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
1913  return SourceRange(getOuterLocStart(), E);
1914}
1915
1916TagDecl* TagDecl::getCanonicalDecl() {
1917  return getFirstDeclaration();
1918}
1919
1920void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) {
1921  TypedefDeclOrQualifier = TDD;
1922  if (TypeForDecl)
1923    const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
1924  ClearLinkageCache();
1925}
1926
1927void TagDecl::startDefinition() {
1928  IsBeingDefined = true;
1929
1930  if (isa<CXXRecordDecl>(this)) {
1931    CXXRecordDecl *D = cast<CXXRecordDecl>(this);
1932    struct CXXRecordDecl::DefinitionData *Data =
1933      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
1934    for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
1935      cast<CXXRecordDecl>(*I)->DefinitionData = Data;
1936  }
1937}
1938
1939void TagDecl::completeDefinition() {
1940  assert((!isa<CXXRecordDecl>(this) ||
1941          cast<CXXRecordDecl>(this)->hasDefinition()) &&
1942         "definition completed but not started");
1943
1944  IsDefinition = true;
1945  IsBeingDefined = false;
1946
1947  if (ASTMutationListener *L = getASTMutationListener())
1948    L->CompletedTagDefinition(this);
1949}
1950
1951TagDecl* TagDecl::getDefinition() const {
1952  if (isDefinition())
1953    return const_cast<TagDecl *>(this);
1954  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
1955    return CXXRD->getDefinition();
1956
1957  for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
1958       R != REnd; ++R)
1959    if (R->isDefinition())
1960      return *R;
1961
1962  return 0;
1963}
1964
1965void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier,
1966                               SourceRange QualifierRange) {
1967  if (Qualifier) {
1968    // Make sure the extended qualifier info is allocated.
1969    if (!hasExtInfo())
1970      TypedefDeclOrQualifier = new (getASTContext()) ExtInfo;
1971    // Set qualifier info.
1972    getExtInfo()->NNS = Qualifier;
1973    getExtInfo()->NNSRange = QualifierRange;
1974  }
1975  else {
1976    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1977    assert(QualifierRange.isInvalid());
1978    if (hasExtInfo()) {
1979      getASTContext().Deallocate(getExtInfo());
1980      TypedefDeclOrQualifier = (TypedefDecl*) 0;
1981    }
1982  }
1983}
1984
1985//===----------------------------------------------------------------------===//
1986// EnumDecl Implementation
1987//===----------------------------------------------------------------------===//
1988
1989EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
1990                           IdentifierInfo *Id, SourceLocation TKL,
1991                           EnumDecl *PrevDecl, bool IsScoped,
1992                           bool IsScopedUsingClassTag, bool IsFixed) {
1993  EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL,
1994                                    IsScoped, IsScopedUsingClassTag, IsFixed);
1995  C.getTypeDeclType(Enum, PrevDecl);
1996  return Enum;
1997}
1998
1999EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
2000  return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation(),
2001                          false, false, false);
2002}
2003
2004void EnumDecl::completeDefinition(QualType NewType,
2005                                  QualType NewPromotionType,
2006                                  unsigned NumPositiveBits,
2007                                  unsigned NumNegativeBits) {
2008  assert(!isDefinition() && "Cannot redefine enums!");
2009  if (!IntegerType)
2010    IntegerType = NewType.getTypePtr();
2011  PromotionType = NewPromotionType;
2012  setNumPositiveBits(NumPositiveBits);
2013  setNumNegativeBits(NumNegativeBits);
2014  TagDecl::completeDefinition();
2015}
2016
2017//===----------------------------------------------------------------------===//
2018// RecordDecl Implementation
2019//===----------------------------------------------------------------------===//
2020
2021RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
2022                       IdentifierInfo *Id, RecordDecl *PrevDecl,
2023                       SourceLocation TKL)
2024  : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) {
2025  HasFlexibleArrayMember = false;
2026  AnonymousStructOrUnion = false;
2027  HasObjectMember = false;
2028  LoadedFieldsFromExternalStorage = false;
2029  assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
2030}
2031
2032RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2033                               SourceLocation L, IdentifierInfo *Id,
2034                               SourceLocation TKL, RecordDecl* PrevDecl) {
2035
2036  RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL);
2037  C.getTypeDeclType(R, PrevDecl);
2038  return R;
2039}
2040
2041RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
2042  return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0,
2043                            SourceLocation());
2044}
2045
2046bool RecordDecl::isInjectedClassName() const {
2047  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
2048    cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2049}
2050
2051RecordDecl::field_iterator RecordDecl::field_begin() const {
2052  if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2053    LoadFieldsFromExternalStorage();
2054
2055  return field_iterator(decl_iterator(FirstDecl));
2056}
2057
2058/// completeDefinition - Notes that the definition of this type is now
2059/// complete.
2060void RecordDecl::completeDefinition() {
2061  assert(!isDefinition() && "Cannot redefine record!");
2062  TagDecl::completeDefinition();
2063}
2064
2065void RecordDecl::LoadFieldsFromExternalStorage() const {
2066  ExternalASTSource *Source = getASTContext().getExternalSource();
2067  assert(hasExternalLexicalStorage() && Source && "No external storage?");
2068
2069  // Notify that we have a RecordDecl doing some initialization.
2070  ExternalASTSource::Deserializing TheFields(Source);
2071
2072  llvm::SmallVector<Decl*, 64> Decls;
2073  if (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls))
2074    return;
2075
2076#ifndef NDEBUG
2077  // Check that all decls we got were FieldDecls.
2078  for (unsigned i=0, e=Decls.size(); i != e; ++i)
2079    assert(isa<FieldDecl>(Decls[i]));
2080#endif
2081
2082  LoadedFieldsFromExternalStorage = true;
2083
2084  if (Decls.empty())
2085    return;
2086
2087  llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
2088}
2089
2090//===----------------------------------------------------------------------===//
2091// BlockDecl Implementation
2092//===----------------------------------------------------------------------===//
2093
2094void BlockDecl::setParams(ParmVarDecl **NewParamInfo,
2095                          unsigned NParms) {
2096  assert(ParamInfo == 0 && "Already has param info!");
2097
2098  // Zero params -> null pointer.
2099  if (NParms) {
2100    NumParams = NParms;
2101    void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams);
2102    ParamInfo = new (Mem) ParmVarDecl*[NumParams];
2103    memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
2104  }
2105}
2106
2107void BlockDecl::setCapturedDecls(ASTContext &Context,
2108                                 VarDecl * const *begin,
2109                                 VarDecl * const *end,
2110                                 bool capturesCXXThis) {
2111  CapturesCXXThis = capturesCXXThis;
2112
2113  if (begin == end) {
2114    NumCapturedDecls = 0;
2115    CapturedDecls = 0;
2116    return;
2117  }
2118
2119  NumCapturedDecls = end - begin;
2120  CapturedDecls = new (Context) VarDecl*[NumCapturedDecls];
2121  memcpy(CapturedDecls, begin, NumCapturedDecls * sizeof(VarDecl*));
2122}
2123
2124SourceRange BlockDecl::getSourceRange() const {
2125  return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2126}
2127
2128//===----------------------------------------------------------------------===//
2129// Other Decl Allocation/Deallocation Method Implementations
2130//===----------------------------------------------------------------------===//
2131
2132TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2133  return new (C) TranslationUnitDecl(C);
2134}
2135
2136NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2137                                     SourceLocation L, IdentifierInfo *Id) {
2138  return new (C) NamespaceDecl(DC, L, Id);
2139}
2140
2141NamespaceDecl *NamespaceDecl::getNextNamespace() {
2142  return dyn_cast_or_null<NamespaceDecl>(
2143                       NextNamespace.get(getASTContext().getExternalSource()));
2144}
2145
2146ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2147    SourceLocation L, IdentifierInfo *Id, QualType T) {
2148  return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T);
2149}
2150
2151FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2152                                   const DeclarationNameInfo &NameInfo,
2153                                   QualType T, TypeSourceInfo *TInfo,
2154                                   StorageClass S, StorageClass SCAsWritten,
2155                                   bool isInlineSpecified,
2156                                   bool hasWrittenPrototype) {
2157  FunctionDecl *New = new (C) FunctionDecl(Function, DC, NameInfo, T, TInfo,
2158                                           S, SCAsWritten, isInlineSpecified);
2159  New->HasWrittenPrototype = hasWrittenPrototype;
2160  return New;
2161}
2162
2163BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2164  return new (C) BlockDecl(DC, L);
2165}
2166
2167EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2168                                           SourceLocation L,
2169                                           IdentifierInfo *Id, QualType T,
2170                                           Expr *E, const llvm::APSInt &V) {
2171  return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2172}
2173
2174IndirectFieldDecl *
2175IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2176                          IdentifierInfo *Id, QualType T, NamedDecl **CH,
2177                          unsigned CHS) {
2178  return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2179}
2180
2181SourceRange EnumConstantDecl::getSourceRange() const {
2182  SourceLocation End = getLocation();
2183  if (Init)
2184    End = Init->getLocEnd();
2185  return SourceRange(getLocation(), End);
2186}
2187
2188TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2189                                 SourceLocation L, IdentifierInfo *Id,
2190                                 TypeSourceInfo *TInfo) {
2191  return new (C) TypedefDecl(DC, L, Id, TInfo);
2192}
2193
2194FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
2195                                           SourceLocation L,
2196                                           StringLiteral *Str) {
2197  return new (C) FileScopeAsmDecl(DC, L, Str);
2198}
2199