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