SemaTemplate.cpp revision a03478231363c67ea0e1f4bc1bc708e064040e56
1b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//
3b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//                     The LLVM Compiler Infrastructure
450294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho//
5b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru// This file is distributed under the University of Illinois Open Source
6b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru// License. See LICENSE.TXT for details.
7b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//===----------------------------------------------------------------------===/
8b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//
9b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//  This file implements semantic analysis for C++ templates.
10b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru//===----------------------------------------------------------------------===/
11b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
12b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/SemaInternal.h"
13b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/Lookup.h"
14b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/Scope.h"
15b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/Template.h"
16b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/TemplateDeduction.h"
17b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "TreeTransform.h"
18b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/ASTContext.h"
19b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/Expr.h"
20b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/ExprCXX.h"
21b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/DeclFriend.h"
22b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/DeclTemplate.h"
23b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/RecursiveASTVisitor.h"
24b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/AST/TypeVisitor.h"
25b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/DeclSpec.h"
26b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Sema/ParsedTemplate.h"
27b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Basic/LangOptions.h"
28b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "clang/Basic/PartialDiagnostic.h"
29b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru#include "llvm/ADT/StringExtras.h"
30b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queruusing namespace clang;
31b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queruusing namespace sema;
32b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
33b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru// Exported for use by Parser.
34b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSourceRange
35b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queruclang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                              unsigned N) {
37b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!N) return SourceRange();
38b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
40b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
41b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// \brief Determine whether the declaration found is acceptable as the name
42b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// of a template and, if so, return that template declaration. Otherwise,
43b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// returns NULL.
44b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Querustatic NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           NamedDecl *Orig) {
46b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  NamedDecl *D = Orig->getUnderlyingDecl();
47b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
48b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (isa<TemplateDecl>(D))
49b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return Orig;
50b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
51b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // C++ [temp.local]p1:
53b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   Like normal (non-template) classes, class templates have an
54b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   injected-class-name (Clause 9). The injected-class-name
55b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   can be used with or without a template-argument-list. When
56b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   it is used without a template-argument-list, it is
57b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   equivalent to the injected-class-name followed by the
58b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   template-parameters of the class template enclosed in
59b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   <>. When it is used with a template-argument-list, it
60b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   refers to the specified class template specialization,
61b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   which could be the current specialization or another
62b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   specialization.
63b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (Record->isInjectedClassName()) {
64b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Record = cast<CXXRecordDecl>(Record->getDeclContext());
65b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      if (Record->getDescribedClassTemplate())
66b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        return Record->getDescribedClassTemplate();
67b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
68b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      if (ClassTemplateSpecializationDecl *Spec
69b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        return Spec->getSpecializedTemplate();
71b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
72b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
73b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return 0;
74b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
75b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
76b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return 0;
77b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
78b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
79b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Querustatic void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
80b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // The set of class templates we've already seen.
81b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
82b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  LookupResult::Filter filter = R.makeFilter();
83b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  while (filter.hasNext()) {
84b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    NamedDecl *Orig = filter.next();
85b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
86b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (!Repl)
87b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      filter.erase();
88b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    else if (Repl != Orig) {
89b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
90b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // C++ [temp.local]p3:
91b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   A lookup that finds an injected-class-name (10.2) can result in an
92b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   ambiguity in certain cases (for example, if it is found in more than
93b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   one base class). If all of the injected-class-names that are found
94b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   refer to specializations of the same class template, and if the name
95b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   is followed by a template-argument-list, the reference refers to the
96b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   class template itself and not a specialization thereof, and is not
97b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   ambiguous.
98b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //
99b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // FIXME: Will we eventually have to do the same for alias templates?
100b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        if (!ClassTemplates.insert(ClassTmpl)) {
102b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          filter.erase();
103b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          continue;
104b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        }
105b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
106b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // FIXME: we promote access to public here as a workaround to
107b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // the fact that LookupResult doesn't let us remember that we
108b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // found this template through a particular injected class name,
109b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // which means we end up doing nasty things to the invariants.
110b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // Pretending that access is public is *much* safer.
111b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      filter.replace(Repl, AS_public);
112b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
113b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
114b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  filter.done();
115b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
116b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
117b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruTemplateNameKind Sema::isTemplateName(Scope *S,
118b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      CXXScopeSpec &SS,
119b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      bool hasTemplateKeyword,
120b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      UnqualifiedId &Name,
121b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      ParsedType ObjectTypePtr,
122b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      bool EnteringContext,
123b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      TemplateTy &TemplateResult,
124b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      bool &MemberOfUnknownSpecialization) {
125b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(getLangOptions().CPlusPlus && "No template names in C!");
126b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
127b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  DeclarationName TName;
128b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  MemberOfUnknownSpecialization = false;
129b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
130b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  switch (Name.getKind()) {
131b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  case UnqualifiedId::IK_Identifier:
132b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TName = DeclarationName(Name.Identifier);
133b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    break;
134b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
135b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  case UnqualifiedId::IK_OperatorFunctionId:
136b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TName = Context.DeclarationNames.getCXXOperatorName(
137b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                              Name.OperatorFunctionId.Operator);
138b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    break;
139b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
140b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  case UnqualifiedId::IK_LiteralOperatorId:
141b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    break;
143b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
144b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  default:
145b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return TNK_Non_template;
146b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
147b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
148b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  QualType ObjectType = ObjectTypePtr.get();
149b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
150b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                 LookupOrdinaryName);
152b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                     MemberOfUnknownSpecialization);
154b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (R.empty()) return TNK_Non_template;
155b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (R.isAmbiguous()) {
156b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Suppress diagnostics;  we'll redo this lookup later.
157b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    R.suppressDiagnostics();
158b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
159b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // FIXME: we might have ambiguous templates, in which case we
16050294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho    // should at least parse them properly!
16150294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho    return TNK_Non_template;
16250294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho  }
163b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
164b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TemplateName Template;
165b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TemplateNameKind TemplateKind;
16650294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho
167b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  unsigned ResultCount = R.end() - R.begin();
168b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (ResultCount > 1) {
169b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // We assume that we'll preserve the qualifier from a function
170b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // template name in other ways.
171b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TemplateKind = TNK_Function_template;
173b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
174b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // We'll do this lookup again later.
175b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    R.suppressDiagnostics();
176b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  } else {
177b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
179b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (SS.isSet() && !SS.isInvalid()) {
180b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      NestedNameSpecifier *Qualifier
181b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
182b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Template = Context.getQualifiedTemplateName(Qualifier,
183b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                  hasTemplateKeyword, TD);
184b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    } else {
18550294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho      Template = TemplateName(TD);
186b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
187b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
188b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (isa<FunctionTemplateDecl>(TD)) {
189b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      TemplateKind = TNK_Function_template;
190b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
191b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // We'll do this lookup again later.
192b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      R.suppressDiagnostics();
193b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    } else {
194b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      TemplateKind = TNK_Type_template;
196b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
197b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
198b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
199b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TemplateResult = TemplateTy::make(Template);
200b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return TemplateKind;
201b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
202b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
203b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Querubool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       SourceLocation IILoc,
205b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       Scope *S,
206b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       const CXXScopeSpec *SS,
207b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       TemplateTy &SuggestedTemplate,
208b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       TemplateNameKind &SuggestedKind) {
209b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // We can't recover unless there's a dependent scope specifier preceding the
210b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // template name.
211b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // FIXME: Typo correction?
212b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
21350294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho      computeDeclContext(*SS))
214b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return false;
215b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
216b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // The code is missing a 'template' keyword prior to the dependent template
217b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // name.
218b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  Diag(IILoc, diag::err_template_kw_missing)
22050294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho    << Qualifier << II.getName()
221b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    << FixItHint::CreateInsertion(IILoc, "template ");
222b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  SuggestedTemplate
223b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  SuggestedKind = TNK_Dependent_template_name;
225b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return true;
226b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
227b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
228b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queruvoid Sema::LookupTemplateName(LookupResult &Found,
229b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                              Scope *S, CXXScopeSpec &SS,
230b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                              QualType ObjectType,
231b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                              bool EnteringContext,
232b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                              bool &MemberOfUnknownSpecialization) {
233b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Determine where to perform name lookup
234b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  MemberOfUnknownSpecialization = false;
235b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  DeclContext *LookupCtx = 0;
236b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool isDependent = false;
237b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!ObjectType.isNull()) {
238b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // This nested-name-specifier occurs in a member access expression, e.g.,
239b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // x->B::f, and we are looking into the type of the object.
240b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    LookupCtx = computeDeclContext(ObjectType);
242b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    isDependent = ObjectType->isDependentType();
243b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    assert((isDependent || !ObjectType->isIncompleteType()) &&
244b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru           "Caller should have completed object type");
245b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  } else if (SS.isSet()) {
246b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // This nested-name-specifier occurs after another nested-name-specifier,
247b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // so long into the context associated with the prior nested-name-specifier.
248b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    LookupCtx = computeDeclContext(SS, EnteringContext);
249b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    isDependent = isDependentScopeSpecifier(SS);
250b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
251b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // The declaration context must be complete.
252b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
253b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return;
254b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
255b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
256b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool ObjectTypeSearchedInScope = false;
257b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (LookupCtx) {
258b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Perform "qualified" name lookup into the declaration context we
259b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // computed, which is either the type of the base of a member access
260b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // expression or the declaration context associated with a prior
261b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // nested-name-specifier.
262b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    LookupQualifiedName(Found, LookupCtx);
263b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
264b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (!ObjectType.isNull() && Found.empty()) {
265b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // C++ [basic.lookup.classref]p1:
266b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   In a class member access expression (5.2.5), if the . or -> token is
267b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   immediately followed by an identifier followed by a <, the
268b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   identifier must be looked up to determine whether the < is the
269b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   beginning of a template argument list (14.2) or a less-than operator.
270b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   The identifier is first looked up in the class of the object
271b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   expression. If the identifier is not found, it is then looked up in
272b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   the context of the entire postfix-expression and shall name a class
273b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   or function template.
274b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      if (S) LookupName(Found, S);
275b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      ObjectTypeSearchedInScope = true;
276b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
277b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  } else if (isDependent && (!S || ObjectType.isNull())) {
278b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // We cannot look into a dependent object type or nested nme
279b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // specifier.
280b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    MemberOfUnknownSpecialization = true;
281b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return;
282b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  } else {
283b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Perform unqualified name lookup in the current scope.
284b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    LookupName(Found, S);
285b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
286b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
287b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Found.empty() && !isDependent) {
288b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // If we did not find any names, attempt to correct any typos.
289b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    DeclarationName Name = Found.getLookupName();
290b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
291b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                false, CTC_CXXCasts)) {
292b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      FilterAcceptableTemplateNames(Context, Found);
293b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      if (!Found.empty()) {
294b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        if (LookupCtx)
295b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            << Name << LookupCtx << Found.getLookupName() << SS.getRange()
297b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            << FixItHint::CreateReplacement(Found.getNameLoc(),
298b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                          Found.getLookupName().getAsString());
299b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        else
300b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            << Name << Found.getLookupName()
302b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            << FixItHint::CreateReplacement(Found.getNameLoc(),
303b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                          Found.getLookupName().getAsString());
304b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          Diag(Template->getLocation(), diag::note_previous_decl)
306b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            << Template->getDeclName();
307b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      }
308b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    } else {
309b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Found.clear();
310b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Found.setLookupName(Name);
311b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
312b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
313b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
314b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  FilterAcceptableTemplateNames(Context, Found);
315b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Found.empty()) {
316b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (isDependent)
317b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      MemberOfUnknownSpecialization = true;
318b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return;
319b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
320b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
321b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // C++ [basic.lookup.classref]p1:
323b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   [...] If the lookup in the class of the object expression finds a
324b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   template, the name is also looked up in the context of the entire
325b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //   postfix-expression and [...]
326b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //
327b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                            LookupOrdinaryName);
329b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    LookupName(FoundOuter, S);
330b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    FilterAcceptableTemplateNames(Context, FoundOuter);
331b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
332b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (FoundOuter.empty()) {
333b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   - if the name is not found, the name found in the class of the
334b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //     object expression is used, otherwise
335b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   - if the name is found in the context of the entire
337b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //     postfix-expression and does not name a class template, the name
338b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //     found in the class of the object expression is used, otherwise
339b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    } else if (!Found.isSuppressingDiagnostics()) {
340b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   - if the name found is a class template, it must refer to the same
341b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //     entity as the one found in the class of the object expression,
342b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //     otherwise the program is ill-formed.
343b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      if (!Found.isSingleResult() ||
344b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          Found.getFoundDecl()->getCanonicalDecl()
345b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru            != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        Diag(Found.getNameLoc(),
347b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru             diag::ext_nested_name_member_ref_lookup_ambiguous)
348b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          << Found.getLookupName()
349b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          << ObjectType;
350b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        Diag(Found.getRepresentativeDecl()->getLocation(),
351b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru             diag::note_ambig_member_ref_object_type)
352b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru          << ObjectType;
353b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        Diag(FoundOuter.getFoundDecl()->getLocation(),
354b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru             diag::note_ambig_member_ref_scope);
355b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
356b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        // Recover by taking the template that we found in the object
357b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        // expression's type.
358b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      }
359b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
360b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
361b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
362b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
363b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// ActOnDependentIdExpression - Handle a dependent id-expression that
364b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// was just parsed.  This is only possible with an explicit scope
365b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// specifier naming a dependent type.
366b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruExprResult
367b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
368b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 const DeclarationNameInfo &NameInfo,
369b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 bool isAddressOfOperand,
370b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                           const TemplateArgumentListInfo *TemplateArgs) {
371b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  NestedNameSpecifier *Qualifier
372b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
373b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
374b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  DeclContext *DC = getFunctionLevelDeclContext();
375b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
376b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!isAddressOfOperand &&
377b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      isa<CXXMethodDecl>(DC) &&
378b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      cast<CXXMethodDecl>(DC)->isInstance()) {
379b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
380b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
381b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Since the 'this' expression is synthesized, we don't need to
382b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // perform the double-lookup check.
383b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    NamedDecl *FirstQualifierInScope = 0;
384b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
385b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return Owned(CXXDependentScopeMemberExpr::Create(Context,
386b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     /*This*/ 0, ThisType,
387b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     /*IsArrow*/ true,
388b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     /*Op*/ SourceLocation(),
389b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     Qualifier, SS.getRange(),
390b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     FirstQualifierInScope,
391b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     NameInfo,
392b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                     TemplateArgs));
393b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
394b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
395b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
396b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
397b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
398b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruExprResult
399b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
400b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                const DeclarationNameInfo &NameInfo,
401b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                const TemplateArgumentListInfo *TemplateArgs) {
402b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return Owned(DependentScopeDeclRefExpr::Create(Context,
403b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru               static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                 SS.getRange(),
405b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                 NameInfo,
406b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                 TemplateArgs));
407b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
408b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
409b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// that the template parameter 'PrevDecl' is being shadowed by a new
411b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// declaration at location Loc. Returns true to indicate that this is
412b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// an error, and false otherwise.
413b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Querubool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
414b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
415b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
416b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Microsoft Visual C++ permits template parameters to be shadowed.
417b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (getLangOptions().Microsoft)
418b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return false;
419b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
420b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // C++ [temp.local]p4:
421b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   A template-parameter shall not be redeclared within its
422b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   scope (including nested scopes).
423b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  Diag(Loc, diag::err_template_param_shadow)
424b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    << cast<NamedDecl>(PrevDecl)->getDeclName();
425b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return true;
427b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
428b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
429b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
430b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// the parameter D to reference the templated declaration and return a pointer
431b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// to the template declaration. Otherwise, do nothing to D and return null.
432b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruTemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    D = Temp->getTemplatedDecl();
435b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return Temp;
436b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
437b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return 0;
438b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
439b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
440b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
441b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                             SourceLocation EllipsisLoc) const {
442b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(Kind == Template &&
443b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         "Only template template arguments can be pack expansions here");
444b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
445b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         "Template template argument pack expansion without packs");
446b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  ParsedTemplateArgument Result(*this);
447b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  Result.EllipsisLoc = EllipsisLoc;
448b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return Result;
449b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
450b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
451b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Querustatic TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
452b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                            const ParsedTemplateArgument &Arg) {
453b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
454b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  switch (Arg.getKind()) {
455b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  case ParsedTemplateArgument::Type: {
456b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TypeSourceInfo *DI;
457b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
458b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (!DI)
459b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
460b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return TemplateArgumentLoc(TemplateArgument(T), DI);
461b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
462b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
463b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  case ParsedTemplateArgument::NonType: {
464b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Expr *E = static_cast<Expr *>(Arg.getAsExpr());
465b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return TemplateArgumentLoc(TemplateArgument(E), E);
466b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
467b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
468b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  case ParsedTemplateArgument::Template: {
469b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TemplateName Template = Arg.getAsTemplate().get();
470b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return TemplateArgumentLoc(TemplateArgument(Template,
471b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                Arg.getEllipsisLoc().isValid()),
472b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               Arg.getScopeSpec().getRange(),
473b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               Arg.getLocation(),
474b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               Arg.getEllipsisLoc());
475b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
476b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
477b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
478b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  llvm_unreachable("Unhandled parsed template argument");
479b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return TemplateArgumentLoc();
480b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
481b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
482b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// \brief Translates template arguments as provided by the parser
483b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// into template arguments used by semantic analysis.
484b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queruvoid Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
485b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      TemplateArgumentListInfo &TemplateArgs) {
486b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
487b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru   TemplateArgs.addArgument(translateTemplateArgument(*this,
488b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                      TemplateArgsIn[I]));
489b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
490b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
491b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// ActOnTypeParameter - Called when a C++ template type parameter
492b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// (e.g., "typename T") has been parsed. Typename specifies whether
493b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// the keyword "typename" was used to declare the type parameter
494b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// (otherwise, "class" was used), and KeyLoc is the location of the
495b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// "class" or "typename" keyword. ParamName is the name of the
496b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// parameter (NULL indicates an unnamed template parameter) and
497b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// ParamName is the location of the parameter name (if any).
498b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// If the type parameter has a default argument, it will be added
499b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// later via ActOnTypeParameterDefault.
500b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
501b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               SourceLocation EllipsisLoc,
502b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               SourceLocation KeyLoc,
503b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               IdentifierInfo *ParamName,
504b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               SourceLocation ParamNameLoc,
505b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               unsigned Depth, unsigned Position,
506b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               SourceLocation EqualLoc,
507b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                               ParsedType DefaultArg) {
508b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(S->isTemplateParamScope() &&
509b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         "Template type parameter not in template parameter scope!");
510b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool Invalid = false;
511b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
512b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (ParamName) {
513b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
514b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           LookupOrdinaryName,
515b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           ForRedeclaration);
516b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (PrevDecl && PrevDecl->isTemplateParameter())
517b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
518b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                           PrevDecl);
519b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
520b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
521b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  SourceLocation Loc = ParamNameLoc;
522b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!ParamName)
523b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Loc = KeyLoc;
524b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
525b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TemplateTypeParmDecl *Param
526b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
527b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                   Loc, Depth, Position, ParamName, Typename,
528b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                   Ellipsis);
529b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Invalid)
530b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Param->setInvalidDecl();
531b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
532b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (ParamName) {
533b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Add the template parameter into the current scope.
534b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    S->AddDecl(Param);
535b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    IdResolver.AddDecl(Param);
536b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
537b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
538b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // C++0x [temp.param]p9:
539b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   A default template-argument may be specified for any kind of
540b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   template-parameter that is not a template parameter pack.
541b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (DefaultArg && Ellipsis) {
542b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
543b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    DefaultArg = ParsedType();
544b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
545b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
546b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Handle the default argument, if provided.
547b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (DefaultArg) {
548b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TypeSourceInfo *DefaultTInfo;
549b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    GetTypeFromParser(DefaultArg, &DefaultTInfo);
550b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
551b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    assert(DefaultTInfo && "expected source information for type");
552b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
553b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Check for unexpanded parameter packs.
554b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
555b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                        UPPC_DefaultArgument))
556b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return Param;
557b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
558b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Check the template argument itself.
559b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (CheckTemplateArgument(Param, DefaultTInfo)) {
560b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Param->setInvalidDecl();
561b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return Param;
562b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
563b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
564b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Param->setDefaultArgument(DefaultTInfo, false);
565b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
566b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
567b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return Param;
568b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
569b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
570b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// \brief Check that the type of a non-type template parameter is
571b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// well-formed.
572b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru///
573b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// \returns the (possibly-promoted) parameter type if valid;
574b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// otherwise, produces a diagnostic and returns a NULL type.
575b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruQualType
576b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
577b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // We don't allow variably-modified types as the type of non-type template
578b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // parameters.
579b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (T->isVariablyModifiedType()) {
580b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(Loc, diag::err_variably_modified_nontype_template_param)
581b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      << T;
582b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return QualType();
583b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
584b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
585b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // C++ [temp.param]p4:
586b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //
587b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // A non-type template-parameter shall have one of the following
588b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // (optionally cv-qualified) types:
589b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //
590b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //       -- integral or enumeration type,
591b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (T->isIntegralOrEnumerationType() ||
592b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   -- pointer to object or pointer to function,
593b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      T->isPointerType() ||
594b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   -- reference to object or reference to function,
595b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      T->isReferenceType() ||
596b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      //   -- pointer to member.
597b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      T->isMemberPointerType() ||
598b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // If T is a dependent type, we can't do the check now, so we
599b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      // assume that it is well-formed.
600b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      T->isDependentType())
601b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return T;
602b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // C++ [temp.param]p8:
603b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //
604b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   A non-type template-parameter of type "array of T" or
605b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   "function returning T" is adjusted to be of type "pointer to
606b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   T" or "pointer to function returning T", respectively.
607b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  else if (T->isArrayType())
608b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // FIXME: Keep the type prior to promotion?
609b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return Context.getArrayDecayedType(T);
610b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  else if (T->isFunctionType())
611b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // FIXME: Keep the type prior to promotion?
612b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return Context.getPointerType(T);
613b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
614b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  Diag(Loc, diag::err_template_nontype_parm_bad_type)
615b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    << T;
616b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
617b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return QualType();
618b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
619b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
620b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
621b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                          unsigned Depth,
622b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                          unsigned Position,
623b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                          SourceLocation EqualLoc,
624b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                          Expr *Default) {
625b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
626b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  QualType T = TInfo->getType();
627b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
628b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(S->isTemplateParamScope() &&
629b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         "Non-type template parameter not in template parameter scope!");
630b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool Invalid = false;
631b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
632b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  IdentifierInfo *ParamName = D.getIdentifier();
63350294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho  if (ParamName) {
634b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
635b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           LookupOrdinaryName,
636b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           ForRedeclaration);
637b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (PrevDecl && PrevDecl->isTemplateParameter())
638b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
639b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                                           PrevDecl);
640b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
641b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
642b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
643b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (T.isNull()) {
644b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    T = Context.IntTy; // Recover with an 'int' type.
645b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Invalid = true;
646b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
647b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
648b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool IsParameterPack = D.hasEllipsis();
649b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  NonTypeTemplateParmDecl *Param
650b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
651b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      D.getIdentifierLoc(),
652b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      Depth, Position, ParamName, T,
653b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                      IsParameterPack, TInfo);
654b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Invalid)
655b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Param->setInvalidDecl();
656b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
657b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (D.getIdentifier()) {
658b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Add the template parameter into the current scope.
659b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    S->AddDecl(Param);
660b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    IdResolver.AddDecl(Param);
661b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
662b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
66350294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho  // C++0x [temp.param]p9:
664b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   A default template-argument may be specified for any kind of
665b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   template-parameter that is not a template parameter pack.
666b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Default && IsParameterPack) {
667b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
668b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Default = 0;
669b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
670b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
671b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Check the well-formedness of the default template argument, if provided.
672b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Default) {
673b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Check for unexpanded parameter packs.
67450294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho    if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
675b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return Param;
676b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
677b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TemplateArgument Converted;
678b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
679b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Param->setInvalidDecl();
680b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return Param;
681b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
682b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
683b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Param->setDefaultArgument(Default, false);
684b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
685b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
686b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return Param;
687b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
688b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
689b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// ActOnTemplateTemplateParameter - Called when a C++ template template
690b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// parameter (e.g. T in template <template <typename> class T> class array)
691b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// has been parsed. S is the current scope.
692b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
693b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           SourceLocation TmpLoc,
694b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           TemplateParamsTy *Params,
695b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           SourceLocation EllipsisLoc,
696b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           IdentifierInfo *Name,
697b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           SourceLocation NameLoc,
698b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           unsigned Depth,
699b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           unsigned Position,
700b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           SourceLocation EqualLoc,
701b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                           ParsedTemplateArgument Default) {
702b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(S->isTemplateParamScope() &&
703b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         "Template template parameter not in template parameter scope!");
704b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
705b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Construct the parameter object.
706b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool IsParameterPack = EllipsisLoc.isValid();
707b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // FIXME: Pack-ness is dropped
708b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TemplateTemplateParmDecl *Param =
709b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
710b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                     NameLoc.isInvalid()? TmpLoc : NameLoc,
711b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                     Depth, Position, IsParameterPack,
712b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                     Name, Params);
713b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
714b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // If the template template parameter has a name, then link the identifier
715b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // into the scope and lookup mechanisms.
716b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Name) {
717b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    S->AddDecl(Param);
718b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    IdResolver.AddDecl(Param);
719b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
720b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
721b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (Params->size() == 0) {
722b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
723b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
724b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Param->setInvalidDecl();
725b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
726b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
727b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // C++0x [temp.param]p9:
728b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   A default template-argument may be specified for any kind of
729b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  //   template-parameter that is not a template parameter pack.
730b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (IsParameterPack && !Default.isInvalid()) {
731b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(EqualLoc, diag::err_template_param_pack_default_arg);
732b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Default = ParsedTemplateArgument();
733b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
734b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
735b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!Default.isInvalid()) {
736b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Check only that we have a template template argument. We don't want to
737b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // try to check well-formedness now, because our template template parameter
738b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // might have dependent types in its template parameters, which we wouldn't
739b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // be able to match now.
740b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    //
741b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // If none of the template template parameter's template arguments mention
742b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // other template parameters, we could actually perform more checking here.
743b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // However, it isn't worth doing.
744b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
745b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (DefaultArg.getArgument().getAsTemplate().isNull()) {
746b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
747b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru        << DefaultArg.getSourceRange();
748b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return Param;
749b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    }
750b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
751b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    // Check for unexpanded parameter packs.
752b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
753b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                        DefaultArg.getArgument().getAsTemplate(),
754b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                        UPPC_DefaultArgument))
755b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru      return Param;
756b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
757b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Param->setDefaultArgument(DefaultArg, false);
758b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
759b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
760b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return Param;
761b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
762b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
763b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// ActOnTemplateParameterList - Builds a TemplateParameterList that
764b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru/// contains the template parameters in Params/NumParams.
765b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSema::TemplateParamsTy *
766b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSema::ActOnTemplateParameterList(unsigned Depth,
767b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 SourceLocation ExportLoc,
768b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 SourceLocation TemplateLoc,
769b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 SourceLocation LAngleLoc,
770b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 Decl **Params, unsigned NumParams,
771b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                 SourceLocation RAngleLoc) {
772b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (ExportLoc.isValid())
773b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(ExportLoc, diag::warn_template_export_unsupported);
774b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
775b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
776b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       (NamedDecl**)Params, NumParams,
777b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                                       RAngleLoc);
778b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
779b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
780b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Querustatic void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
781b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (SS.isSet())
782b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
783b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                        SS.getRange());
784b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru}
785b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
786b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruDeclResult
787b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste QueruSema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
788b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                         SourceLocation KWLoc, CXXScopeSpec &SS,
789b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                         IdentifierInfo *Name, SourceLocation NameLoc,
790b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                         AttributeList *Attr,
791b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                         TemplateParameterList *TemplateParams,
792b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru                         AccessSpecifier AS) {
793b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(TemplateParams && TemplateParams->size() > 0 &&
794b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru         "No template parameters");
795b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(TUK != TUK_Reference && "Can only declare or define class templates");
796b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  bool Invalid = false;
797b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
798b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Check that we can declare a template here.
79950294ead5e5d23f5bbfed76e00e6b510bd41eee1claireho  if (CheckTemplateDeclScope(S, TemplateParams))
800b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return true;
801b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
802b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
803b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  assert(Kind != TTK_Enum && "can't build template of enumerated type");
804b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
805b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // There is no such thing as an unnamed class template.
806b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  if (!Name) {
807b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    Diag(KWLoc, diag::err_template_unnamed_class);
808b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru    return true;
809b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  }
810b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru
811b0ac937921a2c196d8b9da665135bf6ba01a1ccfJean-Baptiste Queru  // Find any previous declaration with this name.
812  DeclContext *SemanticContext;
813  LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
814                        ForRedeclaration);
815  if (SS.isNotEmpty() && !SS.isInvalid()) {
816    SemanticContext = computeDeclContext(SS, true);
817    if (!SemanticContext) {
818      // FIXME: Produce a reasonable diagnostic here
819      return true;
820    }
821
822    if (RequireCompleteDeclContext(SS, SemanticContext))
823      return true;
824
825    LookupQualifiedName(Previous, SemanticContext);
826  } else {
827    SemanticContext = CurContext;
828    LookupName(Previous, S);
829  }
830
831  if (Previous.isAmbiguous())
832    return true;
833
834  NamedDecl *PrevDecl = 0;
835  if (Previous.begin() != Previous.end())
836    PrevDecl = (*Previous.begin())->getUnderlyingDecl();
837
838  // If there is a previous declaration with the same name, check
839  // whether this is a valid redeclaration.
840  ClassTemplateDecl *PrevClassTemplate
841    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
842
843  // We may have found the injected-class-name of a class template,
844  // class template partial specialization, or class template specialization.
845  // In these cases, grab the template that is being defined or specialized.
846  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
847      cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
848    PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
849    PrevClassTemplate
850      = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
851    if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
852      PrevClassTemplate
853        = cast<ClassTemplateSpecializationDecl>(PrevDecl)
854            ->getSpecializedTemplate();
855    }
856  }
857
858  if (TUK == TUK_Friend) {
859    // C++ [namespace.memdef]p3:
860    //   [...] When looking for a prior declaration of a class or a function
861    //   declared as a friend, and when the name of the friend class or
862    //   function is neither a qualified name nor a template-id, scopes outside
863    //   the innermost enclosing namespace scope are not considered.
864    if (!SS.isSet()) {
865      DeclContext *OutermostContext = CurContext;
866      while (!OutermostContext->isFileContext())
867        OutermostContext = OutermostContext->getLookupParent();
868
869      if (PrevDecl &&
870          (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
871           OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
872        SemanticContext = PrevDecl->getDeclContext();
873      } else {
874        // Declarations in outer scopes don't matter. However, the outermost
875        // context we computed is the semantic context for our new
876        // declaration.
877        PrevDecl = PrevClassTemplate = 0;
878        SemanticContext = OutermostContext;
879      }
880    }
881
882    if (CurContext->isDependentContext()) {
883      // If this is a dependent context, we don't want to link the friend
884      // class template to the template in scope, because that would perform
885      // checking of the template parameter lists that can't be performed
886      // until the outer context is instantiated.
887      PrevDecl = PrevClassTemplate = 0;
888    }
889  } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
890    PrevDecl = PrevClassTemplate = 0;
891
892  if (PrevClassTemplate) {
893    // Ensure that the template parameter lists are compatible.
894    if (!TemplateParameterListsAreEqual(TemplateParams,
895                                   PrevClassTemplate->getTemplateParameters(),
896                                        /*Complain=*/true,
897                                        TPL_TemplateMatch))
898      return true;
899
900    // C++ [temp.class]p4:
901    //   In a redeclaration, partial specialization, explicit
902    //   specialization or explicit instantiation of a class template,
903    //   the class-key shall agree in kind with the original class
904    //   template declaration (7.1.5.3).
905    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
906    if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
907      Diag(KWLoc, diag::err_use_with_wrong_tag)
908        << Name
909        << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
910      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
911      Kind = PrevRecordDecl->getTagKind();
912    }
913
914    // Check for redefinition of this class template.
915    if (TUK == TUK_Definition) {
916      if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
917        Diag(NameLoc, diag::err_redefinition) << Name;
918        Diag(Def->getLocation(), diag::note_previous_definition);
919        // FIXME: Would it make sense to try to "forget" the previous
920        // definition, as part of error recovery?
921        return true;
922      }
923    }
924  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
925    // Maybe we will complain about the shadowed template parameter.
926    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
927    // Just pretend that we didn't see the previous declaration.
928    PrevDecl = 0;
929  } else if (PrevDecl) {
930    // C++ [temp]p5:
931    //   A class template shall not have the same name as any other
932    //   template, class, function, object, enumeration, enumerator,
933    //   namespace, or type in the same scope (3.3), except as specified
934    //   in (14.5.4).
935    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
936    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
937    return true;
938  }
939
940  // Check the template parameter list of this declaration, possibly
941  // merging in the template parameter list from the previous class
942  // template declaration.
943  if (CheckTemplateParameterList(TemplateParams,
944            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
945                                 TPC_ClassTemplate))
946    Invalid = true;
947
948  if (SS.isSet()) {
949    // If the name of the template was qualified, we must be defining the
950    // template out-of-line.
951    if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
952        !(TUK == TUK_Friend && CurContext->isDependentContext()))
953      Diag(NameLoc, diag::err_member_def_does_not_match)
954        << Name << SemanticContext << SS.getRange();
955  }
956
957  CXXRecordDecl *NewClass =
958    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
959                          PrevClassTemplate?
960                            PrevClassTemplate->getTemplatedDecl() : 0,
961                          /*DelayTypeCreation=*/true);
962  SetNestedNameSpecifier(NewClass, SS);
963
964  ClassTemplateDecl *NewTemplate
965    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
966                                DeclarationName(Name), TemplateParams,
967                                NewClass, PrevClassTemplate);
968  NewClass->setDescribedClassTemplate(NewTemplate);
969
970  // Build the type for the class template declaration now.
971  QualType T = NewTemplate->getInjectedClassNameSpecialization();
972  T = Context.getInjectedClassNameType(NewClass, T);
973  assert(T->isDependentType() && "Class template type is not dependent?");
974  (void)T;
975
976  // If we are providing an explicit specialization of a member that is a
977  // class template, make a note of that.
978  if (PrevClassTemplate &&
979      PrevClassTemplate->getInstantiatedFromMemberTemplate())
980    PrevClassTemplate->setMemberSpecialization();
981
982  // Set the access specifier.
983  if (!Invalid && TUK != TUK_Friend)
984    SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
985
986  // Set the lexical context of these templates
987  NewClass->setLexicalDeclContext(CurContext);
988  NewTemplate->setLexicalDeclContext(CurContext);
989
990  if (TUK == TUK_Definition)
991    NewClass->startDefinition();
992
993  if (Attr)
994    ProcessDeclAttributeList(S, NewClass, Attr);
995
996  if (TUK != TUK_Friend)
997    PushOnScopeChains(NewTemplate, S);
998  else {
999    if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1000      NewTemplate->setAccess(PrevClassTemplate->getAccess());
1001      NewClass->setAccess(PrevClassTemplate->getAccess());
1002    }
1003
1004    NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1005                                       PrevClassTemplate != NULL);
1006
1007    // Friend templates are visible in fairly strange ways.
1008    if (!CurContext->isDependentContext()) {
1009      DeclContext *DC = SemanticContext->getRedeclContext();
1010      DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1011      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1012        PushOnScopeChains(NewTemplate, EnclosingScope,
1013                          /* AddToContext = */ false);
1014    }
1015
1016    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1017                                            NewClass->getLocation(),
1018                                            NewTemplate,
1019                                    /*FIXME:*/NewClass->getLocation());
1020    Friend->setAccess(AS_public);
1021    CurContext->addDecl(Friend);
1022  }
1023
1024  if (Invalid) {
1025    NewTemplate->setInvalidDecl();
1026    NewClass->setInvalidDecl();
1027  }
1028  return NewTemplate;
1029}
1030
1031/// \brief Diagnose the presence of a default template argument on a
1032/// template parameter, which is ill-formed in certain contexts.
1033///
1034/// \returns true if the default template argument should be dropped.
1035static bool DiagnoseDefaultTemplateArgument(Sema &S,
1036                                            Sema::TemplateParamListContext TPC,
1037                                            SourceLocation ParamLoc,
1038                                            SourceRange DefArgRange) {
1039  switch (TPC) {
1040  case Sema::TPC_ClassTemplate:
1041    return false;
1042
1043  case Sema::TPC_FunctionTemplate:
1044    // C++ [temp.param]p9:
1045    //   A default template-argument shall not be specified in a
1046    //   function template declaration or a function template
1047    //   definition [...]
1048    // (This sentence is not in C++0x, per DR226).
1049    if (!S.getLangOptions().CPlusPlus0x)
1050      S.Diag(ParamLoc,
1051             diag::err_template_parameter_default_in_function_template)
1052        << DefArgRange;
1053    return false;
1054
1055  case Sema::TPC_ClassTemplateMember:
1056    // C++0x [temp.param]p9:
1057    //   A default template-argument shall not be specified in the
1058    //   template-parameter-lists of the definition of a member of a
1059    //   class template that appears outside of the member's class.
1060    S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1061      << DefArgRange;
1062    return true;
1063
1064  case Sema::TPC_FriendFunctionTemplate:
1065    // C++ [temp.param]p9:
1066    //   A default template-argument shall not be specified in a
1067    //   friend template declaration.
1068    S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1069      << DefArgRange;
1070    return true;
1071
1072    // FIXME: C++0x [temp.param]p9 allows default template-arguments
1073    // for friend function templates if there is only a single
1074    // declaration (and it is a definition). Strange!
1075  }
1076
1077  return false;
1078}
1079
1080/// \brief Check for unexpanded parameter packs within the template parameters
1081/// of a template template parameter, recursively.
1082bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1083  TemplateParameterList *Params = TTP->getTemplateParameters();
1084  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1085    NamedDecl *P = Params->getParam(I);
1086    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1087      if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1088                                            NTTP->getTypeSourceInfo(),
1089                                      Sema::UPPC_NonTypeTemplateParameterType))
1090        return true;
1091
1092      continue;
1093    }
1094
1095    if (TemplateTemplateParmDecl *InnerTTP
1096                                        = dyn_cast<TemplateTemplateParmDecl>(P))
1097      if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1098        return true;
1099  }
1100
1101  return false;
1102}
1103
1104/// \brief Checks the validity of a template parameter list, possibly
1105/// considering the template parameter list from a previous
1106/// declaration.
1107///
1108/// If an "old" template parameter list is provided, it must be
1109/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1110/// template parameter list.
1111///
1112/// \param NewParams Template parameter list for a new template
1113/// declaration. This template parameter list will be updated with any
1114/// default arguments that are carried through from the previous
1115/// template parameter list.
1116///
1117/// \param OldParams If provided, template parameter list from a
1118/// previous declaration of the same template. Default template
1119/// arguments will be merged from the old template parameter list to
1120/// the new template parameter list.
1121///
1122/// \param TPC Describes the context in which we are checking the given
1123/// template parameter list.
1124///
1125/// \returns true if an error occurred, false otherwise.
1126bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1127                                      TemplateParameterList *OldParams,
1128                                      TemplateParamListContext TPC) {
1129  bool Invalid = false;
1130
1131  // C++ [temp.param]p10:
1132  //   The set of default template-arguments available for use with a
1133  //   template declaration or definition is obtained by merging the
1134  //   default arguments from the definition (if in scope) and all
1135  //   declarations in scope in the same way default function
1136  //   arguments are (8.3.6).
1137  bool SawDefaultArgument = false;
1138  SourceLocation PreviousDefaultArgLoc;
1139
1140  bool SawParameterPack = false;
1141  SourceLocation ParameterPackLoc;
1142
1143  // Dummy initialization to avoid warnings.
1144  TemplateParameterList::iterator OldParam = NewParams->end();
1145  if (OldParams)
1146    OldParam = OldParams->begin();
1147
1148  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1149                                    NewParamEnd = NewParams->end();
1150       NewParam != NewParamEnd; ++NewParam) {
1151    // Variables used to diagnose redundant default arguments
1152    bool RedundantDefaultArg = false;
1153    SourceLocation OldDefaultLoc;
1154    SourceLocation NewDefaultLoc;
1155
1156    // Variables used to diagnose missing default arguments
1157    bool MissingDefaultArg = false;
1158
1159    // C++0x [temp.param]p11:
1160    //   If a template parameter of a primary class template is a template
1161    //   parameter pack, it shall be the last template parameter.
1162    if (SawParameterPack && TPC == TPC_ClassTemplate) {
1163      Diag(ParameterPackLoc,
1164           diag::err_template_param_pack_must_be_last_template_parameter);
1165      Invalid = true;
1166    }
1167
1168    if (TemplateTypeParmDecl *NewTypeParm
1169          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1170      // Check the presence of a default argument here.
1171      if (NewTypeParm->hasDefaultArgument() &&
1172          DiagnoseDefaultTemplateArgument(*this, TPC,
1173                                          NewTypeParm->getLocation(),
1174               NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1175                                                       .getSourceRange()))
1176        NewTypeParm->removeDefaultArgument();
1177
1178      // Merge default arguments for template type parameters.
1179      TemplateTypeParmDecl *OldTypeParm
1180          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1181
1182      if (NewTypeParm->isParameterPack()) {
1183        assert(!NewTypeParm->hasDefaultArgument() &&
1184               "Parameter packs can't have a default argument!");
1185        SawParameterPack = true;
1186        ParameterPackLoc = NewTypeParm->getLocation();
1187      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1188                 NewTypeParm->hasDefaultArgument()) {
1189        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1190        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1191        SawDefaultArgument = true;
1192        RedundantDefaultArg = true;
1193        PreviousDefaultArgLoc = NewDefaultLoc;
1194      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1195        // Merge the default argument from the old declaration to the
1196        // new declaration.
1197        SawDefaultArgument = true;
1198        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1199                                        true);
1200        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1201      } else if (NewTypeParm->hasDefaultArgument()) {
1202        SawDefaultArgument = true;
1203        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1204      } else if (SawDefaultArgument)
1205        MissingDefaultArg = true;
1206    } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1207               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1208      // Check for unexpanded parameter packs.
1209      if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1210                                          NewNonTypeParm->getTypeSourceInfo(),
1211                                          UPPC_NonTypeTemplateParameterType)) {
1212        Invalid = true;
1213        continue;
1214      }
1215
1216      // Check the presence of a default argument here.
1217      if (NewNonTypeParm->hasDefaultArgument() &&
1218          DiagnoseDefaultTemplateArgument(*this, TPC,
1219                                          NewNonTypeParm->getLocation(),
1220                    NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1221        NewNonTypeParm->removeDefaultArgument();
1222      }
1223
1224      // Merge default arguments for non-type template parameters
1225      NonTypeTemplateParmDecl *OldNonTypeParm
1226        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1227      if (NewNonTypeParm->isParameterPack()) {
1228        assert(!NewNonTypeParm->hasDefaultArgument() &&
1229               "Parameter packs can't have a default argument!");
1230        SawParameterPack = true;
1231        ParameterPackLoc = NewNonTypeParm->getLocation();
1232      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1233          NewNonTypeParm->hasDefaultArgument()) {
1234        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1235        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1236        SawDefaultArgument = true;
1237        RedundantDefaultArg = true;
1238        PreviousDefaultArgLoc = NewDefaultLoc;
1239      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1240        // Merge the default argument from the old declaration to the
1241        // new declaration.
1242        SawDefaultArgument = true;
1243        // FIXME: We need to create a new kind of "default argument"
1244        // expression that points to a previous non-type template
1245        // parameter.
1246        NewNonTypeParm->setDefaultArgument(
1247                                         OldNonTypeParm->getDefaultArgument(),
1248                                         /*Inherited=*/ true);
1249        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1250      } else if (NewNonTypeParm->hasDefaultArgument()) {
1251        SawDefaultArgument = true;
1252        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1253      } else if (SawDefaultArgument)
1254        MissingDefaultArg = true;
1255    } else {
1256      // Check the presence of a default argument here.
1257      TemplateTemplateParmDecl *NewTemplateParm
1258        = cast<TemplateTemplateParmDecl>(*NewParam);
1259
1260      // Check for unexpanded parameter packs, recursively.
1261      if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1262        Invalid = true;
1263        continue;
1264      }
1265
1266      if (NewTemplateParm->hasDefaultArgument() &&
1267          DiagnoseDefaultTemplateArgument(*this, TPC,
1268                                          NewTemplateParm->getLocation(),
1269                     NewTemplateParm->getDefaultArgument().getSourceRange()))
1270        NewTemplateParm->removeDefaultArgument();
1271
1272      // Merge default arguments for template template parameters
1273      TemplateTemplateParmDecl *OldTemplateParm
1274        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1275      if (NewTemplateParm->isParameterPack()) {
1276        assert(!NewTemplateParm->hasDefaultArgument() &&
1277               "Parameter packs can't have a default argument!");
1278        SawParameterPack = true;
1279        ParameterPackLoc = NewTemplateParm->getLocation();
1280      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1281          NewTemplateParm->hasDefaultArgument()) {
1282        OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1283        NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1284        SawDefaultArgument = true;
1285        RedundantDefaultArg = true;
1286        PreviousDefaultArgLoc = NewDefaultLoc;
1287      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1288        // Merge the default argument from the old declaration to the
1289        // new declaration.
1290        SawDefaultArgument = true;
1291        // FIXME: We need to create a new kind of "default argument" expression
1292        // that points to a previous template template parameter.
1293        NewTemplateParm->setDefaultArgument(
1294                                          OldTemplateParm->getDefaultArgument(),
1295                                          /*Inherited=*/ true);
1296        PreviousDefaultArgLoc
1297          = OldTemplateParm->getDefaultArgument().getLocation();
1298      } else if (NewTemplateParm->hasDefaultArgument()) {
1299        SawDefaultArgument = true;
1300        PreviousDefaultArgLoc
1301          = NewTemplateParm->getDefaultArgument().getLocation();
1302      } else if (SawDefaultArgument)
1303        MissingDefaultArg = true;
1304    }
1305
1306    if (RedundantDefaultArg) {
1307      // C++ [temp.param]p12:
1308      //   A template-parameter shall not be given default arguments
1309      //   by two different declarations in the same scope.
1310      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1311      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1312      Invalid = true;
1313    } else if (MissingDefaultArg) {
1314      // C++ [temp.param]p11:
1315      //   If a template-parameter of a class template has a default
1316      //   template-argument, each subsequent template- parameter shall either
1317      //   have a default template-argument supplied or be a template parameter
1318      //   pack.
1319      Diag((*NewParam)->getLocation(),
1320           diag::err_template_param_default_arg_missing);
1321      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1322      Invalid = true;
1323    }
1324
1325    // If we have an old template parameter list that we're merging
1326    // in, move on to the next parameter.
1327    if (OldParams)
1328      ++OldParam;
1329  }
1330
1331  return Invalid;
1332}
1333
1334namespace {
1335
1336/// A class which looks for a use of a certain level of template
1337/// parameter.
1338struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1339  typedef RecursiveASTVisitor<DependencyChecker> super;
1340
1341  unsigned Depth;
1342  bool Match;
1343
1344  DependencyChecker(TemplateParameterList *Params) : Match(false) {
1345    NamedDecl *ND = Params->getParam(0);
1346    if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1347      Depth = PD->getDepth();
1348    } else if (NonTypeTemplateParmDecl *PD =
1349                 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1350      Depth = PD->getDepth();
1351    } else {
1352      Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1353    }
1354  }
1355
1356  bool Matches(unsigned ParmDepth) {
1357    if (ParmDepth >= Depth) {
1358      Match = true;
1359      return true;
1360    }
1361    return false;
1362  }
1363
1364  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1365    return !Matches(T->getDepth());
1366  }
1367
1368  bool TraverseTemplateName(TemplateName N) {
1369    if (TemplateTemplateParmDecl *PD =
1370          dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1371      if (Matches(PD->getDepth())) return false;
1372    return super::TraverseTemplateName(N);
1373  }
1374
1375  bool VisitDeclRefExpr(DeclRefExpr *E) {
1376    if (NonTypeTemplateParmDecl *PD =
1377          dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1378      if (PD->getDepth() == Depth) {
1379        Match = true;
1380        return false;
1381      }
1382    }
1383    return super::VisitDeclRefExpr(E);
1384  }
1385};
1386}
1387
1388/// Determines whether a template-id depends on the given parameter
1389/// list.
1390static bool
1391DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1392                            TemplateParameterList *Params) {
1393  DependencyChecker Checker(Params);
1394  Checker.TraverseType(QualType(TemplateId, 0));
1395  return Checker.Match;
1396}
1397
1398/// \brief Match the given template parameter lists to the given scope
1399/// specifier, returning the template parameter list that applies to the
1400/// name.
1401///
1402/// \param DeclStartLoc the start of the declaration that has a scope
1403/// specifier or a template parameter list.
1404///
1405/// \param SS the scope specifier that will be matched to the given template
1406/// parameter lists. This scope specifier precedes a qualified name that is
1407/// being declared.
1408///
1409/// \param ParamLists the template parameter lists, from the outermost to the
1410/// innermost template parameter lists.
1411///
1412/// \param NumParamLists the number of template parameter lists in ParamLists.
1413///
1414/// \param IsFriend Whether to apply the slightly different rules for
1415/// matching template parameters to scope specifiers in friend
1416/// declarations.
1417///
1418/// \param IsExplicitSpecialization will be set true if the entity being
1419/// declared is an explicit specialization, false otherwise.
1420///
1421/// \returns the template parameter list, if any, that corresponds to the
1422/// name that is preceded by the scope specifier @p SS. This template
1423/// parameter list may be have template parameters (if we're declaring a
1424/// template) or may have no template parameters (if we're declaring a
1425/// template specialization), or may be NULL (if we were's declaring isn't
1426/// itself a template).
1427TemplateParameterList *
1428Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1429                                              const CXXScopeSpec &SS,
1430                                          TemplateParameterList **ParamLists,
1431                                              unsigned NumParamLists,
1432                                              bool IsFriend,
1433                                              bool &IsExplicitSpecialization,
1434                                              bool &Invalid) {
1435  IsExplicitSpecialization = false;
1436
1437  // Find the template-ids that occur within the nested-name-specifier. These
1438  // template-ids will match up with the template parameter lists.
1439  llvm::SmallVector<const TemplateSpecializationType *, 4>
1440    TemplateIdsInSpecifier;
1441  llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1442    ExplicitSpecializationsInSpecifier;
1443  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1444       NNS; NNS = NNS->getPrefix()) {
1445    const Type *T = NNS->getAsType();
1446    if (!T) break;
1447
1448    // C++0x [temp.expl.spec]p17:
1449    //   A member or a member template may be nested within many
1450    //   enclosing class templates. In an explicit specialization for
1451    //   such a member, the member declaration shall be preceded by a
1452    //   template<> for each enclosing class template that is
1453    //   explicitly specialized.
1454    //
1455    // Following the existing practice of GNU and EDG, we allow a typedef of a
1456    // template specialization type.
1457    while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1458      T = TT->getDecl()->getUnderlyingType().getTypePtr();
1459
1460    if (const TemplateSpecializationType *SpecType
1461                                  = dyn_cast<TemplateSpecializationType>(T)) {
1462      TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1463      if (!Template)
1464        continue; // FIXME: should this be an error? probably...
1465
1466      if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1467        ClassTemplateSpecializationDecl *SpecDecl
1468          = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1469        // If the nested name specifier refers to an explicit specialization,
1470        // we don't need a template<> header.
1471        if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1472          ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1473          continue;
1474        }
1475      }
1476
1477      TemplateIdsInSpecifier.push_back(SpecType);
1478    }
1479  }
1480
1481  // Reverse the list of template-ids in the scope specifier, so that we can
1482  // more easily match up the template-ids and the template parameter lists.
1483  std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1484
1485  SourceLocation FirstTemplateLoc = DeclStartLoc;
1486  if (NumParamLists)
1487    FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1488
1489  // Match the template-ids found in the specifier to the template parameter
1490  // lists.
1491  unsigned ParamIdx = 0, TemplateIdx = 0;
1492  for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1493       TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1494    const TemplateSpecializationType *TemplateId
1495      = TemplateIdsInSpecifier[TemplateIdx];
1496    bool DependentTemplateId = TemplateId->isDependentType();
1497
1498    // In friend declarations we can have template-ids which don't
1499    // depend on the corresponding template parameter lists.  But
1500    // assume that empty parameter lists are supposed to match this
1501    // template-id.
1502    if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1503      if (!DependentTemplateId ||
1504          !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1505        continue;
1506    }
1507
1508    if (ParamIdx >= NumParamLists) {
1509      // We have a template-id without a corresponding template parameter
1510      // list.
1511
1512      // ...which is fine if this is a friend declaration.
1513      if (IsFriend) {
1514        IsExplicitSpecialization = true;
1515        break;
1516      }
1517
1518      if (DependentTemplateId) {
1519        // FIXME: the location information here isn't great.
1520        Diag(SS.getRange().getBegin(),
1521             diag::err_template_spec_needs_template_parameters)
1522          << QualType(TemplateId, 0)
1523          << SS.getRange();
1524        Invalid = true;
1525      } else {
1526        Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1527          << SS.getRange()
1528          << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
1529        IsExplicitSpecialization = true;
1530      }
1531      return 0;
1532    }
1533
1534    // Check the template parameter list against its corresponding template-id.
1535    if (DependentTemplateId) {
1536      TemplateParameterList *ExpectedTemplateParams = 0;
1537
1538      // Are there cases in (e.g.) friends where this won't match?
1539      if (const InjectedClassNameType *Injected
1540            = TemplateId->getAs<InjectedClassNameType>()) {
1541        CXXRecordDecl *Record = Injected->getDecl();
1542        if (ClassTemplatePartialSpecializationDecl *Partial =
1543              dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1544          ExpectedTemplateParams = Partial->getTemplateParameters();
1545        else
1546          ExpectedTemplateParams = Record->getDescribedClassTemplate()
1547            ->getTemplateParameters();
1548      }
1549
1550      if (ExpectedTemplateParams)
1551        TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1552                                       ExpectedTemplateParams,
1553                                       true, TPL_TemplateMatch);
1554
1555      CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1556                                 TPC_ClassTemplateMember);
1557    } else if (ParamLists[ParamIdx]->size() > 0)
1558      Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1559           diag::err_template_param_list_matches_nontemplate)
1560        << TemplateId
1561        << ParamLists[ParamIdx]->getSourceRange();
1562    else
1563      IsExplicitSpecialization = true;
1564
1565    ++ParamIdx;
1566  }
1567
1568  // If there were at least as many template-ids as there were template
1569  // parameter lists, then there are no template parameter lists remaining for
1570  // the declaration itself.
1571  if (ParamIdx >= NumParamLists)
1572    return 0;
1573
1574  // If there were too many template parameter lists, complain about that now.
1575  if (ParamIdx != NumParamLists - 1) {
1576    while (ParamIdx < NumParamLists - 1) {
1577      bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1578      Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1579           isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1580                               : diag::err_template_spec_extra_headers)
1581        << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1582                       ParamLists[ParamIdx]->getRAngleLoc());
1583
1584      if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1585        Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1586             diag::note_explicit_template_spec_does_not_need_header)
1587          << ExplicitSpecializationsInSpecifier.back();
1588        ExplicitSpecializationsInSpecifier.pop_back();
1589      }
1590
1591      // We have a template parameter list with no corresponding scope, which
1592      // means that the resulting template declaration can't be instantiated
1593      // properly (we'll end up with dependent nodes when we shouldn't).
1594      if (!isExplicitSpecHeader)
1595        Invalid = true;
1596
1597      ++ParamIdx;
1598    }
1599  }
1600
1601  // Return the last template parameter list, which corresponds to the
1602  // entity being declared.
1603  return ParamLists[NumParamLists - 1];
1604}
1605
1606QualType Sema::CheckTemplateIdType(TemplateName Name,
1607                                   SourceLocation TemplateLoc,
1608                              const TemplateArgumentListInfo &TemplateArgs) {
1609  TemplateDecl *Template = Name.getAsTemplateDecl();
1610  if (!Template) {
1611    // The template name does not resolve to a template, so we just
1612    // build a dependent template-id type.
1613    return Context.getTemplateSpecializationType(Name, TemplateArgs);
1614  }
1615
1616  // Check that the template argument list is well-formed for this
1617  // template.
1618  llvm::SmallVector<TemplateArgument, 4> Converted;
1619  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1620                                false, Converted))
1621    return QualType();
1622
1623  assert((Converted.size() == Template->getTemplateParameters()->size()) &&
1624         "Converted template argument list is too short!");
1625
1626  QualType CanonType;
1627
1628  if (Name.isDependent() ||
1629      TemplateSpecializationType::anyDependentTemplateArguments(
1630                                                      TemplateArgs)) {
1631    // This class template specialization is a dependent
1632    // type. Therefore, its canonical type is another class template
1633    // specialization type that contains all of the converted
1634    // arguments in canonical form. This ensures that, e.g., A<T> and
1635    // A<T, T> have identical types when A is declared as:
1636    //
1637    //   template<typename T, typename U = T> struct A;
1638    TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1639    CanonType = Context.getTemplateSpecializationType(CanonName,
1640                                                      Converted.data(),
1641                                                      Converted.size());
1642
1643    // FIXME: CanonType is not actually the canonical type, and unfortunately
1644    // it is a TemplateSpecializationType that we will never use again.
1645    // In the future, we need to teach getTemplateSpecializationType to only
1646    // build the canonical type and return that to us.
1647    CanonType = Context.getCanonicalType(CanonType);
1648
1649    // This might work out to be a current instantiation, in which
1650    // case the canonical type needs to be the InjectedClassNameType.
1651    //
1652    // TODO: in theory this could be a simple hashtable lookup; most
1653    // changes to CurContext don't change the set of current
1654    // instantiations.
1655    if (isa<ClassTemplateDecl>(Template)) {
1656      for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1657        // If we get out to a namespace, we're done.
1658        if (Ctx->isFileContext()) break;
1659
1660        // If this isn't a record, keep looking.
1661        CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1662        if (!Record) continue;
1663
1664        // Look for one of the two cases with InjectedClassNameTypes
1665        // and check whether it's the same template.
1666        if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1667            !Record->getDescribedClassTemplate())
1668          continue;
1669
1670        // Fetch the injected class name type and check whether its
1671        // injected type is equal to the type we just built.
1672        QualType ICNT = Context.getTypeDeclType(Record);
1673        QualType Injected = cast<InjectedClassNameType>(ICNT)
1674          ->getInjectedSpecializationType();
1675
1676        if (CanonType != Injected->getCanonicalTypeInternal())
1677          continue;
1678
1679        // If so, the canonical type of this TST is the injected
1680        // class name type of the record we just found.
1681        assert(ICNT.isCanonical());
1682        CanonType = ICNT;
1683        break;
1684      }
1685    }
1686  } else if (ClassTemplateDecl *ClassTemplate
1687               = dyn_cast<ClassTemplateDecl>(Template)) {
1688    // Find the class template specialization declaration that
1689    // corresponds to these arguments.
1690    void *InsertPos = 0;
1691    ClassTemplateSpecializationDecl *Decl
1692      = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1693                                          InsertPos);
1694    if (!Decl) {
1695      // This is the first time we have referenced this class template
1696      // specialization. Create the canonical declaration and add it to
1697      // the set of specializations.
1698      Decl = ClassTemplateSpecializationDecl::Create(Context,
1699                            ClassTemplate->getTemplatedDecl()->getTagKind(),
1700                                                ClassTemplate->getDeclContext(),
1701                                                ClassTemplate->getLocation(),
1702                                                     ClassTemplate,
1703                                                     Converted.data(),
1704                                                     Converted.size(), 0);
1705      ClassTemplate->AddSpecialization(Decl, InsertPos);
1706      Decl->setLexicalDeclContext(CurContext);
1707    }
1708
1709    CanonType = Context.getTypeDeclType(Decl);
1710    assert(isa<RecordType>(CanonType) &&
1711           "type of non-dependent specialization is not a RecordType");
1712  }
1713
1714  // Build the fully-sugared type for this class template
1715  // specialization, which refers back to the class template
1716  // specialization we created or found.
1717  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
1718}
1719
1720TypeResult
1721Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1722                          SourceLocation LAngleLoc,
1723                          ASTTemplateArgsPtr TemplateArgsIn,
1724                          SourceLocation RAngleLoc) {
1725  TemplateName Template = TemplateD.getAsVal<TemplateName>();
1726
1727  // Translate the parser's template argument list in our AST format.
1728  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1729  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1730
1731  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1732  TemplateArgsIn.release();
1733
1734  if (Result.isNull())
1735    return true;
1736
1737  TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1738  TemplateSpecializationTypeLoc TL
1739    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1740  TL.setTemplateNameLoc(TemplateLoc);
1741  TL.setLAngleLoc(LAngleLoc);
1742  TL.setRAngleLoc(RAngleLoc);
1743  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1744    TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1745
1746  return CreateParsedType(Result, DI);
1747}
1748
1749TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1750                                        TypeResult TypeResult,
1751                                        TagUseKind TUK,
1752                                        TypeSpecifierType TagSpec,
1753                                        SourceLocation TagLoc) {
1754  if (TypeResult.isInvalid())
1755    return ::TypeResult();
1756
1757  TypeSourceInfo *DI;
1758  QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1759
1760  // Verify the tag specifier.
1761  TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1762
1763  if (const RecordType *RT = Type->getAs<RecordType>()) {
1764    RecordDecl *D = RT->getDecl();
1765
1766    IdentifierInfo *Id = D->getIdentifier();
1767    assert(Id && "templated class must have an identifier");
1768
1769    if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1770      Diag(TagLoc, diag::err_use_with_wrong_tag)
1771        << Type
1772        << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
1773      Diag(D->getLocation(), diag::note_previous_use);
1774    }
1775  }
1776
1777  ElaboratedTypeKeyword Keyword
1778    = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1779  QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
1780
1781  TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1782  ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1783  TL.setKeywordLoc(TagLoc);
1784  TL.setQualifierRange(SS.getRange());
1785  TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1786  return CreateParsedType(ElabType, ElabDI);
1787}
1788
1789ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1790                                                 LookupResult &R,
1791                                                 bool RequiresADL,
1792                                 const TemplateArgumentListInfo &TemplateArgs) {
1793  // FIXME: Can we do any checking at this point? I guess we could check the
1794  // template arguments that we have against the template name, if the template
1795  // name refers to a single template. That's not a terribly common case,
1796  // though.
1797
1798  // These should be filtered out by our callers.
1799  assert(!R.empty() && "empty lookup results when building templateid");
1800  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1801
1802  NestedNameSpecifier *Qualifier = 0;
1803  SourceRange QualifierRange;
1804  if (SS.isSet()) {
1805    Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1806    QualifierRange = SS.getRange();
1807  }
1808
1809  // We don't want lookup warnings at this point.
1810  R.suppressDiagnostics();
1811
1812  UnresolvedLookupExpr *ULE
1813    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
1814                                   Qualifier, QualifierRange,
1815                                   R.getLookupNameInfo(),
1816                                   RequiresADL, TemplateArgs,
1817                                   R.begin(), R.end());
1818
1819  return Owned(ULE);
1820}
1821
1822// We actually only call this from template instantiation.
1823ExprResult
1824Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
1825                                   const DeclarationNameInfo &NameInfo,
1826                             const TemplateArgumentListInfo &TemplateArgs) {
1827  DeclContext *DC;
1828  if (!(DC = computeDeclContext(SS, false)) ||
1829      DC->isDependentContext() ||
1830      RequireCompleteDeclContext(SS, DC))
1831    return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
1832
1833  bool MemberOfUnknownSpecialization;
1834  LookupResult R(*this, NameInfo, LookupOrdinaryName);
1835  LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1836                     MemberOfUnknownSpecialization);
1837
1838  if (R.isAmbiguous())
1839    return ExprError();
1840
1841  if (R.empty()) {
1842    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1843      << NameInfo.getName() << SS.getRange();
1844    return ExprError();
1845  }
1846
1847  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1848    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1849      << (NestedNameSpecifier*) SS.getScopeRep()
1850      << NameInfo.getName() << SS.getRange();
1851    Diag(Temp->getLocation(), diag::note_referenced_class_template);
1852    return ExprError();
1853  }
1854
1855  return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1856}
1857
1858/// \brief Form a dependent template name.
1859///
1860/// This action forms a dependent template name given the template
1861/// name and its (presumably dependent) scope specifier. For
1862/// example, given "MetaFun::template apply", the scope specifier \p
1863/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1864/// of the "template" keyword, and "apply" is the \p Name.
1865TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1866                                                  SourceLocation TemplateKWLoc,
1867                                                  CXXScopeSpec &SS,
1868                                                  UnqualifiedId &Name,
1869                                                  ParsedType ObjectType,
1870                                                  bool EnteringContext,
1871                                                  TemplateTy &Result) {
1872  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1873      !getLangOptions().CPlusPlus0x)
1874    Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1875      << FixItHint::CreateRemoval(TemplateKWLoc);
1876
1877  DeclContext *LookupCtx = 0;
1878  if (SS.isSet())
1879    LookupCtx = computeDeclContext(SS, EnteringContext);
1880  if (!LookupCtx && ObjectType)
1881    LookupCtx = computeDeclContext(ObjectType.get());
1882  if (LookupCtx) {
1883    // C++0x [temp.names]p5:
1884    //   If a name prefixed by the keyword template is not the name of
1885    //   a template, the program is ill-formed. [Note: the keyword
1886    //   template may not be applied to non-template members of class
1887    //   templates. -end note ] [ Note: as is the case with the
1888    //   typename prefix, the template prefix is allowed in cases
1889    //   where it is not strictly necessary; i.e., when the
1890    //   nested-name-specifier or the expression on the left of the ->
1891    //   or . is not dependent on a template-parameter, or the use
1892    //   does not appear in the scope of a template. -end note]
1893    //
1894    // Note: C++03 was more strict here, because it banned the use of
1895    // the "template" keyword prior to a template-name that was not a
1896    // dependent name. C++ DR468 relaxed this requirement (the
1897    // "template" keyword is now permitted). We follow the C++0x
1898    // rules, even in C++03 mode with a warning, retroactively applying the DR.
1899    bool MemberOfUnknownSpecialization;
1900    TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1901                                          ObjectType, EnteringContext, Result,
1902                                          MemberOfUnknownSpecialization);
1903    if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1904        isa<CXXRecordDecl>(LookupCtx) &&
1905        cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
1906      // This is a dependent template. Handle it below.
1907    } else if (TNK == TNK_Non_template) {
1908      Diag(Name.getSourceRange().getBegin(),
1909           diag::err_template_kw_refers_to_non_template)
1910        << GetNameFromUnqualifiedId(Name).getName()
1911        << Name.getSourceRange()
1912        << TemplateKWLoc;
1913      return TNK_Non_template;
1914    } else {
1915      // We found something; return it.
1916      return TNK;
1917    }
1918  }
1919
1920  NestedNameSpecifier *Qualifier
1921    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1922
1923  switch (Name.getKind()) {
1924  case UnqualifiedId::IK_Identifier:
1925    Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1926                                                              Name.Identifier));
1927    return TNK_Dependent_template_name;
1928
1929  case UnqualifiedId::IK_OperatorFunctionId:
1930    Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1931                                             Name.OperatorFunctionId.Operator));
1932    return TNK_Dependent_template_name;
1933
1934  case UnqualifiedId::IK_LiteralOperatorId:
1935    assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1936
1937  default:
1938    break;
1939  }
1940
1941  Diag(Name.getSourceRange().getBegin(),
1942       diag::err_template_kw_refers_to_non_template)
1943    << GetNameFromUnqualifiedId(Name).getName()
1944    << Name.getSourceRange()
1945    << TemplateKWLoc;
1946  return TNK_Non_template;
1947}
1948
1949bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1950                                     const TemplateArgumentLoc &AL,
1951                          llvm::SmallVectorImpl<TemplateArgument> &Converted) {
1952  const TemplateArgument &Arg = AL.getArgument();
1953
1954  // Check template type parameter.
1955  switch(Arg.getKind()) {
1956  case TemplateArgument::Type:
1957    // C++ [temp.arg.type]p1:
1958    //   A template-argument for a template-parameter which is a
1959    //   type shall be a type-id.
1960    break;
1961  case TemplateArgument::Template: {
1962    // We have a template type parameter but the template argument
1963    // is a template without any arguments.
1964    SourceRange SR = AL.getSourceRange();
1965    TemplateName Name = Arg.getAsTemplate();
1966    Diag(SR.getBegin(), diag::err_template_missing_args)
1967      << Name << SR;
1968    if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1969      Diag(Decl->getLocation(), diag::note_template_decl_here);
1970
1971    return true;
1972  }
1973  default: {
1974    // We have a template type parameter but the template argument
1975    // is not a type.
1976    SourceRange SR = AL.getSourceRange();
1977    Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
1978    Diag(Param->getLocation(), diag::note_template_param_here);
1979
1980    return true;
1981  }
1982  }
1983
1984  if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
1985    return true;
1986
1987  // Add the converted template type argument.
1988  Converted.push_back(
1989                 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
1990  return false;
1991}
1992
1993/// \brief Substitute template arguments into the default template argument for
1994/// the given template type parameter.
1995///
1996/// \param SemaRef the semantic analysis object for which we are performing
1997/// the substitution.
1998///
1999/// \param Template the template that we are synthesizing template arguments
2000/// for.
2001///
2002/// \param TemplateLoc the location of the template name that started the
2003/// template-id we are checking.
2004///
2005/// \param RAngleLoc the location of the right angle bracket ('>') that
2006/// terminates the template-id.
2007///
2008/// \param Param the template template parameter whose default we are
2009/// substituting into.
2010///
2011/// \param Converted the list of template arguments provided for template
2012/// parameters that precede \p Param in the template parameter list.
2013///
2014/// \returns the substituted template argument, or NULL if an error occurred.
2015static TypeSourceInfo *
2016SubstDefaultTemplateArgument(Sema &SemaRef,
2017                             TemplateDecl *Template,
2018                             SourceLocation TemplateLoc,
2019                             SourceLocation RAngleLoc,
2020                             TemplateTypeParmDecl *Param,
2021                         llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2022  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
2023
2024  // If the argument type is dependent, instantiate it now based
2025  // on the previously-computed template arguments.
2026  if (ArgType->getType()->isDependentType()) {
2027    TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2028                                      Converted.data(), Converted.size());
2029
2030    MultiLevelTemplateArgumentList AllTemplateArgs
2031      = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2032
2033    Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2034                                     Template, Converted.data(),
2035                                     Converted.size(),
2036                                     SourceRange(TemplateLoc, RAngleLoc));
2037
2038    ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2039                                Param->getDefaultArgumentLoc(),
2040                                Param->getDeclName());
2041  }
2042
2043  return ArgType;
2044}
2045
2046/// \brief Substitute template arguments into the default template argument for
2047/// the given non-type template parameter.
2048///
2049/// \param SemaRef the semantic analysis object for which we are performing
2050/// the substitution.
2051///
2052/// \param Template the template that we are synthesizing template arguments
2053/// for.
2054///
2055/// \param TemplateLoc the location of the template name that started the
2056/// template-id we are checking.
2057///
2058/// \param RAngleLoc the location of the right angle bracket ('>') that
2059/// terminates the template-id.
2060///
2061/// \param Param the non-type template parameter whose default we are
2062/// substituting into.
2063///
2064/// \param Converted the list of template arguments provided for template
2065/// parameters that precede \p Param in the template parameter list.
2066///
2067/// \returns the substituted template argument, or NULL if an error occurred.
2068static ExprResult
2069SubstDefaultTemplateArgument(Sema &SemaRef,
2070                             TemplateDecl *Template,
2071                             SourceLocation TemplateLoc,
2072                             SourceLocation RAngleLoc,
2073                             NonTypeTemplateParmDecl *Param,
2074                        llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2075  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2076                                    Converted.data(), Converted.size());
2077
2078  MultiLevelTemplateArgumentList AllTemplateArgs
2079    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2080
2081  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2082                                   Template, Converted.data(),
2083                                   Converted.size(),
2084                                   SourceRange(TemplateLoc, RAngleLoc));
2085
2086  return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2087}
2088
2089/// \brief Substitute template arguments into the default template argument for
2090/// the given template template parameter.
2091///
2092/// \param SemaRef the semantic analysis object for which we are performing
2093/// the substitution.
2094///
2095/// \param Template the template that we are synthesizing template arguments
2096/// for.
2097///
2098/// \param TemplateLoc the location of the template name that started the
2099/// template-id we are checking.
2100///
2101/// \param RAngleLoc the location of the right angle bracket ('>') that
2102/// terminates the template-id.
2103///
2104/// \param Param the template template parameter whose default we are
2105/// substituting into.
2106///
2107/// \param Converted the list of template arguments provided for template
2108/// parameters that precede \p Param in the template parameter list.
2109///
2110/// \returns the substituted template argument, or NULL if an error occurred.
2111static TemplateName
2112SubstDefaultTemplateArgument(Sema &SemaRef,
2113                             TemplateDecl *Template,
2114                             SourceLocation TemplateLoc,
2115                             SourceLocation RAngleLoc,
2116                             TemplateTemplateParmDecl *Param,
2117                       llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2118  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2119                                    Converted.data(), Converted.size());
2120
2121  MultiLevelTemplateArgumentList AllTemplateArgs
2122    = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2123
2124  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2125                                   Template, Converted.data(),
2126                                   Converted.size(),
2127                                   SourceRange(TemplateLoc, RAngleLoc));
2128
2129  return SemaRef.SubstTemplateName(
2130                      Param->getDefaultArgument().getArgument().getAsTemplate(),
2131                              Param->getDefaultArgument().getTemplateNameLoc(),
2132                                   AllTemplateArgs);
2133}
2134
2135/// \brief If the given template parameter has a default template
2136/// argument, substitute into that default template argument and
2137/// return the corresponding template argument.
2138TemplateArgumentLoc
2139Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2140                                              SourceLocation TemplateLoc,
2141                                              SourceLocation RAngleLoc,
2142                                              Decl *Param,
2143                      llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2144   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2145    if (!TypeParm->hasDefaultArgument())
2146      return TemplateArgumentLoc();
2147
2148    TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
2149                                                      TemplateLoc,
2150                                                      RAngleLoc,
2151                                                      TypeParm,
2152                                                      Converted);
2153    if (DI)
2154      return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2155
2156    return TemplateArgumentLoc();
2157  }
2158
2159  if (NonTypeTemplateParmDecl *NonTypeParm
2160        = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2161    if (!NonTypeParm->hasDefaultArgument())
2162      return TemplateArgumentLoc();
2163
2164    ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
2165                                                        TemplateLoc,
2166                                                        RAngleLoc,
2167                                                        NonTypeParm,
2168                                                        Converted);
2169    if (Arg.isInvalid())
2170      return TemplateArgumentLoc();
2171
2172    Expr *ArgE = Arg.takeAs<Expr>();
2173    return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2174  }
2175
2176  TemplateTemplateParmDecl *TempTempParm
2177    = cast<TemplateTemplateParmDecl>(Param);
2178  if (!TempTempParm->hasDefaultArgument())
2179    return TemplateArgumentLoc();
2180
2181  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2182                                                    TemplateLoc,
2183                                                    RAngleLoc,
2184                                                    TempTempParm,
2185                                                    Converted);
2186  if (TName.isNull())
2187    return TemplateArgumentLoc();
2188
2189  return TemplateArgumentLoc(TemplateArgument(TName),
2190                TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2191                TempTempParm->getDefaultArgument().getTemplateNameLoc());
2192}
2193
2194/// \brief Check that the given template argument corresponds to the given
2195/// template parameter.
2196bool Sema::CheckTemplateArgument(NamedDecl *Param,
2197                                 const TemplateArgumentLoc &Arg,
2198                                 NamedDecl *Template,
2199                                 SourceLocation TemplateLoc,
2200                                 SourceLocation RAngleLoc,
2201                            llvm::SmallVectorImpl<TemplateArgument> &Converted,
2202                                 CheckTemplateArgumentKind CTAK) {
2203  // Check template type parameters.
2204  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2205    return CheckTemplateTypeArgument(TTP, Arg, Converted);
2206
2207  // Check non-type template parameters.
2208  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2209    // Do substitution on the type of the non-type template parameter
2210    // with the template arguments we've seen thus far.  But if the
2211    // template has a dependent context then we cannot substitute yet.
2212    QualType NTTPType = NTTP->getType();
2213    if (NTTPType->isDependentType() &&
2214        !isa<TemplateTemplateParmDecl>(Template) &&
2215        !Template->getDeclContext()->isDependentContext()) {
2216      // Do substitution on the type of the non-type template parameter.
2217      InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2218                                 NTTP, Converted.data(), Converted.size(),
2219                                 SourceRange(TemplateLoc, RAngleLoc));
2220
2221      TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2222                                        Converted.data(), Converted.size());
2223      NTTPType = SubstType(NTTPType,
2224                           MultiLevelTemplateArgumentList(TemplateArgs),
2225                           NTTP->getLocation(),
2226                           NTTP->getDeclName());
2227      // If that worked, check the non-type template parameter type
2228      // for validity.
2229      if (!NTTPType.isNull())
2230        NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2231                                                     NTTP->getLocation());
2232      if (NTTPType.isNull())
2233        return true;
2234    }
2235
2236    switch (Arg.getArgument().getKind()) {
2237    case TemplateArgument::Null:
2238      assert(false && "Should never see a NULL template argument here");
2239      return true;
2240
2241    case TemplateArgument::Expression: {
2242      Expr *E = Arg.getArgument().getAsExpr();
2243      TemplateArgument Result;
2244      if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
2245        return true;
2246
2247      Converted.push_back(Result);
2248      break;
2249    }
2250
2251    case TemplateArgument::Declaration:
2252    case TemplateArgument::Integral:
2253      // We've already checked this template argument, so just copy
2254      // it to the list of converted arguments.
2255      Converted.push_back(Arg.getArgument());
2256      break;
2257
2258    case TemplateArgument::Template:
2259    case TemplateArgument::TemplateExpansion:
2260      // We were given a template template argument. It may not be ill-formed;
2261      // see below.
2262      if (DependentTemplateName *DTN
2263            = Arg.getArgument().getAsTemplateOrTemplatePattern()
2264                                              .getAsDependentTemplateName()) {
2265        // We have a template argument such as \c T::template X, which we
2266        // parsed as a template template argument. However, since we now
2267        // know that we need a non-type template argument, convert this
2268        // template name into an expression.
2269
2270        DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2271                                     Arg.getTemplateNameLoc());
2272
2273        Expr *E = DependentScopeDeclRefExpr::Create(Context,
2274                                                    DTN->getQualifier(),
2275                                               Arg.getTemplateQualifierRange(),
2276                                                    NameInfo);
2277
2278        // If we parsed the template argument as a pack expansion, create a
2279        // pack expansion expression.
2280        if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2281          ExprResult Expansion = ActOnPackExpansion(E,
2282                                                  Arg.getTemplateEllipsisLoc());
2283          if (Expansion.isInvalid())
2284            return true;
2285
2286          E = Expansion.get();
2287        }
2288
2289        TemplateArgument Result;
2290        if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2291          return true;
2292
2293        Converted.push_back(Result);
2294        break;
2295      }
2296
2297      // We have a template argument that actually does refer to a class
2298      // template, template alias, or template template parameter, and
2299      // therefore cannot be a non-type template argument.
2300      Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2301        << Arg.getSourceRange();
2302
2303      Diag(Param->getLocation(), diag::note_template_param_here);
2304      return true;
2305
2306    case TemplateArgument::Type: {
2307      // We have a non-type template parameter but the template
2308      // argument is a type.
2309
2310      // C++ [temp.arg]p2:
2311      //   In a template-argument, an ambiguity between a type-id and
2312      //   an expression is resolved to a type-id, regardless of the
2313      //   form of the corresponding template-parameter.
2314      //
2315      // We warn specifically about this case, since it can be rather
2316      // confusing for users.
2317      QualType T = Arg.getArgument().getAsType();
2318      SourceRange SR = Arg.getSourceRange();
2319      if (T->isFunctionType())
2320        Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2321      else
2322        Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2323      Diag(Param->getLocation(), diag::note_template_param_here);
2324      return true;
2325    }
2326
2327    case TemplateArgument::Pack:
2328      llvm_unreachable("Caller must expand template argument packs");
2329      break;
2330    }
2331
2332    return false;
2333  }
2334
2335
2336  // Check template template parameters.
2337  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2338
2339  // Substitute into the template parameter list of the template
2340  // template parameter, since previously-supplied template arguments
2341  // may appear within the template template parameter.
2342  {
2343    // Set up a template instantiation context.
2344    LocalInstantiationScope Scope(*this);
2345    InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2346                               TempParm, Converted.data(), Converted.size(),
2347                               SourceRange(TemplateLoc, RAngleLoc));
2348
2349    TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2350                                      Converted.data(), Converted.size());
2351    TempParm = cast_or_null<TemplateTemplateParmDecl>(
2352                      SubstDecl(TempParm, CurContext,
2353                                MultiLevelTemplateArgumentList(TemplateArgs)));
2354    if (!TempParm)
2355      return true;
2356  }
2357
2358  switch (Arg.getArgument().getKind()) {
2359  case TemplateArgument::Null:
2360    assert(false && "Should never see a NULL template argument here");
2361    return true;
2362
2363  case TemplateArgument::Template:
2364  case TemplateArgument::TemplateExpansion:
2365    if (CheckTemplateArgument(TempParm, Arg))
2366      return true;
2367
2368    Converted.push_back(Arg.getArgument());
2369    break;
2370
2371  case TemplateArgument::Expression:
2372  case TemplateArgument::Type:
2373    // We have a template template parameter but the template
2374    // argument does not refer to a template.
2375    Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2376    return true;
2377
2378  case TemplateArgument::Declaration:
2379    llvm_unreachable(
2380                       "Declaration argument with template template parameter");
2381    break;
2382  case TemplateArgument::Integral:
2383    llvm_unreachable(
2384                          "Integral argument with template template parameter");
2385    break;
2386
2387  case TemplateArgument::Pack:
2388    llvm_unreachable("Caller must expand template argument packs");
2389    break;
2390  }
2391
2392  return false;
2393}
2394
2395/// \brief Check that the given template argument list is well-formed
2396/// for specializing the given template.
2397bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2398                                     SourceLocation TemplateLoc,
2399                                const TemplateArgumentListInfo &TemplateArgs,
2400                                     bool PartialTemplateArgs,
2401                          llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2402  TemplateParameterList *Params = Template->getTemplateParameters();
2403  unsigned NumParams = Params->size();
2404  unsigned NumArgs = TemplateArgs.size();
2405  bool Invalid = false;
2406
2407  SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2408
2409  bool HasParameterPack =
2410    NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2411
2412  if ((NumArgs > NumParams && !HasParameterPack) ||
2413      (NumArgs < Params->getMinRequiredArguments() &&
2414       !PartialTemplateArgs)) {
2415    // FIXME: point at either the first arg beyond what we can handle,
2416    // or the '>', depending on whether we have too many or too few
2417    // arguments.
2418    SourceRange Range;
2419    if (NumArgs > NumParams)
2420      Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2421    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2422      << (NumArgs > NumParams)
2423      << (isa<ClassTemplateDecl>(Template)? 0 :
2424          isa<FunctionTemplateDecl>(Template)? 1 :
2425          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2426      << Template << Range;
2427    Diag(Template->getLocation(), diag::note_template_decl_here)
2428      << Params->getSourceRange();
2429    Invalid = true;
2430  }
2431
2432  // C++ [temp.arg]p1:
2433  //   [...] The type and form of each template-argument specified in
2434  //   a template-id shall match the type and form specified for the
2435  //   corresponding parameter declared by the template in its
2436  //   template-parameter-list.
2437  llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2438  TemplateParameterList::iterator Param = Params->begin(),
2439                               ParamEnd = Params->end();
2440  unsigned ArgIdx = 0;
2441  while (Param != ParamEnd) {
2442    if (ArgIdx > NumArgs && PartialTemplateArgs)
2443      break;
2444
2445    if (ArgIdx < NumArgs) {
2446      // Check the template argument we were given.
2447      if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2448                                TemplateLoc, RAngleLoc, Converted))
2449        return true;
2450
2451      if ((*Param)->isTemplateParameterPack()) {
2452        // The template parameter was a template parameter pack, so take the
2453        // deduced argument and place it on the argument pack. Note that we
2454        // stay on the same template parameter so that we can deduce more
2455        // arguments.
2456        ArgumentPack.push_back(Converted.back());
2457        Converted.pop_back();
2458      } else {
2459        // Move to the next template parameter.
2460        ++Param;
2461      }
2462      ++ArgIdx;
2463      continue;
2464    }
2465
2466    // If we have a template parameter pack with no more corresponding
2467    // arguments, just break out now and we'll fill in the argument pack below.
2468    if ((*Param)->isTemplateParameterPack())
2469      break;
2470
2471    // We have a default template argument that we will use.
2472    TemplateArgumentLoc Arg;
2473
2474    // Retrieve the default template argument from the template
2475    // parameter. For each kind of template parameter, we substitute the
2476    // template arguments provided thus far and any "outer" template arguments
2477    // (when the template parameter was part of a nested template) into
2478    // the default argument.
2479    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2480      if (!TTP->hasDefaultArgument()) {
2481        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2482        break;
2483      }
2484
2485      TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2486                                                             Template,
2487                                                             TemplateLoc,
2488                                                             RAngleLoc,
2489                                                             TTP,
2490                                                             Converted);
2491      if (!ArgType)
2492        return true;
2493
2494      Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2495                                ArgType);
2496    } else if (NonTypeTemplateParmDecl *NTTP
2497                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2498      if (!NTTP->hasDefaultArgument()) {
2499        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2500        break;
2501      }
2502
2503      ExprResult E = SubstDefaultTemplateArgument(*this, Template,
2504                                                              TemplateLoc,
2505                                                              RAngleLoc,
2506                                                              NTTP,
2507                                                              Converted);
2508      if (E.isInvalid())
2509        return true;
2510
2511      Expr *Ex = E.takeAs<Expr>();
2512      Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2513    } else {
2514      TemplateTemplateParmDecl *TempParm
2515        = cast<TemplateTemplateParmDecl>(*Param);
2516
2517      if (!TempParm->hasDefaultArgument()) {
2518        assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2519        break;
2520      }
2521
2522      TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2523                                                       TemplateLoc,
2524                                                       RAngleLoc,
2525                                                       TempParm,
2526                                                       Converted);
2527      if (Name.isNull())
2528        return true;
2529
2530      Arg = TemplateArgumentLoc(TemplateArgument(Name),
2531                  TempParm->getDefaultArgument().getTemplateQualifierRange(),
2532                  TempParm->getDefaultArgument().getTemplateNameLoc());
2533    }
2534
2535    // Introduce an instantiation record that describes where we are using
2536    // the default template argument.
2537    InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2538                                        Converted.data(), Converted.size(),
2539                                        SourceRange(TemplateLoc, RAngleLoc));
2540
2541    // Check the default template argument.
2542    if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2543                              RAngleLoc, Converted))
2544      return true;
2545
2546    // Move to the next template parameter and argument.
2547    ++Param;
2548    ++ArgIdx;
2549  }
2550
2551  // Form argument packs for each of the parameter packs remaining.
2552  while (Param != ParamEnd) {
2553    // If we're checking a partial list of template arguments, don't fill
2554    // in arguments for non-template parameter packs.
2555
2556    if ((*Param)->isTemplateParameterPack()) {
2557      if (PartialTemplateArgs && ArgumentPack.empty()) {
2558        Converted.push_back(TemplateArgument());
2559      } else if (ArgumentPack.empty())
2560        Converted.push_back(TemplateArgument(0, 0));
2561      else {
2562        Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2563                                                          ArgumentPack.data(),
2564                                                         ArgumentPack.size()));
2565        ArgumentPack.clear();
2566      }
2567    }
2568
2569    ++Param;
2570  }
2571
2572  return Invalid;
2573}
2574
2575namespace {
2576  class UnnamedLocalNoLinkageFinder
2577    : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2578  {
2579    Sema &S;
2580    SourceRange SR;
2581
2582    typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2583
2584  public:
2585    UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2586
2587    bool Visit(QualType T) {
2588      return inherited::Visit(T.getTypePtr());
2589    }
2590
2591#define TYPE(Class, Parent) \
2592    bool Visit##Class##Type(const Class##Type *);
2593#define ABSTRACT_TYPE(Class, Parent) \
2594    bool Visit##Class##Type(const Class##Type *) { return false; }
2595#define NON_CANONICAL_TYPE(Class, Parent) \
2596    bool Visit##Class##Type(const Class##Type *) { return false; }
2597#include "clang/AST/TypeNodes.def"
2598
2599    bool VisitTagDecl(const TagDecl *Tag);
2600    bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2601  };
2602}
2603
2604bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2605  return false;
2606}
2607
2608bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2609  return Visit(T->getElementType());
2610}
2611
2612bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2613  return Visit(T->getPointeeType());
2614}
2615
2616bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2617                                                    const BlockPointerType* T) {
2618  return Visit(T->getPointeeType());
2619}
2620
2621bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2622                                                const LValueReferenceType* T) {
2623  return Visit(T->getPointeeType());
2624}
2625
2626bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2627                                                const RValueReferenceType* T) {
2628  return Visit(T->getPointeeType());
2629}
2630
2631bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2632                                                  const MemberPointerType* T) {
2633  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2634}
2635
2636bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2637                                                  const ConstantArrayType* T) {
2638  return Visit(T->getElementType());
2639}
2640
2641bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2642                                                 const IncompleteArrayType* T) {
2643  return Visit(T->getElementType());
2644}
2645
2646bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2647                                                   const VariableArrayType* T) {
2648  return Visit(T->getElementType());
2649}
2650
2651bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2652                                            const DependentSizedArrayType* T) {
2653  return Visit(T->getElementType());
2654}
2655
2656bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2657                                         const DependentSizedExtVectorType* T) {
2658  return Visit(T->getElementType());
2659}
2660
2661bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2662  return Visit(T->getElementType());
2663}
2664
2665bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2666  return Visit(T->getElementType());
2667}
2668
2669bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2670                                                  const FunctionProtoType* T) {
2671  for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2672                                         AEnd = T->arg_type_end();
2673       A != AEnd; ++A) {
2674    if (Visit(*A))
2675      return true;
2676  }
2677
2678  return Visit(T->getResultType());
2679}
2680
2681bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2682                                               const FunctionNoProtoType* T) {
2683  return Visit(T->getResultType());
2684}
2685
2686bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2687                                                  const UnresolvedUsingType*) {
2688  return false;
2689}
2690
2691bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2692  return false;
2693}
2694
2695bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2696  return Visit(T->getUnderlyingType());
2697}
2698
2699bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2700  return false;
2701}
2702
2703bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2704  return VisitTagDecl(T->getDecl());
2705}
2706
2707bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2708  return VisitTagDecl(T->getDecl());
2709}
2710
2711bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2712                                                 const TemplateTypeParmType*) {
2713  return false;
2714}
2715
2716bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2717                                            const TemplateSpecializationType*) {
2718  return false;
2719}
2720
2721bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2722                                              const InjectedClassNameType* T) {
2723  return VisitTagDecl(T->getDecl());
2724}
2725
2726bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2727                                                   const DependentNameType* T) {
2728  return VisitNestedNameSpecifier(T->getQualifier());
2729}
2730
2731bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2732                                 const DependentTemplateSpecializationType* T) {
2733  return VisitNestedNameSpecifier(T->getQualifier());
2734}
2735
2736bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2737                                                   const PackExpansionType* T) {
2738  return Visit(T->getPattern());
2739}
2740
2741bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2742  return false;
2743}
2744
2745bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2746                                                   const ObjCInterfaceType *) {
2747  return false;
2748}
2749
2750bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2751                                                const ObjCObjectPointerType *) {
2752  return false;
2753}
2754
2755bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2756  if (Tag->getDeclContext()->isFunctionOrMethod()) {
2757    S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2758      << S.Context.getTypeDeclType(Tag) << SR;
2759    return true;
2760  }
2761
2762  if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2763    S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2764    S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2765    return true;
2766  }
2767
2768  return false;
2769}
2770
2771bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2772                                                    NestedNameSpecifier *NNS) {
2773  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2774    return true;
2775
2776  switch (NNS->getKind()) {
2777  case NestedNameSpecifier::Identifier:
2778  case NestedNameSpecifier::Namespace:
2779  case NestedNameSpecifier::Global:
2780    return false;
2781
2782  case NestedNameSpecifier::TypeSpec:
2783  case NestedNameSpecifier::TypeSpecWithTemplate:
2784    return Visit(QualType(NNS->getAsType(), 0));
2785  }
2786  return false;
2787}
2788
2789
2790/// \brief Check a template argument against its corresponding
2791/// template type parameter.
2792///
2793/// This routine implements the semantics of C++ [temp.arg.type]. It
2794/// returns true if an error occurred, and false otherwise.
2795bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2796                                 TypeSourceInfo *ArgInfo) {
2797  assert(ArgInfo && "invalid TypeSourceInfo");
2798  QualType Arg = ArgInfo->getType();
2799  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2800
2801  if (Arg->isVariablyModifiedType()) {
2802    return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
2803  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2804    return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2805  }
2806
2807  // C++03 [temp.arg.type]p2:
2808  //   A local type, a type with no linkage, an unnamed type or a type
2809  //   compounded from any of these types shall not be used as a
2810  //   template-argument for a template type-parameter.
2811  //
2812  // C++0x allows these, and even in C++03 we allow them as an extension with
2813  // a warning.
2814  if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
2815    UnnamedLocalNoLinkageFinder Finder(*this, SR);
2816    (void)Finder.Visit(Context.getCanonicalType(Arg));
2817  }
2818
2819  return false;
2820}
2821
2822/// \brief Checks whether the given template argument is the address
2823/// of an object or function according to C++ [temp.arg.nontype]p1.
2824static bool
2825CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2826                                               NonTypeTemplateParmDecl *Param,
2827                                               QualType ParamType,
2828                                               Expr *ArgIn,
2829                                               TemplateArgument &Converted) {
2830  bool Invalid = false;
2831  Expr *Arg = ArgIn;
2832  QualType ArgType = Arg->getType();
2833
2834  // See through any implicit casts we added to fix the type.
2835  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2836    Arg = Cast->getSubExpr();
2837
2838  // C++ [temp.arg.nontype]p1:
2839  //
2840  //   A template-argument for a non-type, non-template
2841  //   template-parameter shall be one of: [...]
2842  //
2843  //     -- the address of an object or function with external
2844  //        linkage, including function templates and function
2845  //        template-ids but excluding non-static class members,
2846  //        expressed as & id-expression where the & is optional if
2847  //        the name refers to a function or array, or if the
2848  //        corresponding template-parameter is a reference; or
2849  DeclRefExpr *DRE = 0;
2850
2851  // In C++98/03 mode, give an extension warning on any extra parentheses.
2852  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2853  bool ExtraParens = false;
2854  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2855    if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
2856      S.Diag(Arg->getSourceRange().getBegin(),
2857             diag::ext_template_arg_extra_parens)
2858        << Arg->getSourceRange();
2859      ExtraParens = true;
2860    }
2861
2862    Arg = Parens->getSubExpr();
2863  }
2864
2865  bool AddressTaken = false;
2866  SourceLocation AddrOpLoc;
2867  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2868    if (UnOp->getOpcode() == UO_AddrOf) {
2869      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2870      AddressTaken = true;
2871      AddrOpLoc = UnOp->getOperatorLoc();
2872    }
2873  } else
2874    DRE = dyn_cast<DeclRefExpr>(Arg);
2875
2876  if (!DRE) {
2877    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2878      << Arg->getSourceRange();
2879    S.Diag(Param->getLocation(), diag::note_template_param_here);
2880    return true;
2881  }
2882
2883  // Stop checking the precise nature of the argument if it is value dependent,
2884  // it should be checked when instantiated.
2885  if (Arg->isValueDependent()) {
2886    Converted = TemplateArgument(ArgIn);
2887    return false;
2888  }
2889
2890  if (!isa<ValueDecl>(DRE->getDecl())) {
2891    S.Diag(Arg->getSourceRange().getBegin(),
2892           diag::err_template_arg_not_object_or_func_form)
2893      << Arg->getSourceRange();
2894    S.Diag(Param->getLocation(), diag::note_template_param_here);
2895    return true;
2896  }
2897
2898  NamedDecl *Entity = 0;
2899
2900  // Cannot refer to non-static data members
2901  if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2902    S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2903      << Field << Arg->getSourceRange();
2904    S.Diag(Param->getLocation(), diag::note_template_param_here);
2905    return true;
2906  }
2907
2908  // Cannot refer to non-static member functions
2909  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2910    if (!Method->isStatic()) {
2911      S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
2912        << Method << Arg->getSourceRange();
2913      S.Diag(Param->getLocation(), diag::note_template_param_here);
2914      return true;
2915    }
2916
2917  // Functions must have external linkage.
2918  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2919    if (!isExternalLinkage(Func->getLinkage())) {
2920      S.Diag(Arg->getSourceRange().getBegin(),
2921             diag::err_template_arg_function_not_extern)
2922        << Func << Arg->getSourceRange();
2923      S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2924        << true;
2925      return true;
2926    }
2927
2928    // Okay: we've named a function with external linkage.
2929    Entity = Func;
2930
2931    // If the template parameter has pointer type, the function decays.
2932    if (ParamType->isPointerType() && !AddressTaken)
2933      ArgType = S.Context.getPointerType(Func->getType());
2934    else if (AddressTaken && ParamType->isReferenceType()) {
2935      // If we originally had an address-of operator, but the
2936      // parameter has reference type, complain and (if things look
2937      // like they will work) drop the address-of operator.
2938      if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2939                                            ParamType.getNonReferenceType())) {
2940        S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2941          << ParamType;
2942        S.Diag(Param->getLocation(), diag::note_template_param_here);
2943        return true;
2944      }
2945
2946      S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2947        << ParamType
2948        << FixItHint::CreateRemoval(AddrOpLoc);
2949      S.Diag(Param->getLocation(), diag::note_template_param_here);
2950
2951      ArgType = Func->getType();
2952    }
2953  } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2954    if (!isExternalLinkage(Var->getLinkage())) {
2955      S.Diag(Arg->getSourceRange().getBegin(),
2956             diag::err_template_arg_object_not_extern)
2957        << Var << Arg->getSourceRange();
2958      S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2959        << true;
2960      return true;
2961    }
2962
2963    // A value of reference type is not an object.
2964    if (Var->getType()->isReferenceType()) {
2965      S.Diag(Arg->getSourceRange().getBegin(),
2966             diag::err_template_arg_reference_var)
2967        << Var->getType() << Arg->getSourceRange();
2968      S.Diag(Param->getLocation(), diag::note_template_param_here);
2969      return true;
2970    }
2971
2972    // Okay: we've named an object with external linkage
2973    Entity = Var;
2974
2975    // If the template parameter has pointer type, we must have taken
2976    // the address of this object.
2977    if (ParamType->isReferenceType()) {
2978      if (AddressTaken) {
2979        // If we originally had an address-of operator, but the
2980        // parameter has reference type, complain and (if things look
2981        // like they will work) drop the address-of operator.
2982        if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2983                                            ParamType.getNonReferenceType())) {
2984          S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2985            << ParamType;
2986          S.Diag(Param->getLocation(), diag::note_template_param_here);
2987          return true;
2988        }
2989
2990        S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2991          << ParamType
2992          << FixItHint::CreateRemoval(AddrOpLoc);
2993        S.Diag(Param->getLocation(), diag::note_template_param_here);
2994
2995        ArgType = Var->getType();
2996      }
2997    } else if (!AddressTaken && ParamType->isPointerType()) {
2998      if (Var->getType()->isArrayType()) {
2999        // Array-to-pointer decay.
3000        ArgType = S.Context.getArrayDecayedType(Var->getType());
3001      } else {
3002        // If the template parameter has pointer type but the address of
3003        // this object was not taken, complain and (possibly) recover by
3004        // taking the address of the entity.
3005        ArgType = S.Context.getPointerType(Var->getType());
3006        if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3007          S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3008            << ParamType;
3009          S.Diag(Param->getLocation(), diag::note_template_param_here);
3010          return true;
3011        }
3012
3013        S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3014          << ParamType
3015          << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3016
3017        S.Diag(Param->getLocation(), diag::note_template_param_here);
3018      }
3019    }
3020  } else {
3021    // We found something else, but we don't know specifically what it is.
3022    S.Diag(Arg->getSourceRange().getBegin(),
3023           diag::err_template_arg_not_object_or_func)
3024      << Arg->getSourceRange();
3025    S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3026    return true;
3027  }
3028
3029  if (ParamType->isPointerType() &&
3030      !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3031      S.IsQualificationConversion(ArgType, ParamType)) {
3032    // For pointer-to-object types, qualification conversions are
3033    // permitted.
3034  } else {
3035    if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3036      if (!ParamRef->getPointeeType()->isFunctionType()) {
3037        // C++ [temp.arg.nontype]p5b3:
3038        //   For a non-type template-parameter of type reference to
3039        //   object, no conversions apply. The type referred to by the
3040        //   reference may be more cv-qualified than the (otherwise
3041        //   identical) type of the template- argument. The
3042        //   template-parameter is bound directly to the
3043        //   template-argument, which shall be an lvalue.
3044
3045        // FIXME: Other qualifiers?
3046        unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3047        unsigned ArgQuals = ArgType.getCVRQualifiers();
3048
3049        if ((ParamQuals | ArgQuals) != ParamQuals) {
3050          S.Diag(Arg->getSourceRange().getBegin(),
3051                 diag::err_template_arg_ref_bind_ignores_quals)
3052            << ParamType << Arg->getType()
3053            << Arg->getSourceRange();
3054          S.Diag(Param->getLocation(), diag::note_template_param_here);
3055          return true;
3056        }
3057      }
3058    }
3059
3060    // At this point, the template argument refers to an object or
3061    // function with external linkage. We now need to check whether the
3062    // argument and parameter types are compatible.
3063    if (!S.Context.hasSameUnqualifiedType(ArgType,
3064                                          ParamType.getNonReferenceType())) {
3065      // We can't perform this conversion or binding.
3066      if (ParamType->isReferenceType())
3067        S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3068          << ParamType << Arg->getType() << Arg->getSourceRange();
3069      else
3070        S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
3071          << Arg->getType() << ParamType << Arg->getSourceRange();
3072      S.Diag(Param->getLocation(), diag::note_template_param_here);
3073      return true;
3074    }
3075  }
3076
3077  // Create the template argument.
3078  Converted = TemplateArgument(Entity->getCanonicalDecl());
3079  S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
3080  return false;
3081}
3082
3083/// \brief Checks whether the given template argument is a pointer to
3084/// member constant according to C++ [temp.arg.nontype]p1.
3085bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3086                                                TemplateArgument &Converted) {
3087  bool Invalid = false;
3088
3089  // See through any implicit casts we added to fix the type.
3090  while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
3091    Arg = Cast->getSubExpr();
3092
3093  // C++ [temp.arg.nontype]p1:
3094  //
3095  //   A template-argument for a non-type, non-template
3096  //   template-parameter shall be one of: [...]
3097  //
3098  //     -- a pointer to member expressed as described in 5.3.1.
3099  DeclRefExpr *DRE = 0;
3100
3101  // In C++98/03 mode, give an extension warning on any extra parentheses.
3102  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3103  bool ExtraParens = false;
3104  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3105    if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
3106      Diag(Arg->getSourceRange().getBegin(),
3107           diag::ext_template_arg_extra_parens)
3108        << Arg->getSourceRange();
3109      ExtraParens = true;
3110    }
3111
3112    Arg = Parens->getSubExpr();
3113  }
3114
3115  // A pointer-to-member constant written &Class::member.
3116  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3117    if (UnOp->getOpcode() == UO_AddrOf) {
3118      DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3119      if (DRE && !DRE->getQualifier())
3120        DRE = 0;
3121    }
3122  }
3123  // A constant of pointer-to-member type.
3124  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3125    if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3126      if (VD->getType()->isMemberPointerType()) {
3127        if (isa<NonTypeTemplateParmDecl>(VD) ||
3128            (isa<VarDecl>(VD) &&
3129             Context.getCanonicalType(VD->getType()).isConstQualified())) {
3130          if (Arg->isTypeDependent() || Arg->isValueDependent())
3131            Converted = TemplateArgument(Arg);
3132          else
3133            Converted = TemplateArgument(VD->getCanonicalDecl());
3134          return Invalid;
3135        }
3136      }
3137    }
3138
3139    DRE = 0;
3140  }
3141
3142  if (!DRE)
3143    return Diag(Arg->getSourceRange().getBegin(),
3144                diag::err_template_arg_not_pointer_to_member_form)
3145      << Arg->getSourceRange();
3146
3147  if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3148    assert((isa<FieldDecl>(DRE->getDecl()) ||
3149            !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3150           "Only non-static member pointers can make it here");
3151
3152    // Okay: this is the address of a non-static member, and therefore
3153    // a member pointer constant.
3154    if (Arg->isTypeDependent() || Arg->isValueDependent())
3155      Converted = TemplateArgument(Arg);
3156    else
3157      Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
3158    return Invalid;
3159  }
3160
3161  // We found something else, but we don't know specifically what it is.
3162  Diag(Arg->getSourceRange().getBegin(),
3163       diag::err_template_arg_not_pointer_to_member_form)
3164      << Arg->getSourceRange();
3165  Diag(DRE->getDecl()->getLocation(),
3166       diag::note_template_arg_refers_here);
3167  return true;
3168}
3169
3170/// \brief Check a template argument against its corresponding
3171/// non-type template parameter.
3172///
3173/// This routine implements the semantics of C++ [temp.arg.nontype].
3174/// It returns true if an error occurred, and false otherwise. \p
3175/// InstantiatedParamType is the type of the non-type template
3176/// parameter after it has been instantiated.
3177///
3178/// If no error was detected, Converted receives the converted template argument.
3179bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3180                                 QualType InstantiatedParamType, Expr *&Arg,
3181                                 TemplateArgument &Converted,
3182                                 CheckTemplateArgumentKind CTAK) {
3183  SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3184
3185  // If either the parameter has a dependent type or the argument is
3186  // type-dependent, there's nothing we can check now.
3187  if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3188    // FIXME: Produce a cloned, canonical expression?
3189    Converted = TemplateArgument(Arg);
3190    return false;
3191  }
3192
3193  // C++ [temp.arg.nontype]p5:
3194  //   The following conversions are performed on each expression used
3195  //   as a non-type template-argument. If a non-type
3196  //   template-argument cannot be converted to the type of the
3197  //   corresponding template-parameter then the program is
3198  //   ill-formed.
3199  //
3200  //     -- for a non-type template-parameter of integral or
3201  //        enumeration type, integral promotions (4.5) and integral
3202  //        conversions (4.7) are applied.
3203  QualType ParamType = InstantiatedParamType;
3204  QualType ArgType = Arg->getType();
3205  if (ParamType->isIntegralOrEnumerationType()) {
3206    // C++ [temp.arg.nontype]p1:
3207    //   A template-argument for a non-type, non-template
3208    //   template-parameter shall be one of:
3209    //
3210    //     -- an integral constant-expression of integral or enumeration
3211    //        type; or
3212    //     -- the name of a non-type template-parameter; or
3213    SourceLocation NonConstantLoc;
3214    llvm::APSInt Value;
3215    if (!ArgType->isIntegralOrEnumerationType()) {
3216      Diag(Arg->getSourceRange().getBegin(),
3217           diag::err_template_arg_not_integral_or_enumeral)
3218        << ArgType << Arg->getSourceRange();
3219      Diag(Param->getLocation(), diag::note_template_param_here);
3220      return true;
3221    } else if (!Arg->isValueDependent() &&
3222               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
3223      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3224        << ArgType << Arg->getSourceRange();
3225      return true;
3226    }
3227
3228    // From here on out, all we care about are the unqualified forms
3229    // of the parameter and argument types.
3230    ParamType = ParamType.getUnqualifiedType();
3231    ArgType = ArgType.getUnqualifiedType();
3232
3233    // Try to convert the argument to the parameter's type.
3234    if (Context.hasSameType(ParamType, ArgType)) {
3235      // Okay: no conversion necessary
3236    } else if (CTAK == CTAK_Deduced) {
3237      // C++ [temp.deduct.type]p17:
3238      //   If, in the declaration of a function template with a non-type
3239      //   template-parameter, the non-type template- parameter is used
3240      //   in an expression in the function parameter-list and, if the
3241      //   corresponding template-argument is deduced, the
3242      //   template-argument type shall match the type of the
3243      //   template-parameter exactly, except that a template-argument
3244      //   deduced from an array bound may be of any integral type.
3245      Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3246        << ArgType << ParamType;
3247      Diag(Param->getLocation(), diag::note_template_param_here);
3248      return true;
3249    } else if (ParamType->isBooleanType()) {
3250      // This is an integral-to-boolean conversion.
3251      ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
3252    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3253               !ParamType->isEnumeralType()) {
3254      // This is an integral promotion or conversion.
3255      ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
3256    } else {
3257      // We can't perform this conversion.
3258      Diag(Arg->getSourceRange().getBegin(),
3259           diag::err_template_arg_not_convertible)
3260        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3261      Diag(Param->getLocation(), diag::note_template_param_here);
3262      return true;
3263    }
3264
3265    QualType IntegerType = Context.getCanonicalType(ParamType);
3266    if (const EnumType *Enum = IntegerType->getAs<EnumType>())
3267      IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
3268
3269    if (!Arg->isValueDependent()) {
3270      llvm::APSInt OldValue = Value;
3271
3272      // Coerce the template argument's value to the value it will have
3273      // based on the template parameter's type.
3274      unsigned AllowedBits = Context.getTypeSize(IntegerType);
3275      if (Value.getBitWidth() != AllowedBits)
3276        Value = Value.extOrTrunc(AllowedBits);
3277      Value.setIsSigned(IntegerType->isSignedIntegerType());
3278
3279      // Complain if an unsigned parameter received a negative value.
3280      if (IntegerType->isUnsignedIntegerType()
3281          && (OldValue.isSigned() && OldValue.isNegative())) {
3282        Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3283          << OldValue.toString(10) << Value.toString(10) << Param->getType()
3284          << Arg->getSourceRange();
3285        Diag(Param->getLocation(), diag::note_template_param_here);
3286      }
3287
3288      // Complain if we overflowed the template parameter's type.
3289      unsigned RequiredBits;
3290      if (IntegerType->isUnsignedIntegerType())
3291        RequiredBits = OldValue.getActiveBits();
3292      else if (OldValue.isUnsigned())
3293        RequiredBits = OldValue.getActiveBits() + 1;
3294      else
3295        RequiredBits = OldValue.getMinSignedBits();
3296      if (RequiredBits > AllowedBits) {
3297        Diag(Arg->getSourceRange().getBegin(),
3298             diag::warn_template_arg_too_large)
3299          << OldValue.toString(10) << Value.toString(10) << Param->getType()
3300          << Arg->getSourceRange();
3301        Diag(Param->getLocation(), diag::note_template_param_here);
3302      }
3303    }
3304
3305    // Add the value of this argument to the list of converted
3306    // arguments. We use the bitwidth and signedness of the template
3307    // parameter.
3308    if (Arg->isValueDependent()) {
3309      // The argument is value-dependent. Create a new
3310      // TemplateArgument with the converted expression.
3311      Converted = TemplateArgument(Arg);
3312      return false;
3313    }
3314
3315    Converted = TemplateArgument(Value,
3316                                 ParamType->isEnumeralType() ? ParamType
3317                                                             : IntegerType);
3318    return false;
3319  }
3320
3321  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3322
3323  // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3324  // from a template argument of type std::nullptr_t to a non-type
3325  // template parameter of type pointer to object, pointer to
3326  // function, or pointer-to-member, respectively.
3327  if (ArgType->isNullPtrType() &&
3328      (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3329    Converted = TemplateArgument((NamedDecl *)0);
3330    return false;
3331  }
3332
3333  // Handle pointer-to-function, reference-to-function, and
3334  // pointer-to-member-function all in (roughly) the same way.
3335  if (// -- For a non-type template-parameter of type pointer to
3336      //    function, only the function-to-pointer conversion (4.3) is
3337      //    applied. If the template-argument represents a set of
3338      //    overloaded functions (or a pointer to such), the matching
3339      //    function is selected from the set (13.4).
3340      (ParamType->isPointerType() &&
3341       ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
3342      // -- For a non-type template-parameter of type reference to
3343      //    function, no conversions apply. If the template-argument
3344      //    represents a set of overloaded functions, the matching
3345      //    function is selected from the set (13.4).
3346      (ParamType->isReferenceType() &&
3347       ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
3348      // -- For a non-type template-parameter of type pointer to
3349      //    member function, no conversions apply. If the
3350      //    template-argument represents a set of overloaded member
3351      //    functions, the matching member function is selected from
3352      //    the set (13.4).
3353      (ParamType->isMemberPointerType() &&
3354       ParamType->getAs<MemberPointerType>()->getPointeeType()
3355         ->isFunctionType())) {
3356
3357    if (Arg->getType() == Context.OverloadTy) {
3358      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3359                                                                true,
3360                                                                FoundResult)) {
3361        if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3362          return true;
3363
3364        Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3365        ArgType = Arg->getType();
3366      } else
3367        return true;
3368    }
3369
3370    if (!ParamType->isMemberPointerType())
3371      return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3372                                                            ParamType,
3373                                                            Arg, Converted);
3374
3375    if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
3376      ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
3377    } else if (!Context.hasSameUnqualifiedType(ArgType,
3378                                           ParamType.getNonReferenceType())) {
3379      // We can't perform this conversion.
3380      Diag(Arg->getSourceRange().getBegin(),
3381           diag::err_template_arg_not_convertible)
3382        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3383      Diag(Param->getLocation(), diag::note_template_param_here);
3384      return true;
3385    }
3386
3387    return CheckTemplateArgumentPointerToMember(Arg, Converted);
3388  }
3389
3390  if (ParamType->isPointerType()) {
3391    //   -- for a non-type template-parameter of type pointer to
3392    //      object, qualification conversions (4.4) and the
3393    //      array-to-pointer conversion (4.2) are applied.
3394    // C++0x also allows a value of std::nullptr_t.
3395    assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
3396           "Only object pointers allowed here");
3397
3398    return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3399                                                          ParamType,
3400                                                          Arg, Converted);
3401  }
3402
3403  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
3404    //   -- For a non-type template-parameter of type reference to
3405    //      object, no conversions apply. The type referred to by the
3406    //      reference may be more cv-qualified than the (otherwise
3407    //      identical) type of the template-argument. The
3408    //      template-parameter is bound directly to the
3409    //      template-argument, which must be an lvalue.
3410    assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
3411           "Only object references allowed here");
3412
3413    if (Arg->getType() == Context.OverloadTy) {
3414      if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3415                                                 ParamRefType->getPointeeType(),
3416                                                                true,
3417                                                                FoundResult)) {
3418        if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3419          return true;
3420
3421        Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3422        ArgType = Arg->getType();
3423      } else
3424        return true;
3425    }
3426
3427    return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3428                                                          ParamType,
3429                                                          Arg, Converted);
3430  }
3431
3432  //     -- For a non-type template-parameter of type pointer to data
3433  //        member, qualification conversions (4.4) are applied.
3434  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3435
3436  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
3437    // Types match exactly: nothing more to do here.
3438  } else if (IsQualificationConversion(ArgType, ParamType)) {
3439    ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
3440  } else {
3441    // We can't perform this conversion.
3442    Diag(Arg->getSourceRange().getBegin(),
3443         diag::err_template_arg_not_convertible)
3444      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3445    Diag(Param->getLocation(), diag::note_template_param_here);
3446    return true;
3447  }
3448
3449  return CheckTemplateArgumentPointerToMember(Arg, Converted);
3450}
3451
3452/// \brief Check a template argument against its corresponding
3453/// template template parameter.
3454///
3455/// This routine implements the semantics of C++ [temp.arg.template].
3456/// It returns true if an error occurred, and false otherwise.
3457bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3458                                 const TemplateArgumentLoc &Arg) {
3459  TemplateName Name = Arg.getArgument().getAsTemplate();
3460  TemplateDecl *Template = Name.getAsTemplateDecl();
3461  if (!Template) {
3462    // Any dependent template name is fine.
3463    assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3464    return false;
3465  }
3466
3467  // C++ [temp.arg.template]p1:
3468  //   A template-argument for a template template-parameter shall be
3469  //   the name of a class template, expressed as id-expression. Only
3470  //   primary class templates are considered when matching the
3471  //   template template argument with the corresponding parameter;
3472  //   partial specializations are not considered even if their
3473  //   parameter lists match that of the template template parameter.
3474  //
3475  // Note that we also allow template template parameters here, which
3476  // will happen when we are dealing with, e.g., class template
3477  // partial specializations.
3478  if (!isa<ClassTemplateDecl>(Template) &&
3479      !isa<TemplateTemplateParmDecl>(Template)) {
3480    assert(isa<FunctionTemplateDecl>(Template) &&
3481           "Only function templates are possible here");
3482    Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
3483    Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
3484      << Template;
3485  }
3486
3487  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3488                                         Param->getTemplateParameters(),
3489                                         true,
3490                                         TPL_TemplateTemplateArgumentMatch,
3491                                         Arg.getLocation());
3492}
3493
3494/// \brief Given a non-type template argument that refers to a
3495/// declaration and the type of its corresponding non-type template
3496/// parameter, produce an expression that properly refers to that
3497/// declaration.
3498ExprResult
3499Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3500                                              QualType ParamType,
3501                                              SourceLocation Loc) {
3502  assert(Arg.getKind() == TemplateArgument::Declaration &&
3503         "Only declaration template arguments permitted here");
3504  ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3505
3506  if (VD->getDeclContext()->isRecord() &&
3507      (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3508    // If the value is a class member, we might have a pointer-to-member.
3509    // Determine whether the non-type template template parameter is of
3510    // pointer-to-member type. If so, we need to build an appropriate
3511    // expression for a pointer-to-member, since a "normal" DeclRefExpr
3512    // would refer to the member itself.
3513    if (ParamType->isMemberPointerType()) {
3514      QualType ClassType
3515        = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3516      NestedNameSpecifier *Qualifier
3517        = NestedNameSpecifier::Create(Context, 0, false,
3518                                      ClassType.getTypePtr());
3519      CXXScopeSpec SS;
3520      SS.setScopeRep(Qualifier);
3521
3522      // The actual value-ness of this is unimportant, but for
3523      // internal consistency's sake, references to instance methods
3524      // are r-values.
3525      ExprValueKind VK = VK_LValue;
3526      if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3527        VK = VK_RValue;
3528
3529      ExprResult RefExpr = BuildDeclRefExpr(VD,
3530                                            VD->getType().getNonReferenceType(),
3531                                            VK,
3532                                            Loc,
3533                                            &SS);
3534      if (RefExpr.isInvalid())
3535        return ExprError();
3536
3537      RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
3538
3539      // We might need to perform a trailing qualification conversion, since
3540      // the element type on the parameter could be more qualified than the
3541      // element type in the expression we constructed.
3542      if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3543                                    ParamType.getUnqualifiedType())) {
3544        Expr *RefE = RefExpr.takeAs<Expr>();
3545        ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
3546        RefExpr = Owned(RefE);
3547      }
3548
3549      assert(!RefExpr.isInvalid() &&
3550             Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3551                                 ParamType.getUnqualifiedType()));
3552      return move(RefExpr);
3553    }
3554  }
3555
3556  QualType T = VD->getType().getNonReferenceType();
3557  if (ParamType->isPointerType()) {
3558    // When the non-type template parameter is a pointer, take the
3559    // address of the declaration.
3560    ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
3561    if (RefExpr.isInvalid())
3562      return ExprError();
3563
3564    if (T->isFunctionType() || T->isArrayType()) {
3565      // Decay functions and arrays.
3566      Expr *RefE = (Expr *)RefExpr.get();
3567      DefaultFunctionArrayConversion(RefE);
3568      if (RefE != RefExpr.get()) {
3569        RefExpr.release();
3570        RefExpr = Owned(RefE);
3571      }
3572
3573      return move(RefExpr);
3574    }
3575
3576    // Take the address of everything else
3577    return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
3578  }
3579
3580  ExprValueKind VK = VK_RValue;
3581
3582  // If the non-type template parameter has reference type, qualify the
3583  // resulting declaration reference with the extra qualifiers on the
3584  // type that the reference refers to.
3585  if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3586    VK = VK_LValue;
3587    T = Context.getQualifiedType(T,
3588                              TargetRef->getPointeeType().getQualifiers());
3589  }
3590
3591  return BuildDeclRefExpr(VD, T, VK, Loc);
3592}
3593
3594/// \brief Construct a new expression that refers to the given
3595/// integral template argument with the given source-location
3596/// information.
3597///
3598/// This routine takes care of the mapping from an integral template
3599/// argument (which may have any integral type) to the appropriate
3600/// literal value.
3601ExprResult
3602Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3603                                                  SourceLocation Loc) {
3604  assert(Arg.getKind() == TemplateArgument::Integral &&
3605         "Operation is only valid for integral template arguments");
3606  QualType T = Arg.getIntegralType();
3607  if (T->isCharType() || T->isWideCharType())
3608    return Owned(new (Context) CharacterLiteral(
3609                                             Arg.getAsIntegral()->getZExtValue(),
3610                                             T->isWideCharType(),
3611                                             T,
3612                                             Loc));
3613  if (T->isBooleanType())
3614    return Owned(new (Context) CXXBoolLiteralExpr(
3615                                            Arg.getAsIntegral()->getBoolValue(),
3616                                            T,
3617                                            Loc));
3618
3619  QualType BT;
3620  if (const EnumType *ET = T->getAs<EnumType>())
3621    BT = ET->getDecl()->getPromotionType();
3622  else
3623    BT = T;
3624
3625  Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3626  ImpCastExprToType(E, T, CK_IntegralCast);
3627
3628  return Owned(E);
3629}
3630
3631/// \brief Match two template parameters within template parameter lists.
3632static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
3633                                       bool Complain,
3634                                     Sema::TemplateParameterListEqualKind Kind,
3635                                       SourceLocation TemplateArgLoc) {
3636  // Check the actual kind (type, non-type, template).
3637  if (Old->getKind() != New->getKind()) {
3638    if (Complain) {
3639      unsigned NextDiag = diag::err_template_param_different_kind;
3640      if (TemplateArgLoc.isValid()) {
3641        S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3642        NextDiag = diag::note_template_param_different_kind;
3643      }
3644      S.Diag(New->getLocation(), NextDiag)
3645        << (Kind != Sema::TPL_TemplateMatch);
3646      S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
3647        << (Kind != Sema::TPL_TemplateMatch);
3648    }
3649
3650    return false;
3651  }
3652
3653  // Check that both are parameter packs are neither are parameter packs.
3654  // However, if we are matching a template template argument to a
3655  // template template parameter, the template template parameter can have
3656  // a parameter pack where the template template argument does not.
3657  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
3658      !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3659        Old->isTemplateParameterPack())) {
3660    if (Complain) {
3661      unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3662      if (TemplateArgLoc.isValid()) {
3663        S.Diag(TemplateArgLoc,
3664             diag::err_template_arg_template_params_mismatch);
3665        NextDiag = diag::note_template_parameter_pack_non_pack;
3666      }
3667
3668      unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
3669                      : isa<NonTypeTemplateParmDecl>(New)? 1
3670                      : 2;
3671      S.Diag(New->getLocation(), NextDiag)
3672        << ParamKind << New->isParameterPack();
3673      S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
3674        << ParamKind << Old->isParameterPack();
3675    }
3676
3677    return false;
3678  }
3679
3680  // For non-type template parameters, check the type of the parameter.
3681  if (NonTypeTemplateParmDecl *OldNTTP
3682                                    = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
3683    NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
3684
3685    // If we are matching a template template argument to a template
3686    // template parameter and one of the non-type template parameter types
3687    // is dependent, then we must wait until template instantiation time
3688    // to actually compare the arguments.
3689    if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3690        (OldNTTP->getType()->isDependentType() ||
3691         NewNTTP->getType()->isDependentType()))
3692      return true;
3693
3694    if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
3695      if (Complain) {
3696        unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3697        if (TemplateArgLoc.isValid()) {
3698          S.Diag(TemplateArgLoc,
3699                 diag::err_template_arg_template_params_mismatch);
3700          NextDiag = diag::note_template_nontype_parm_different_type;
3701        }
3702        S.Diag(NewNTTP->getLocation(), NextDiag)
3703          << NewNTTP->getType()
3704          << (Kind != Sema::TPL_TemplateMatch);
3705        S.Diag(OldNTTP->getLocation(),
3706               diag::note_template_nontype_parm_prev_declaration)
3707          << OldNTTP->getType();
3708      }
3709
3710      return false;
3711    }
3712
3713    return true;
3714  }
3715
3716  // For template template parameters, check the template parameter types.
3717  // The template parameter lists of template template
3718  // parameters must agree.
3719  if (TemplateTemplateParmDecl *OldTTP
3720                                    = dyn_cast<TemplateTemplateParmDecl>(Old)) {
3721    TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
3722    return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3723                                            OldTTP->getTemplateParameters(),
3724                                            Complain,
3725                                        (Kind == Sema::TPL_TemplateMatch
3726                                           ? Sema::TPL_TemplateTemplateParmMatch
3727                                           : Kind),
3728                                            TemplateArgLoc);
3729  }
3730
3731  return true;
3732}
3733
3734/// \brief Diagnose a known arity mismatch when comparing template argument
3735/// lists.
3736static
3737void DiagnoseTemplateParameterListArityMismatch(Sema &S,
3738                                                TemplateParameterList *New,
3739                                                TemplateParameterList *Old,
3740                                      Sema::TemplateParameterListEqualKind Kind,
3741                                                SourceLocation TemplateArgLoc) {
3742  unsigned NextDiag = diag::err_template_param_list_different_arity;
3743  if (TemplateArgLoc.isValid()) {
3744    S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3745    NextDiag = diag::note_template_param_list_different_arity;
3746  }
3747  S.Diag(New->getTemplateLoc(), NextDiag)
3748    << (New->size() > Old->size())
3749    << (Kind != Sema::TPL_TemplateMatch)
3750    << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
3751  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
3752    << (Kind != Sema::TPL_TemplateMatch)
3753    << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3754}
3755
3756/// \brief Determine whether the given template parameter lists are
3757/// equivalent.
3758///
3759/// \param New  The new template parameter list, typically written in the
3760/// source code as part of a new template declaration.
3761///
3762/// \param Old  The old template parameter list, typically found via
3763/// name lookup of the template declared with this template parameter
3764/// list.
3765///
3766/// \param Complain  If true, this routine will produce a diagnostic if
3767/// the template parameter lists are not equivalent.
3768///
3769/// \param Kind describes how we are to match the template parameter lists.
3770///
3771/// \param TemplateArgLoc If this source location is valid, then we
3772/// are actually checking the template parameter list of a template
3773/// argument (New) against the template parameter list of its
3774/// corresponding template template parameter (Old). We produce
3775/// slightly different diagnostics in this scenario.
3776///
3777/// \returns True if the template parameter lists are equal, false
3778/// otherwise.
3779bool
3780Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3781                                     TemplateParameterList *Old,
3782                                     bool Complain,
3783                                     TemplateParameterListEqualKind Kind,
3784                                     SourceLocation TemplateArgLoc) {
3785  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
3786    if (Complain)
3787      DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3788                                                 TemplateArgLoc);
3789
3790    return false;
3791  }
3792
3793  // C++0x [temp.arg.template]p3:
3794  //   A template-argument matches a template template-parameter (call it P)
3795  //   when each of the template parameters in the template-parameter-list of
3796  //   the template-argument’s corresponding class template or template alias
3797  //   (call it A) matches the corresponding template parameter in the
3798  //   template-parameter-list of P. [...]
3799  TemplateParameterList::iterator NewParm = New->begin();
3800  TemplateParameterList::iterator NewParmEnd = New->end();
3801  for (TemplateParameterList::iterator OldParm = Old->begin(),
3802                                    OldParmEnd = Old->end();
3803       OldParm != OldParmEnd; ++OldParm) {
3804    if (!(*OldParm)->isTemplateParameterPack()) {
3805      if (NewParm == NewParmEnd) {
3806        if (Complain)
3807          DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3808                                                     TemplateArgLoc);
3809
3810        return false;
3811      }
3812
3813      if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3814                                      Kind, TemplateArgLoc))
3815        return false;
3816
3817      ++NewParm;
3818      continue;
3819    }
3820
3821    // C++0x [temp.arg.template]p3:
3822    //   [...] When P’s template- parameter-list contains a template parameter
3823    //   pack (14.5.3), the template parameter pack will match zero or more
3824    //   template parameters or template parameter packs in the
3825    //   template-parameter-list of A with the same type and form as the
3826    //   template parameter pack in P (ignoring whether those template
3827    //   parameters are template parameter packs).
3828    for (; NewParm != NewParmEnd; ++NewParm) {
3829      if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3830                                      Kind, TemplateArgLoc))
3831        return false;
3832    }
3833  }
3834
3835  // Make sure we exhausted all of the arguments.
3836  if (NewParm != NewParmEnd) {
3837    if (Complain)
3838      DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3839                                                 TemplateArgLoc);
3840
3841    return false;
3842  }
3843
3844  return true;
3845}
3846
3847/// \brief Check whether a template can be declared within this scope.
3848///
3849/// If the template declaration is valid in this scope, returns
3850/// false. Otherwise, issues a diagnostic and returns true.
3851bool
3852Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
3853  // Find the nearest enclosing declaration scope.
3854  while ((S->getFlags() & Scope::DeclScope) == 0 ||
3855         (S->getFlags() & Scope::TemplateParamScope) != 0)
3856    S = S->getParent();
3857
3858  // C++ [temp]p2:
3859  //   A template-declaration can appear only as a namespace scope or
3860  //   class scope declaration.
3861  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
3862  if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3863      cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
3864    return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
3865             << TemplateParams->getSourceRange();
3866
3867  while (Ctx && isa<LinkageSpecDecl>(Ctx))
3868    Ctx = Ctx->getParent();
3869
3870  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3871    return false;
3872
3873  return Diag(TemplateParams->getTemplateLoc(),
3874              diag::err_template_outside_namespace_or_class_scope)
3875    << TemplateParams->getSourceRange();
3876}
3877
3878/// \brief Determine what kind of template specialization the given declaration
3879/// is.
3880static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3881  if (!D)
3882    return TSK_Undeclared;
3883
3884  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3885    return Record->getTemplateSpecializationKind();
3886  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3887    return Function->getTemplateSpecializationKind();
3888  if (VarDecl *Var = dyn_cast<VarDecl>(D))
3889    return Var->getTemplateSpecializationKind();
3890
3891  return TSK_Undeclared;
3892}
3893
3894/// \brief Check whether a specialization is well-formed in the current
3895/// context.
3896///
3897/// This routine determines whether a template specialization can be declared
3898/// in the current context (C++ [temp.expl.spec]p2).
3899///
3900/// \param S the semantic analysis object for which this check is being
3901/// performed.
3902///
3903/// \param Specialized the entity being specialized or instantiated, which
3904/// may be a kind of template (class template, function template, etc.) or
3905/// a member of a class template (member function, static data member,
3906/// member class).
3907///
3908/// \param PrevDecl the previous declaration of this entity, if any.
3909///
3910/// \param Loc the location of the explicit specialization or instantiation of
3911/// this entity.
3912///
3913/// \param IsPartialSpecialization whether this is a partial specialization of
3914/// a class template.
3915///
3916/// \returns true if there was an error that we cannot recover from, false
3917/// otherwise.
3918static bool CheckTemplateSpecializationScope(Sema &S,
3919                                             NamedDecl *Specialized,
3920                                             NamedDecl *PrevDecl,
3921                                             SourceLocation Loc,
3922                                             bool IsPartialSpecialization) {
3923  // Keep these "kind" numbers in sync with the %select statements in the
3924  // various diagnostics emitted by this routine.
3925  int EntityKind = 0;
3926  bool isTemplateSpecialization = false;
3927  if (isa<ClassTemplateDecl>(Specialized)) {
3928    EntityKind = IsPartialSpecialization? 1 : 0;
3929    isTemplateSpecialization = true;
3930  } else if (isa<FunctionTemplateDecl>(Specialized)) {
3931    EntityKind = 2;
3932    isTemplateSpecialization = true;
3933  } else if (isa<CXXMethodDecl>(Specialized))
3934    EntityKind = 3;
3935  else if (isa<VarDecl>(Specialized))
3936    EntityKind = 4;
3937  else if (isa<RecordDecl>(Specialized))
3938    EntityKind = 5;
3939  else {
3940    S.Diag(Loc, diag::err_template_spec_unknown_kind);
3941    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3942    return true;
3943  }
3944
3945  // C++ [temp.expl.spec]p2:
3946  //   An explicit specialization shall be declared in the namespace
3947  //   of which the template is a member, or, for member templates, in
3948  //   the namespace of which the enclosing class or enclosing class
3949  //   template is a member. An explicit specialization of a member
3950  //   function, member class or static data member of a class
3951  //   template shall be declared in the namespace of which the class
3952  //   template is a member. Such a declaration may also be a
3953  //   definition. If the declaration is not a definition, the
3954  //   specialization may be defined later in the name- space in which
3955  //   the explicit specialization was declared, or in a namespace
3956  //   that encloses the one in which the explicit specialization was
3957  //   declared.
3958  if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
3959    S.Diag(Loc, diag::err_template_spec_decl_function_scope)
3960      << Specialized;
3961    return true;
3962  }
3963
3964  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3965    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
3966      << Specialized;
3967    return true;
3968  }
3969
3970  // C++ [temp.class.spec]p6:
3971  //   A class template partial specialization may be declared or redeclared
3972  //   in any namespace scope in which its definition may be defined (14.5.1
3973  //   and 14.5.2).
3974  bool ComplainedAboutScope = false;
3975  DeclContext *SpecializedContext
3976    = Specialized->getDeclContext()->getEnclosingNamespaceContext();
3977  DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
3978  if ((!PrevDecl ||
3979       getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3980       getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3981    // C++ [temp.exp.spec]p2:
3982    //   An explicit specialization shall be declared in the namespace of which
3983    //   the template is a member, or, for member templates, in the namespace
3984    //   of which the enclosing class or enclosing class template is a member.
3985    //   An explicit specialization of a member function, member class or
3986    //   static data member of a class template shall be declared in the
3987    //   namespace of which the class template is a member.
3988    //
3989    // C++0x [temp.expl.spec]p2:
3990    //   An explicit specialization shall be declared in a namespace enclosing
3991    //   the specialized template.
3992    if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3993        !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
3994      bool IsCPlusPlus0xExtension
3995        = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
3996      if (isa<TranslationUnitDecl>(SpecializedContext))
3997        S.Diag(Loc, IsCPlusPlus0xExtension
3998                      ? diag::ext_template_spec_decl_out_of_scope_global
3999                      : diag::err_template_spec_decl_out_of_scope_global)
4000          << EntityKind << Specialized;
4001      else if (isa<NamespaceDecl>(SpecializedContext))
4002        S.Diag(Loc, IsCPlusPlus0xExtension
4003                      ? diag::ext_template_spec_decl_out_of_scope
4004                      : diag::err_template_spec_decl_out_of_scope)
4005          << EntityKind << Specialized
4006          << cast<NamedDecl>(SpecializedContext);
4007
4008      S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4009      ComplainedAboutScope = true;
4010    }
4011  }
4012
4013  // Make sure that this redeclaration (or definition) occurs in an enclosing
4014  // namespace.
4015  // Note that HandleDeclarator() performs this check for explicit
4016  // specializations of function templates, static data members, and member
4017  // functions, so we skip the check here for those kinds of entities.
4018  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
4019  // Should we refactor that check, so that it occurs later?
4020  if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
4021      !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4022        isa<FunctionDecl>(Specialized))) {
4023    if (isa<TranslationUnitDecl>(SpecializedContext))
4024      S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4025        << EntityKind << Specialized;
4026    else if (isa<NamespaceDecl>(SpecializedContext))
4027      S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4028        << EntityKind << Specialized
4029        << cast<NamedDecl>(SpecializedContext);
4030
4031    S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4032  }
4033
4034  // FIXME: check for specialization-after-instantiation errors and such.
4035
4036  return false;
4037}
4038
4039/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4040/// that checks non-type template partial specialization arguments.
4041static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4042                                                NonTypeTemplateParmDecl *Param,
4043                                                  const TemplateArgument *Args,
4044                                                        unsigned NumArgs) {
4045  for (unsigned I = 0; I != NumArgs; ++I) {
4046    if (Args[I].getKind() == TemplateArgument::Pack) {
4047      if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4048                                                           Args[I].pack_begin(),
4049                                                           Args[I].pack_size()))
4050        return true;
4051
4052      continue;
4053    }
4054
4055    Expr *ArgExpr = Args[I].getAsExpr();
4056    if (!ArgExpr) {
4057      continue;
4058    }
4059
4060    // We can have a pack expansion of any of the bullets below.
4061    if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4062      ArgExpr = Expansion->getPattern();
4063
4064    // Strip off any implicit casts we added as part of type checking.
4065    while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4066      ArgExpr = ICE->getSubExpr();
4067
4068    // C++ [temp.class.spec]p8:
4069    //   A non-type argument is non-specialized if it is the name of a
4070    //   non-type parameter. All other non-type arguments are
4071    //   specialized.
4072    //
4073    // Below, we check the two conditions that only apply to
4074    // specialized non-type arguments, so skip any non-specialized
4075    // arguments.
4076    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
4077      if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
4078        continue;
4079
4080    // C++ [temp.class.spec]p9:
4081    //   Within the argument list of a class template partial
4082    //   specialization, the following restrictions apply:
4083    //     -- A partially specialized non-type argument expression
4084    //        shall not involve a template parameter of the partial
4085    //        specialization except when the argument expression is a
4086    //        simple identifier.
4087    if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
4088      S.Diag(ArgExpr->getLocStart(),
4089           diag::err_dependent_non_type_arg_in_partial_spec)
4090        << ArgExpr->getSourceRange();
4091      return true;
4092    }
4093
4094    //     -- The type of a template parameter corresponding to a
4095    //        specialized non-type argument shall not be dependent on a
4096    //        parameter of the specialization.
4097    if (Param->getType()->isDependentType()) {
4098      S.Diag(ArgExpr->getLocStart(),
4099           diag::err_dependent_typed_non_type_arg_in_partial_spec)
4100        << Param->getType()
4101        << ArgExpr->getSourceRange();
4102      S.Diag(Param->getLocation(), diag::note_template_param_here);
4103      return true;
4104    }
4105  }
4106
4107  return false;
4108}
4109
4110/// \brief Check the non-type template arguments of a class template
4111/// partial specialization according to C++ [temp.class.spec]p9.
4112///
4113/// \param TemplateParams the template parameters of the primary class
4114/// template.
4115///
4116/// \param TemplateArg the template arguments of the class template
4117/// partial specialization.
4118///
4119/// \returns true if there was an error, false otherwise.
4120static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4121                                        TemplateParameterList *TemplateParams,
4122                       llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4123  const TemplateArgument *ArgList = TemplateArgs.data();
4124
4125  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4126    NonTypeTemplateParmDecl *Param
4127      = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4128    if (!Param)
4129      continue;
4130
4131    if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4132                                                           &ArgList[I], 1))
4133      return true;
4134  }
4135
4136  return false;
4137}
4138
4139/// \brief Retrieve the previous declaration of the given declaration.
4140static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4141  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4142    return VD->getPreviousDeclaration();
4143  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4144    return FD->getPreviousDeclaration();
4145  if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4146    return TD->getPreviousDeclaration();
4147  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
4148    return TD->getPreviousDeclaration();
4149  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4150    return FTD->getPreviousDeclaration();
4151  if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4152    return CTD->getPreviousDeclaration();
4153  return 0;
4154}
4155
4156DeclResult
4157Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4158                                       TagUseKind TUK,
4159                                       SourceLocation KWLoc,
4160                                       CXXScopeSpec &SS,
4161                                       TemplateTy TemplateD,
4162                                       SourceLocation TemplateNameLoc,
4163                                       SourceLocation LAngleLoc,
4164                                       ASTTemplateArgsPtr TemplateArgsIn,
4165                                       SourceLocation RAngleLoc,
4166                                       AttributeList *Attr,
4167                               MultiTemplateParamsArg TemplateParameterLists) {
4168  assert(TUK != TUK_Reference && "References are not specializations");
4169
4170  // Find the class template we're specializing
4171  TemplateName Name = TemplateD.getAsVal<TemplateName>();
4172  ClassTemplateDecl *ClassTemplate
4173    = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4174
4175  if (!ClassTemplate) {
4176    Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4177      << (Name.getAsTemplateDecl() &&
4178          isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4179    return true;
4180  }
4181
4182  bool isExplicitSpecialization = false;
4183  bool isPartialSpecialization = false;
4184
4185  // Check the validity of the template headers that introduce this
4186  // template.
4187  // FIXME: We probably shouldn't complain about these headers for
4188  // friend declarations.
4189  bool Invalid = false;
4190  TemplateParameterList *TemplateParams
4191    = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4192                        (TemplateParameterList**)TemplateParameterLists.get(),
4193                                              TemplateParameterLists.size(),
4194                                              TUK == TUK_Friend,
4195                                              isExplicitSpecialization,
4196                                              Invalid);
4197  if (Invalid)
4198    return true;
4199
4200  unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4201  if (TemplateParams)
4202    --NumMatchedTemplateParamLists;
4203
4204  if (TemplateParams && TemplateParams->size() > 0) {
4205    isPartialSpecialization = true;
4206
4207    if (TUK == TUK_Friend) {
4208      Diag(KWLoc, diag::err_partial_specialization_friend)
4209        << SourceRange(LAngleLoc, RAngleLoc);
4210      return true;
4211    }
4212
4213    // C++ [temp.class.spec]p10:
4214    //   The template parameter list of a specialization shall not
4215    //   contain default template argument values.
4216    for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4217      Decl *Param = TemplateParams->getParam(I);
4218      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4219        if (TTP->hasDefaultArgument()) {
4220          Diag(TTP->getDefaultArgumentLoc(),
4221               diag::err_default_arg_in_partial_spec);
4222          TTP->removeDefaultArgument();
4223        }
4224      } else if (NonTypeTemplateParmDecl *NTTP
4225                   = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4226        if (Expr *DefArg = NTTP->getDefaultArgument()) {
4227          Diag(NTTP->getDefaultArgumentLoc(),
4228               diag::err_default_arg_in_partial_spec)
4229            << DefArg->getSourceRange();
4230          NTTP->removeDefaultArgument();
4231        }
4232      } else {
4233        TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
4234        if (TTP->hasDefaultArgument()) {
4235          Diag(TTP->getDefaultArgument().getLocation(),
4236               diag::err_default_arg_in_partial_spec)
4237            << TTP->getDefaultArgument().getSourceRange();
4238          TTP->removeDefaultArgument();
4239        }
4240      }
4241    }
4242  } else if (TemplateParams) {
4243    if (TUK == TUK_Friend)
4244      Diag(KWLoc, diag::err_template_spec_friend)
4245        << FixItHint::CreateRemoval(
4246                                SourceRange(TemplateParams->getTemplateLoc(),
4247                                            TemplateParams->getRAngleLoc()))
4248        << SourceRange(LAngleLoc, RAngleLoc);
4249    else
4250      isExplicitSpecialization = true;
4251  } else if (TUK != TUK_Friend) {
4252    Diag(KWLoc, diag::err_template_spec_needs_header)
4253      << FixItHint::CreateInsertion(KWLoc, "template<> ");
4254    isExplicitSpecialization = true;
4255  }
4256
4257  // Check that the specialization uses the same tag kind as the
4258  // original template.
4259  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4260  assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
4261  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4262                                    Kind, KWLoc,
4263                                    *ClassTemplate->getIdentifier())) {
4264    Diag(KWLoc, diag::err_use_with_wrong_tag)
4265      << ClassTemplate
4266      << FixItHint::CreateReplacement(KWLoc,
4267                            ClassTemplate->getTemplatedDecl()->getKindName());
4268    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4269         diag::note_previous_use);
4270    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4271  }
4272
4273  // Translate the parser's template argument list in our AST format.
4274  TemplateArgumentListInfo TemplateArgs;
4275  TemplateArgs.setLAngleLoc(LAngleLoc);
4276  TemplateArgs.setRAngleLoc(RAngleLoc);
4277  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4278
4279  // Check for unexpanded parameter packs in any of the template arguments.
4280  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4281    if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4282                                        UPPC_PartialSpecialization))
4283      return true;
4284
4285  // Check that the template argument list is well-formed for this
4286  // template.
4287  llvm::SmallVector<TemplateArgument, 4> Converted;
4288  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4289                                TemplateArgs, false, Converted))
4290    return true;
4291
4292  assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
4293         "Converted template argument list is too short!");
4294
4295  // Find the class template (partial) specialization declaration that
4296  // corresponds to these arguments.
4297  if (isPartialSpecialization) {
4298    if (CheckClassTemplatePartialSpecializationArgs(*this,
4299                                         ClassTemplate->getTemplateParameters(),
4300                                         Converted))
4301      return true;
4302
4303    if (!Name.isDependent() &&
4304        !TemplateSpecializationType::anyDependentTemplateArguments(
4305                                             TemplateArgs.getArgumentArray(),
4306                                                         TemplateArgs.size())) {
4307      Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4308        << ClassTemplate->getDeclName();
4309      isPartialSpecialization = false;
4310    }
4311  }
4312
4313  void *InsertPos = 0;
4314  ClassTemplateSpecializationDecl *PrevDecl = 0;
4315
4316  if (isPartialSpecialization)
4317    // FIXME: Template parameter list matters, too
4318    PrevDecl
4319      = ClassTemplate->findPartialSpecialization(Converted.data(),
4320                                                 Converted.size(),
4321                                                 InsertPos);
4322  else
4323    PrevDecl
4324      = ClassTemplate->findSpecialization(Converted.data(),
4325                                          Converted.size(), InsertPos);
4326
4327  ClassTemplateSpecializationDecl *Specialization = 0;
4328
4329  // Check whether we can declare a class template specialization in
4330  // the current scope.
4331  if (TUK != TUK_Friend &&
4332      CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
4333                                       TemplateNameLoc,
4334                                       isPartialSpecialization))
4335    return true;
4336
4337  // The canonical type
4338  QualType CanonType;
4339  if (PrevDecl &&
4340      (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
4341               TUK == TUK_Friend)) {
4342    // Since the only prior class template specialization with these
4343    // arguments was referenced but not declared, or we're only
4344    // referencing this specialization as a friend, reuse that
4345    // declaration node as our own, updating its source location to
4346    // reflect our new declaration.
4347    Specialization = PrevDecl;
4348    Specialization->setLocation(TemplateNameLoc);
4349    PrevDecl = 0;
4350    CanonType = Context.getTypeDeclType(Specialization);
4351  } else if (isPartialSpecialization) {
4352    // Build the canonical type that describes the converted template
4353    // arguments of the class template partial specialization.
4354    TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4355    CanonType = Context.getTemplateSpecializationType(CanonTemplate,
4356                                                      Converted.data(),
4357                                                      Converted.size());
4358
4359    if (Context.hasSameType(CanonType,
4360                        ClassTemplate->getInjectedClassNameSpecialization())) {
4361      // C++ [temp.class.spec]p9b3:
4362      //
4363      //   -- The argument list of the specialization shall not be identical
4364      //      to the implicit argument list of the primary template.
4365      Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4366      << (TUK == TUK_Definition)
4367      << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4368      return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4369                                ClassTemplate->getIdentifier(),
4370                                TemplateNameLoc,
4371                                Attr,
4372                                TemplateParams,
4373                                AS_none);
4374    }
4375
4376    // Create a new class template partial specialization declaration node.
4377    ClassTemplatePartialSpecializationDecl *PrevPartial
4378      = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
4379    unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
4380                            : ClassTemplate->getNextPartialSpecSequenceNumber();
4381    ClassTemplatePartialSpecializationDecl *Partial
4382      = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
4383                                             ClassTemplate->getDeclContext(),
4384                                                       TemplateNameLoc,
4385                                                       TemplateParams,
4386                                                       ClassTemplate,
4387                                                       Converted.data(),
4388                                                       Converted.size(),
4389                                                       TemplateArgs,
4390                                                       CanonType,
4391                                                       PrevPartial,
4392                                                       SequenceNumber);
4393    SetNestedNameSpecifier(Partial, SS);
4394    if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
4395      Partial->setTemplateParameterListsInfo(Context,
4396                                             NumMatchedTemplateParamLists,
4397                    (TemplateParameterList**) TemplateParameterLists.release());
4398    }
4399
4400    if (!PrevPartial)
4401      ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
4402    Specialization = Partial;
4403
4404    // If we are providing an explicit specialization of a member class
4405    // template specialization, make a note of that.
4406    if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4407      PrevPartial->setMemberSpecialization();
4408
4409    // Check that all of the template parameters of the class template
4410    // partial specialization are deducible from the template
4411    // arguments. If not, this class template partial specialization
4412    // will never be used.
4413    llvm::SmallVector<bool, 8> DeducibleParams;
4414    DeducibleParams.resize(TemplateParams->size());
4415    MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4416                               TemplateParams->getDepth(),
4417                               DeducibleParams);
4418    unsigned NumNonDeducible = 0;
4419    for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4420      if (!DeducibleParams[I])
4421        ++NumNonDeducible;
4422
4423    if (NumNonDeducible) {
4424      Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4425        << (NumNonDeducible > 1)
4426        << SourceRange(TemplateNameLoc, RAngleLoc);
4427      for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4428        if (!DeducibleParams[I]) {
4429          NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4430          if (Param->getDeclName())
4431            Diag(Param->getLocation(),
4432                 diag::note_partial_spec_unused_parameter)
4433              << Param->getDeclName();
4434          else
4435            Diag(Param->getLocation(),
4436                 diag::note_partial_spec_unused_parameter)
4437              << "<anonymous>";
4438        }
4439      }
4440    }
4441  } else {
4442    // Create a new class template specialization declaration node for
4443    // this explicit specialization or friend declaration.
4444    Specialization
4445      = ClassTemplateSpecializationDecl::Create(Context, Kind,
4446                                             ClassTemplate->getDeclContext(),
4447                                                TemplateNameLoc,
4448                                                ClassTemplate,
4449                                                Converted.data(),
4450                                                Converted.size(),
4451                                                PrevDecl);
4452    SetNestedNameSpecifier(Specialization, SS);
4453    if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
4454      Specialization->setTemplateParameterListsInfo(Context,
4455                                                  NumMatchedTemplateParamLists,
4456                    (TemplateParameterList**) TemplateParameterLists.release());
4457    }
4458
4459    if (!PrevDecl)
4460      ClassTemplate->AddSpecialization(Specialization, InsertPos);
4461
4462    CanonType = Context.getTypeDeclType(Specialization);
4463  }
4464
4465  // C++ [temp.expl.spec]p6:
4466  //   If a template, a member template or the member of a class template is
4467  //   explicitly specialized then that specialization shall be declared
4468  //   before the first use of that specialization that would cause an implicit
4469  //   instantiation to take place, in every translation unit in which such a
4470  //   use occurs; no diagnostic is required.
4471  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4472    bool Okay = false;
4473    for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4474      // Is there any previous explicit specialization declaration?
4475      if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4476        Okay = true;
4477        break;
4478      }
4479    }
4480
4481    if (!Okay) {
4482      SourceRange Range(TemplateNameLoc, RAngleLoc);
4483      Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4484        << Context.getTypeDeclType(Specialization) << Range;
4485
4486      Diag(PrevDecl->getPointOfInstantiation(),
4487           diag::note_instantiation_required_here)
4488        << (PrevDecl->getTemplateSpecializationKind()
4489                                                != TSK_ImplicitInstantiation);
4490      return true;
4491    }
4492  }
4493
4494  // If this is not a friend, note that this is an explicit specialization.
4495  if (TUK != TUK_Friend)
4496    Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4497
4498  // Check that this isn't a redefinition of this specialization.
4499  if (TUK == TUK_Definition) {
4500    if (RecordDecl *Def = Specialization->getDefinition()) {
4501      SourceRange Range(TemplateNameLoc, RAngleLoc);
4502      Diag(TemplateNameLoc, diag::err_redefinition)
4503        << Context.getTypeDeclType(Specialization) << Range;
4504      Diag(Def->getLocation(), diag::note_previous_definition);
4505      Specialization->setInvalidDecl();
4506      return true;
4507    }
4508  }
4509
4510  if (Attr)
4511    ProcessDeclAttributeList(S, Specialization, Attr);
4512
4513  // Build the fully-sugared type for this class template
4514  // specialization as the user wrote in the specialization
4515  // itself. This means that we'll pretty-print the type retrieved
4516  // from the specialization's declaration the way that the user
4517  // actually wrote the specialization, rather than formatting the
4518  // name based on the "canonical" representation used to store the
4519  // template arguments in the specialization.
4520  TypeSourceInfo *WrittenTy
4521    = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4522                                                TemplateArgs, CanonType);
4523  if (TUK != TUK_Friend) {
4524    Specialization->setTypeAsWritten(WrittenTy);
4525    if (TemplateParams)
4526      Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
4527  }
4528  TemplateArgsIn.release();
4529
4530  // C++ [temp.expl.spec]p9:
4531  //   A template explicit specialization is in the scope of the
4532  //   namespace in which the template was defined.
4533  //
4534  // We actually implement this paragraph where we set the semantic
4535  // context (in the creation of the ClassTemplateSpecializationDecl),
4536  // but we also maintain the lexical context where the actual
4537  // definition occurs.
4538  Specialization->setLexicalDeclContext(CurContext);
4539
4540  // We may be starting the definition of this specialization.
4541  if (TUK == TUK_Definition)
4542    Specialization->startDefinition();
4543
4544  if (TUK == TUK_Friend) {
4545    FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4546                                            TemplateNameLoc,
4547                                            WrittenTy,
4548                                            /*FIXME:*/KWLoc);
4549    Friend->setAccess(AS_public);
4550    CurContext->addDecl(Friend);
4551  } else {
4552    // Add the specialization into its lexical context, so that it can
4553    // be seen when iterating through the list of declarations in that
4554    // context. However, specializations are not found by name lookup.
4555    CurContext->addDecl(Specialization);
4556  }
4557  return Specialization;
4558}
4559
4560Decl *Sema::ActOnTemplateDeclarator(Scope *S,
4561                              MultiTemplateParamsArg TemplateParameterLists,
4562                                    Declarator &D) {
4563  return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4564}
4565
4566Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4567                               MultiTemplateParamsArg TemplateParameterLists,
4568                                            Declarator &D) {
4569  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4570  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4571
4572  if (FTI.hasPrototype) {
4573    // FIXME: Diagnose arguments without names in C.
4574  }
4575
4576  Scope *ParentScope = FnBodyScope->getParent();
4577
4578  Decl *DP = HandleDeclarator(ParentScope, D,
4579                              move(TemplateParameterLists),
4580                              /*IsFunctionDefinition=*/true);
4581  if (FunctionTemplateDecl *FunctionTemplate
4582        = dyn_cast_or_null<FunctionTemplateDecl>(DP))
4583    return ActOnStartOfFunctionDef(FnBodyScope,
4584                                   FunctionTemplate->getTemplatedDecl());
4585  if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4586    return ActOnStartOfFunctionDef(FnBodyScope, Function);
4587  return 0;
4588}
4589
4590/// \brief Strips various properties off an implicit instantiation
4591/// that has just been explicitly specialized.
4592static void StripImplicitInstantiation(NamedDecl *D) {
4593  D->dropAttrs();
4594
4595  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4596    FD->setInlineSpecified(false);
4597  }
4598}
4599
4600/// \brief Diagnose cases where we have an explicit template specialization
4601/// before/after an explicit template instantiation, producing diagnostics
4602/// for those cases where they are required and determining whether the
4603/// new specialization/instantiation will have any effect.
4604///
4605/// \param NewLoc the location of the new explicit specialization or
4606/// instantiation.
4607///
4608/// \param NewTSK the kind of the new explicit specialization or instantiation.
4609///
4610/// \param PrevDecl the previous declaration of the entity.
4611///
4612/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4613///
4614/// \param PrevPointOfInstantiation if valid, indicates where the previus
4615/// declaration was instantiated (either implicitly or explicitly).
4616///
4617/// \param HasNoEffect will be set to true to indicate that the new
4618/// specialization or instantiation has no effect and should be ignored.
4619///
4620/// \returns true if there was an error that should prevent the introduction of
4621/// the new declaration into the AST, false otherwise.
4622bool
4623Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4624                                             TemplateSpecializationKind NewTSK,
4625                                             NamedDecl *PrevDecl,
4626                                             TemplateSpecializationKind PrevTSK,
4627                                        SourceLocation PrevPointOfInstantiation,
4628                                             bool &HasNoEffect) {
4629  HasNoEffect = false;
4630
4631  switch (NewTSK) {
4632  case TSK_Undeclared:
4633  case TSK_ImplicitInstantiation:
4634    assert(false && "Don't check implicit instantiations here");
4635    return false;
4636
4637  case TSK_ExplicitSpecialization:
4638    switch (PrevTSK) {
4639    case TSK_Undeclared:
4640    case TSK_ExplicitSpecialization:
4641      // Okay, we're just specializing something that is either already
4642      // explicitly specialized or has merely been mentioned without any
4643      // instantiation.
4644      return false;
4645
4646    case TSK_ImplicitInstantiation:
4647      if (PrevPointOfInstantiation.isInvalid()) {
4648        // The declaration itself has not actually been instantiated, so it is
4649        // still okay to specialize it.
4650        StripImplicitInstantiation(PrevDecl);
4651        return false;
4652      }
4653      // Fall through
4654
4655    case TSK_ExplicitInstantiationDeclaration:
4656    case TSK_ExplicitInstantiationDefinition:
4657      assert((PrevTSK == TSK_ImplicitInstantiation ||
4658              PrevPointOfInstantiation.isValid()) &&
4659             "Explicit instantiation without point of instantiation?");
4660
4661      // C++ [temp.expl.spec]p6:
4662      //   If a template, a member template or the member of a class template
4663      //   is explicitly specialized then that specialization shall be declared
4664      //   before the first use of that specialization that would cause an
4665      //   implicit instantiation to take place, in every translation unit in
4666      //   which such a use occurs; no diagnostic is required.
4667      for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4668        // Is there any previous explicit specialization declaration?
4669        if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4670          return false;
4671      }
4672
4673      Diag(NewLoc, diag::err_specialization_after_instantiation)
4674        << PrevDecl;
4675      Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
4676        << (PrevTSK != TSK_ImplicitInstantiation);
4677
4678      return true;
4679    }
4680    break;
4681
4682  case TSK_ExplicitInstantiationDeclaration:
4683    switch (PrevTSK) {
4684    case TSK_ExplicitInstantiationDeclaration:
4685      // This explicit instantiation declaration is redundant (that's okay).
4686      HasNoEffect = true;
4687      return false;
4688
4689    case TSK_Undeclared:
4690    case TSK_ImplicitInstantiation:
4691      // We're explicitly instantiating something that may have already been
4692      // implicitly instantiated; that's fine.
4693      return false;
4694
4695    case TSK_ExplicitSpecialization:
4696      // C++0x [temp.explicit]p4:
4697      //   For a given set of template parameters, if an explicit instantiation
4698      //   of a template appears after a declaration of an explicit
4699      //   specialization for that template, the explicit instantiation has no
4700      //   effect.
4701      HasNoEffect = true;
4702      return false;
4703
4704    case TSK_ExplicitInstantiationDefinition:
4705      // C++0x [temp.explicit]p10:
4706      //   If an entity is the subject of both an explicit instantiation
4707      //   declaration and an explicit instantiation definition in the same
4708      //   translation unit, the definition shall follow the declaration.
4709      Diag(NewLoc,
4710           diag::err_explicit_instantiation_declaration_after_definition);
4711      Diag(PrevPointOfInstantiation,
4712           diag::note_explicit_instantiation_definition_here);
4713      assert(PrevPointOfInstantiation.isValid() &&
4714             "Explicit instantiation without point of instantiation?");
4715      HasNoEffect = true;
4716      return false;
4717    }
4718    break;
4719
4720  case TSK_ExplicitInstantiationDefinition:
4721    switch (PrevTSK) {
4722    case TSK_Undeclared:
4723    case TSK_ImplicitInstantiation:
4724      // We're explicitly instantiating something that may have already been
4725      // implicitly instantiated; that's fine.
4726      return false;
4727
4728    case TSK_ExplicitSpecialization:
4729      // C++ DR 259, C++0x [temp.explicit]p4:
4730      //   For a given set of template parameters, if an explicit
4731      //   instantiation of a template appears after a declaration of
4732      //   an explicit specialization for that template, the explicit
4733      //   instantiation has no effect.
4734      //
4735      // In C++98/03 mode, we only give an extension warning here, because it
4736      // is not harmful to try to explicitly instantiate something that
4737      // has been explicitly specialized.
4738      if (!getLangOptions().CPlusPlus0x) {
4739        Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
4740          << PrevDecl;
4741        Diag(PrevDecl->getLocation(),
4742             diag::note_previous_template_specialization);
4743      }
4744      HasNoEffect = true;
4745      return false;
4746
4747    case TSK_ExplicitInstantiationDeclaration:
4748      // We're explicity instantiating a definition for something for which we
4749      // were previously asked to suppress instantiations. That's fine.
4750      return false;
4751
4752    case TSK_ExplicitInstantiationDefinition:
4753      // C++0x [temp.spec]p5:
4754      //   For a given template and a given set of template-arguments,
4755      //     - an explicit instantiation definition shall appear at most once
4756      //       in a program,
4757      Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
4758        << PrevDecl;
4759      Diag(PrevPointOfInstantiation,
4760           diag::note_previous_explicit_instantiation);
4761      HasNoEffect = true;
4762      return false;
4763    }
4764    break;
4765  }
4766
4767  assert(false && "Missing specialization/instantiation case?");
4768
4769  return false;
4770}
4771
4772/// \brief Perform semantic analysis for the given dependent function
4773/// template specialization.  The only possible way to get a dependent
4774/// function template specialization is with a friend declaration,
4775/// like so:
4776///
4777///   template <class T> void foo(T);
4778///   template <class T> class A {
4779///     friend void foo<>(T);
4780///   };
4781///
4782/// There really isn't any useful analysis we can do here, so we
4783/// just store the information.
4784bool
4785Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4786                   const TemplateArgumentListInfo &ExplicitTemplateArgs,
4787                                                   LookupResult &Previous) {
4788  // Remove anything from Previous that isn't a function template in
4789  // the correct context.
4790  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
4791  LookupResult::Filter F = Previous.makeFilter();
4792  while (F.hasNext()) {
4793    NamedDecl *D = F.next()->getUnderlyingDecl();
4794    if (!isa<FunctionTemplateDecl>(D) ||
4795        !FDLookupContext->InEnclosingNamespaceSetOf(
4796                              D->getDeclContext()->getRedeclContext()))
4797      F.erase();
4798  }
4799  F.done();
4800
4801  // Should this be diagnosed here?
4802  if (Previous.empty()) return true;
4803
4804  FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4805                                         ExplicitTemplateArgs);
4806  return false;
4807}
4808
4809/// \brief Perform semantic analysis for the given function template
4810/// specialization.
4811///
4812/// This routine performs all of the semantic analysis required for an
4813/// explicit function template specialization. On successful completion,
4814/// the function declaration \p FD will become a function template
4815/// specialization.
4816///
4817/// \param FD the function declaration, which will be updated to become a
4818/// function template specialization.
4819///
4820/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4821/// if any. Note that this may be valid info even when 0 arguments are
4822/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4823/// as it anyway contains info on the angle brackets locations.
4824///
4825/// \param PrevDecl the set of declarations that may be specialized by
4826/// this function specialization.
4827bool
4828Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4829                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
4830                                          LookupResult &Previous) {
4831  // The set of function template specializations that could match this
4832  // explicit function template specialization.
4833  UnresolvedSet<8> Candidates;
4834
4835  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
4836  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4837         I != E; ++I) {
4838    NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4839    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
4840      // Only consider templates found within the same semantic lookup scope as
4841      // FD.
4842      if (!FDLookupContext->InEnclosingNamespaceSetOf(
4843                                Ovl->getDeclContext()->getRedeclContext()))
4844        continue;
4845
4846      // C++ [temp.expl.spec]p11:
4847      //   A trailing template-argument can be left unspecified in the
4848      //   template-id naming an explicit function template specialization
4849      //   provided it can be deduced from the function argument type.
4850      // Perform template argument deduction to determine whether we may be
4851      // specializing this template.
4852      // FIXME: It is somewhat wasteful to build
4853      TemplateDeductionInfo Info(Context, FD->getLocation());
4854      FunctionDecl *Specialization = 0;
4855      if (TemplateDeductionResult TDK
4856            = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
4857                                      FD->getType(),
4858                                      Specialization,
4859                                      Info)) {
4860        // FIXME: Template argument deduction failed; record why it failed, so
4861        // that we can provide nifty diagnostics.
4862        (void)TDK;
4863        continue;
4864      }
4865
4866      // Record this candidate.
4867      Candidates.addDecl(Specialization, I.getAccess());
4868    }
4869  }
4870
4871  // Find the most specialized function template.
4872  UnresolvedSetIterator Result
4873    = getMostSpecialized(Candidates.begin(), Candidates.end(),
4874                         TPOC_Other, 0, FD->getLocation(),
4875                  PDiag(diag::err_function_template_spec_no_match)
4876                    << FD->getDeclName(),
4877                  PDiag(diag::err_function_template_spec_ambiguous)
4878                    << FD->getDeclName() << (ExplicitTemplateArgs != 0),
4879                  PDiag(diag::note_function_template_spec_matched));
4880  if (Result == Candidates.end())
4881    return true;
4882
4883  // Ignore access information;  it doesn't figure into redeclaration checking.
4884  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
4885  Specialization->setLocation(FD->getLocation());
4886
4887  // FIXME: Check if the prior specialization has a point of instantiation.
4888  // If so, we have run afoul of .
4889
4890  // If this is a friend declaration, then we're not really declaring
4891  // an explicit specialization.
4892  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
4893
4894  // Check the scope of this explicit specialization.
4895  if (!isFriend &&
4896      CheckTemplateSpecializationScope(*this,
4897                                       Specialization->getPrimaryTemplate(),
4898                                       Specialization, FD->getLocation(),
4899                                       false))
4900    return true;
4901
4902  // C++ [temp.expl.spec]p6:
4903  //   If a template, a member template or the member of a class template is
4904  //   explicitly specialized then that specialization shall be declared
4905  //   before the first use of that specialization that would cause an implicit
4906  //   instantiation to take place, in every translation unit in which such a
4907  //   use occurs; no diagnostic is required.
4908  FunctionTemplateSpecializationInfo *SpecInfo
4909    = Specialization->getTemplateSpecializationInfo();
4910  assert(SpecInfo && "Function template specialization info missing?");
4911
4912  bool HasNoEffect = false;
4913  if (!isFriend &&
4914      CheckSpecializationInstantiationRedecl(FD->getLocation(),
4915                                             TSK_ExplicitSpecialization,
4916                                             Specialization,
4917                                   SpecInfo->getTemplateSpecializationKind(),
4918                                         SpecInfo->getPointOfInstantiation(),
4919                                             HasNoEffect))
4920    return true;
4921
4922  // Mark the prior declaration as an explicit specialization, so that later
4923  // clients know that this is an explicit specialization.
4924  if (!isFriend) {
4925    SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
4926    MarkUnusedFileScopedDecl(Specialization);
4927  }
4928
4929  // Turn the given function declaration into a function template
4930  // specialization, with the template arguments from the previous
4931  // specialization.
4932  // Take copies of (semantic and syntactic) template argument lists.
4933  const TemplateArgumentList* TemplArgs = new (Context)
4934    TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4935  const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4936    ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
4937  FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
4938                                        TemplArgs, /*InsertPos=*/0,
4939                                    SpecInfo->getTemplateSpecializationKind(),
4940                                        TemplArgsAsWritten);
4941
4942  // The "previous declaration" for this function template specialization is
4943  // the prior function template specialization.
4944  Previous.clear();
4945  Previous.addDecl(Specialization);
4946  return false;
4947}
4948
4949/// \brief Perform semantic analysis for the given non-template member
4950/// specialization.
4951///
4952/// This routine performs all of the semantic analysis required for an
4953/// explicit member function specialization. On successful completion,
4954/// the function declaration \p FD will become a member function
4955/// specialization.
4956///
4957/// \param Member the member declaration, which will be updated to become a
4958/// specialization.
4959///
4960/// \param Previous the set of declarations, one of which may be specialized
4961/// by this function specialization;  the set will be modified to contain the
4962/// redeclared member.
4963bool
4964Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
4965  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4966
4967  // Try to find the member we are instantiating.
4968  NamedDecl *Instantiation = 0;
4969  NamedDecl *InstantiatedFrom = 0;
4970  MemberSpecializationInfo *MSInfo = 0;
4971
4972  if (Previous.empty()) {
4973    // Nowhere to look anyway.
4974  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
4975    for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4976           I != E; ++I) {
4977      NamedDecl *D = (*I)->getUnderlyingDecl();
4978      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4979        if (Context.hasSameType(Function->getType(), Method->getType())) {
4980          Instantiation = Method;
4981          InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
4982          MSInfo = Method->getMemberSpecializationInfo();
4983          break;
4984        }
4985      }
4986    }
4987  } else if (isa<VarDecl>(Member)) {
4988    VarDecl *PrevVar;
4989    if (Previous.isSingleResult() &&
4990        (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
4991      if (PrevVar->isStaticDataMember()) {
4992        Instantiation = PrevVar;
4993        InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
4994        MSInfo = PrevVar->getMemberSpecializationInfo();
4995      }
4996  } else if (isa<RecordDecl>(Member)) {
4997    CXXRecordDecl *PrevRecord;
4998    if (Previous.isSingleResult() &&
4999        (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5000      Instantiation = PrevRecord;
5001      InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
5002      MSInfo = PrevRecord->getMemberSpecializationInfo();
5003    }
5004  }
5005
5006  if (!Instantiation) {
5007    // There is no previous declaration that matches. Since member
5008    // specializations are always out-of-line, the caller will complain about
5009    // this mismatch later.
5010    return false;
5011  }
5012
5013  // If this is a friend, just bail out here before we start turning
5014  // things into explicit specializations.
5015  if (Member->getFriendObjectKind() != Decl::FOK_None) {
5016    // Preserve instantiation information.
5017    if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5018      cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5019                                      cast<CXXMethodDecl>(InstantiatedFrom),
5020        cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5021    } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5022      cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5023                                      cast<CXXRecordDecl>(InstantiatedFrom),
5024        cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5025    }
5026
5027    Previous.clear();
5028    Previous.addDecl(Instantiation);
5029    return false;
5030  }
5031
5032  // Make sure that this is a specialization of a member.
5033  if (!InstantiatedFrom) {
5034    Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5035      << Member;
5036    Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5037    return true;
5038  }
5039
5040  // C++ [temp.expl.spec]p6:
5041  //   If a template, a member template or the member of a class template is
5042  //   explicitly specialized then that spe- cialization shall be declared
5043  //   before the first use of that specialization that would cause an implicit
5044  //   instantiation to take place, in every translation unit in which such a
5045  //   use occurs; no diagnostic is required.
5046  assert(MSInfo && "Member specialization info missing?");
5047
5048  bool HasNoEffect = false;
5049  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5050                                             TSK_ExplicitSpecialization,
5051                                             Instantiation,
5052                                     MSInfo->getTemplateSpecializationKind(),
5053                                           MSInfo->getPointOfInstantiation(),
5054                                             HasNoEffect))
5055    return true;
5056
5057  // Check the scope of this explicit specialization.
5058  if (CheckTemplateSpecializationScope(*this,
5059                                       InstantiatedFrom,
5060                                       Instantiation, Member->getLocation(),
5061                                       false))
5062    return true;
5063
5064  // Note that this is an explicit instantiation of a member.
5065  // the original declaration to note that it is an explicit specialization
5066  // (if it was previously an implicit instantiation). This latter step
5067  // makes bookkeeping easier.
5068  if (isa<FunctionDecl>(Member)) {
5069    FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5070    if (InstantiationFunction->getTemplateSpecializationKind() ==
5071          TSK_ImplicitInstantiation) {
5072      InstantiationFunction->setTemplateSpecializationKind(
5073                                                  TSK_ExplicitSpecialization);
5074      InstantiationFunction->setLocation(Member->getLocation());
5075    }
5076
5077    cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5078                                        cast<CXXMethodDecl>(InstantiatedFrom),
5079                                                  TSK_ExplicitSpecialization);
5080    MarkUnusedFileScopedDecl(InstantiationFunction);
5081  } else if (isa<VarDecl>(Member)) {
5082    VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5083    if (InstantiationVar->getTemplateSpecializationKind() ==
5084          TSK_ImplicitInstantiation) {
5085      InstantiationVar->setTemplateSpecializationKind(
5086                                                  TSK_ExplicitSpecialization);
5087      InstantiationVar->setLocation(Member->getLocation());
5088    }
5089
5090    Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5091                                                cast<VarDecl>(InstantiatedFrom),
5092                                                TSK_ExplicitSpecialization);
5093    MarkUnusedFileScopedDecl(InstantiationVar);
5094  } else {
5095    assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
5096    CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5097    if (InstantiationClass->getTemplateSpecializationKind() ==
5098          TSK_ImplicitInstantiation) {
5099      InstantiationClass->setTemplateSpecializationKind(
5100                                                   TSK_ExplicitSpecialization);
5101      InstantiationClass->setLocation(Member->getLocation());
5102    }
5103
5104    cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5105                                        cast<CXXRecordDecl>(InstantiatedFrom),
5106                                                   TSK_ExplicitSpecialization);
5107  }
5108
5109  // Save the caller the trouble of having to figure out which declaration
5110  // this specialization matches.
5111  Previous.clear();
5112  Previous.addDecl(Instantiation);
5113  return false;
5114}
5115
5116/// \brief Check the scope of an explicit instantiation.
5117///
5118/// \returns true if a serious error occurs, false otherwise.
5119static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
5120                                            SourceLocation InstLoc,
5121                                            bool WasQualifiedName) {
5122  DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5123  DeclContext *CurContext = S.CurContext->getRedeclContext();
5124
5125  if (CurContext->isRecord()) {
5126    S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5127      << D;
5128    return true;
5129  }
5130
5131  // C++0x [temp.explicit]p2:
5132  //   An explicit instantiation shall appear in an enclosing namespace of its
5133  //   template.
5134  //
5135  // This is DR275, which we do not retroactively apply to C++98/03.
5136  if (S.getLangOptions().CPlusPlus0x &&
5137      !CurContext->Encloses(OrigContext)) {
5138    if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
5139      S.Diag(InstLoc,
5140             S.getLangOptions().CPlusPlus0x?
5141                 diag::err_explicit_instantiation_out_of_scope
5142               : diag::warn_explicit_instantiation_out_of_scope_0x)
5143        << D << NS;
5144    else
5145      S.Diag(InstLoc,
5146             S.getLangOptions().CPlusPlus0x?
5147                 diag::err_explicit_instantiation_must_be_global
5148               : diag::warn_explicit_instantiation_out_of_scope_0x)
5149        << D;
5150    S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5151    return false;
5152  }
5153
5154  // C++0x [temp.explicit]p2:
5155  //   If the name declared in the explicit instantiation is an unqualified
5156  //   name, the explicit instantiation shall appear in the namespace where
5157  //   its template is declared or, if that namespace is inline (7.3.1), any
5158  //   namespace from its enclosing namespace set.
5159  if (WasQualifiedName)
5160    return false;
5161
5162  if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5163    return false;
5164
5165  S.Diag(InstLoc,
5166         S.getLangOptions().CPlusPlus0x?
5167             diag::err_explicit_instantiation_unqualified_wrong_namespace
5168           : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5169    << D << OrigContext;
5170  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5171  return false;
5172}
5173
5174/// \brief Determine whether the given scope specifier has a template-id in it.
5175static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5176  if (!SS.isSet())
5177    return false;
5178
5179  // C++0x [temp.explicit]p2:
5180  //   If the explicit instantiation is for a member function, a member class
5181  //   or a static data member of a class template specialization, the name of
5182  //   the class template specialization in the qualified-id for the member
5183  //   name shall be a simple-template-id.
5184  //
5185  // C++98 has the same restriction, just worded differently.
5186  for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5187       NNS; NNS = NNS->getPrefix())
5188    if (Type *T = NNS->getAsType())
5189      if (isa<TemplateSpecializationType>(T))
5190        return true;
5191
5192  return false;
5193}
5194
5195// Explicit instantiation of a class template specialization
5196DeclResult
5197Sema::ActOnExplicitInstantiation(Scope *S,
5198                                 SourceLocation ExternLoc,
5199                                 SourceLocation TemplateLoc,
5200                                 unsigned TagSpec,
5201                                 SourceLocation KWLoc,
5202                                 const CXXScopeSpec &SS,
5203                                 TemplateTy TemplateD,
5204                                 SourceLocation TemplateNameLoc,
5205                                 SourceLocation LAngleLoc,
5206                                 ASTTemplateArgsPtr TemplateArgsIn,
5207                                 SourceLocation RAngleLoc,
5208                                 AttributeList *Attr) {
5209  // Find the class template we're specializing
5210  TemplateName Name = TemplateD.getAsVal<TemplateName>();
5211  ClassTemplateDecl *ClassTemplate
5212    = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5213
5214  // Check that the specialization uses the same tag kind as the
5215  // original template.
5216  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5217  assert(Kind != TTK_Enum &&
5218         "Invalid enum tag in class template explicit instantiation!");
5219  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5220                                    Kind, KWLoc,
5221                                    *ClassTemplate->getIdentifier())) {
5222    Diag(KWLoc, diag::err_use_with_wrong_tag)
5223      << ClassTemplate
5224      << FixItHint::CreateReplacement(KWLoc,
5225                            ClassTemplate->getTemplatedDecl()->getKindName());
5226    Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5227         diag::note_previous_use);
5228    Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5229  }
5230
5231  // C++0x [temp.explicit]p2:
5232  //   There are two forms of explicit instantiation: an explicit instantiation
5233  //   definition and an explicit instantiation declaration. An explicit
5234  //   instantiation declaration begins with the extern keyword. [...]
5235  TemplateSpecializationKind TSK
5236    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5237                           : TSK_ExplicitInstantiationDeclaration;
5238
5239  // Translate the parser's template argument list in our AST format.
5240  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
5241  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5242
5243  // Check that the template argument list is well-formed for this
5244  // template.
5245  llvm::SmallVector<TemplateArgument, 4> Converted;
5246  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5247                                TemplateArgs, false, Converted))
5248    return true;
5249
5250  assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
5251         "Converted template argument list is too short!");
5252
5253  // Find the class template specialization declaration that
5254  // corresponds to these arguments.
5255  void *InsertPos = 0;
5256  ClassTemplateSpecializationDecl *PrevDecl
5257    = ClassTemplate->findSpecialization(Converted.data(),
5258                                        Converted.size(), InsertPos);
5259
5260  TemplateSpecializationKind PrevDecl_TSK
5261    = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5262
5263  // C++0x [temp.explicit]p2:
5264  //   [...] An explicit instantiation shall appear in an enclosing
5265  //   namespace of its template. [...]
5266  //
5267  // This is C++ DR 275.
5268  if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5269                                      SS.isSet()))
5270    return true;
5271
5272  ClassTemplateSpecializationDecl *Specialization = 0;
5273
5274  bool ReusedDecl = false;
5275  bool HasNoEffect = false;
5276  if (PrevDecl) {
5277    if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
5278                                               PrevDecl, PrevDecl_TSK,
5279                                            PrevDecl->getPointOfInstantiation(),
5280                                               HasNoEffect))
5281      return PrevDecl;
5282
5283    // Even though HasNoEffect == true means that this explicit instantiation
5284    // has no effect on semantics, we go on to put its syntax in the AST.
5285
5286    if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5287        PrevDecl_TSK == TSK_Undeclared) {
5288      // Since the only prior class template specialization with these
5289      // arguments was referenced but not declared, reuse that
5290      // declaration node as our own, updating the source location
5291      // for the template name to reflect our new declaration.
5292      // (Other source locations will be updated later.)
5293      Specialization = PrevDecl;
5294      Specialization->setLocation(TemplateNameLoc);
5295      PrevDecl = 0;
5296      ReusedDecl = true;
5297    }
5298  }
5299
5300  if (!Specialization) {
5301    // Create a new class template specialization declaration node for
5302    // this explicit specialization.
5303    Specialization
5304      = ClassTemplateSpecializationDecl::Create(Context, Kind,
5305                                             ClassTemplate->getDeclContext(),
5306                                                TemplateNameLoc,
5307                                                ClassTemplate,
5308                                                Converted.data(),
5309                                                Converted.size(),
5310                                                PrevDecl);
5311    SetNestedNameSpecifier(Specialization, SS);
5312
5313    if (!HasNoEffect && !PrevDecl) {
5314      // Insert the new specialization.
5315      ClassTemplate->AddSpecialization(Specialization, InsertPos);
5316    }
5317  }
5318
5319  // Build the fully-sugared type for this explicit instantiation as
5320  // the user wrote in the explicit instantiation itself. This means
5321  // that we'll pretty-print the type retrieved from the
5322  // specialization's declaration the way that the user actually wrote
5323  // the explicit instantiation, rather than formatting the name based
5324  // on the "canonical" representation used to store the template
5325  // arguments in the specialization.
5326  TypeSourceInfo *WrittenTy
5327    = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5328                                                TemplateArgs,
5329                                  Context.getTypeDeclType(Specialization));
5330  Specialization->setTypeAsWritten(WrittenTy);
5331  TemplateArgsIn.release();
5332
5333  // Set source locations for keywords.
5334  Specialization->setExternLoc(ExternLoc);
5335  Specialization->setTemplateKeywordLoc(TemplateLoc);
5336
5337  // Add the explicit instantiation into its lexical context. However,
5338  // since explicit instantiations are never found by name lookup, we
5339  // just put it into the declaration context directly.
5340  Specialization->setLexicalDeclContext(CurContext);
5341  CurContext->addDecl(Specialization);
5342
5343  // Syntax is now OK, so return if it has no other effect on semantics.
5344  if (HasNoEffect) {
5345    // Set the template specialization kind.
5346    Specialization->setTemplateSpecializationKind(TSK);
5347    return Specialization;
5348  }
5349
5350  // C++ [temp.explicit]p3:
5351  //   A definition of a class template or class member template
5352  //   shall be in scope at the point of the explicit instantiation of
5353  //   the class template or class member template.
5354  //
5355  // This check comes when we actually try to perform the
5356  // instantiation.
5357  ClassTemplateSpecializationDecl *Def
5358    = cast_or_null<ClassTemplateSpecializationDecl>(
5359                                              Specialization->getDefinition());
5360  if (!Def)
5361    InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
5362  else if (TSK == TSK_ExplicitInstantiationDefinition) {
5363    MarkVTableUsed(TemplateNameLoc, Specialization, true);
5364    Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5365  }
5366
5367  // Instantiate the members of this class template specialization.
5368  Def = cast_or_null<ClassTemplateSpecializationDecl>(
5369                                       Specialization->getDefinition());
5370  if (Def) {
5371    TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5372
5373    // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5374    // TSK_ExplicitInstantiationDefinition
5375    if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5376        TSK == TSK_ExplicitInstantiationDefinition)
5377      Def->setTemplateSpecializationKind(TSK);
5378
5379    InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
5380  }
5381
5382  // Set the template specialization kind.
5383  Specialization->setTemplateSpecializationKind(TSK);
5384  return Specialization;
5385}
5386
5387// Explicit instantiation of a member class of a class template.
5388DeclResult
5389Sema::ActOnExplicitInstantiation(Scope *S,
5390                                 SourceLocation ExternLoc,
5391                                 SourceLocation TemplateLoc,
5392                                 unsigned TagSpec,
5393                                 SourceLocation KWLoc,
5394                                 CXXScopeSpec &SS,
5395                                 IdentifierInfo *Name,
5396                                 SourceLocation NameLoc,
5397                                 AttributeList *Attr) {
5398
5399  bool Owned = false;
5400  bool IsDependent = false;
5401  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
5402                        KWLoc, SS, Name, NameLoc, Attr, AS_none,
5403                        MultiTemplateParamsArg(*this, 0, 0),
5404                        Owned, IsDependent, false, false,
5405                        TypeResult());
5406  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5407
5408  if (!TagD)
5409    return true;
5410
5411  TagDecl *Tag = cast<TagDecl>(TagD);
5412  if (Tag->isEnum()) {
5413    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5414      << Context.getTypeDeclType(Tag);
5415    return true;
5416  }
5417
5418  if (Tag->isInvalidDecl())
5419    return true;
5420
5421  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5422  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5423  if (!Pattern) {
5424    Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5425      << Context.getTypeDeclType(Record);
5426    Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5427    return true;
5428  }
5429
5430  // C++0x [temp.explicit]p2:
5431  //   If the explicit instantiation is for a class or member class, the
5432  //   elaborated-type-specifier in the declaration shall include a
5433  //   simple-template-id.
5434  //
5435  // C++98 has the same restriction, just worded differently.
5436  if (!ScopeSpecifierHasTemplateId(SS))
5437    Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
5438      << Record << SS.getRange();
5439
5440  // C++0x [temp.explicit]p2:
5441  //   There are two forms of explicit instantiation: an explicit instantiation
5442  //   definition and an explicit instantiation declaration. An explicit
5443  //   instantiation declaration begins with the extern keyword. [...]
5444  TemplateSpecializationKind TSK
5445    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5446                           : TSK_ExplicitInstantiationDeclaration;
5447
5448  // C++0x [temp.explicit]p2:
5449  //   [...] An explicit instantiation shall appear in an enclosing
5450  //   namespace of its template. [...]
5451  //
5452  // This is C++ DR 275.
5453  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
5454
5455  // Verify that it is okay to explicitly instantiate here.
5456  CXXRecordDecl *PrevDecl
5457    = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
5458  if (!PrevDecl && Record->getDefinition())
5459    PrevDecl = Record;
5460  if (PrevDecl) {
5461    MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
5462    bool HasNoEffect = false;
5463    assert(MSInfo && "No member specialization information?");
5464    if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
5465                                               PrevDecl,
5466                                        MSInfo->getTemplateSpecializationKind(),
5467                                             MSInfo->getPointOfInstantiation(),
5468                                               HasNoEffect))
5469      return true;
5470    if (HasNoEffect)
5471      return TagD;
5472  }
5473
5474  CXXRecordDecl *RecordDef
5475    = cast_or_null<CXXRecordDecl>(Record->getDefinition());
5476  if (!RecordDef) {
5477    // C++ [temp.explicit]p3:
5478    //   A definition of a member class of a class template shall be in scope
5479    //   at the point of an explicit instantiation of the member class.
5480    CXXRecordDecl *Def
5481      = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
5482    if (!Def) {
5483      Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5484        << 0 << Record->getDeclName() << Record->getDeclContext();
5485      Diag(Pattern->getLocation(), diag::note_forward_declaration)
5486        << Pattern;
5487      return true;
5488    } else {
5489      if (InstantiateClass(NameLoc, Record, Def,
5490                           getTemplateInstantiationArgs(Record),
5491                           TSK))
5492        return true;
5493
5494      RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
5495      if (!RecordDef)
5496        return true;
5497    }
5498  }
5499
5500  // Instantiate all of the members of the class.
5501  InstantiateClassMembers(NameLoc, RecordDef,
5502                          getTemplateInstantiationArgs(Record), TSK);
5503
5504  if (TSK == TSK_ExplicitInstantiationDefinition)
5505    MarkVTableUsed(NameLoc, RecordDef, true);
5506
5507  // FIXME: We don't have any representation for explicit instantiations of
5508  // member classes. Such a representation is not needed for compilation, but it
5509  // should be available for clients that want to see all of the declarations in
5510  // the source code.
5511  return TagD;
5512}
5513
5514DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5515                                            SourceLocation ExternLoc,
5516                                            SourceLocation TemplateLoc,
5517                                            Declarator &D) {
5518  // Explicit instantiations always require a name.
5519  // TODO: check if/when DNInfo should replace Name.
5520  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5521  DeclarationName Name = NameInfo.getName();
5522  if (!Name) {
5523    if (!D.isInvalidType())
5524      Diag(D.getDeclSpec().getSourceRange().getBegin(),
5525           diag::err_explicit_instantiation_requires_name)
5526        << D.getDeclSpec().getSourceRange()
5527        << D.getSourceRange();
5528
5529    return true;
5530  }
5531
5532  // The scope passed in may not be a decl scope.  Zip up the scope tree until
5533  // we find one that is.
5534  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5535         (S->getFlags() & Scope::TemplateParamScope) != 0)
5536    S = S->getParent();
5537
5538  // Determine the type of the declaration.
5539  TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5540  QualType R = T->getType();
5541  if (R.isNull())
5542    return true;
5543
5544  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5545    // Cannot explicitly instantiate a typedef.
5546    Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5547      << Name;
5548    return true;
5549  }
5550
5551  // C++0x [temp.explicit]p1:
5552  //   [...] An explicit instantiation of a function template shall not use the
5553  //   inline or constexpr specifiers.
5554  // Presumably, this also applies to member functions of class templates as
5555  // well.
5556  if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5557    Diag(D.getDeclSpec().getInlineSpecLoc(),
5558         diag::err_explicit_instantiation_inline)
5559      <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5560
5561  // FIXME: check for constexpr specifier.
5562
5563  // C++0x [temp.explicit]p2:
5564  //   There are two forms of explicit instantiation: an explicit instantiation
5565  //   definition and an explicit instantiation declaration. An explicit
5566  //   instantiation declaration begins with the extern keyword. [...]
5567  TemplateSpecializationKind TSK
5568    = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5569                           : TSK_ExplicitInstantiationDeclaration;
5570
5571  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
5572  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
5573
5574  if (!R->isFunctionType()) {
5575    // C++ [temp.explicit]p1:
5576    //   A [...] static data member of a class template can be explicitly
5577    //   instantiated from the member definition associated with its class
5578    //   template.
5579    if (Previous.isAmbiguous())
5580      return true;
5581
5582    VarDecl *Prev = Previous.getAsSingle<VarDecl>();
5583    if (!Prev || !Prev->isStaticDataMember()) {
5584      // We expect to see a data data member here.
5585      Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5586        << Name;
5587      for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5588           P != PEnd; ++P)
5589        Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
5590      return true;
5591    }
5592
5593    if (!Prev->getInstantiatedFromStaticDataMember()) {
5594      // FIXME: Check for explicit specialization?
5595      Diag(D.getIdentifierLoc(),
5596           diag::err_explicit_instantiation_data_member_not_instantiated)
5597        << Prev;
5598      Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5599      // FIXME: Can we provide a note showing where this was declared?
5600      return true;
5601    }
5602
5603    // C++0x [temp.explicit]p2:
5604    //   If the explicit instantiation is for a member function, a member class
5605    //   or a static data member of a class template specialization, the name of
5606    //   the class template specialization in the qualified-id for the member
5607    //   name shall be a simple-template-id.
5608    //
5609    // C++98 has the same restriction, just worded differently.
5610    if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5611      Diag(D.getIdentifierLoc(),
5612           diag::ext_explicit_instantiation_without_qualified_id)
5613        << Prev << D.getCXXScopeSpec().getRange();
5614
5615    // Check the scope of this explicit instantiation.
5616    CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5617
5618    // Verify that it is okay to explicitly instantiate here.
5619    MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5620    assert(MSInfo && "Missing static data member specialization info?");
5621    bool HasNoEffect = false;
5622    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
5623                                        MSInfo->getTemplateSpecializationKind(),
5624                                              MSInfo->getPointOfInstantiation(),
5625                                               HasNoEffect))
5626      return true;
5627    if (HasNoEffect)
5628      return (Decl*) 0;
5629
5630    // Instantiate static data member.
5631    Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5632    if (TSK == TSK_ExplicitInstantiationDefinition)
5633      InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
5634
5635    // FIXME: Create an ExplicitInstantiation node?
5636    return (Decl*) 0;
5637  }
5638
5639  // If the declarator is a template-id, translate the parser's template
5640  // argument list into our AST format.
5641  bool HasExplicitTemplateArgs = false;
5642  TemplateArgumentListInfo TemplateArgs;
5643  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5644    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5645    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5646    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5647    ASTTemplateArgsPtr TemplateArgsPtr(*this,
5648                                       TemplateId->getTemplateArgs(),
5649                                       TemplateId->NumArgs);
5650    translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
5651    HasExplicitTemplateArgs = true;
5652    TemplateArgsPtr.release();
5653  }
5654
5655  // C++ [temp.explicit]p1:
5656  //   A [...] function [...] can be explicitly instantiated from its template.
5657  //   A member function [...] of a class template can be explicitly
5658  //  instantiated from the member definition associated with its class
5659  //  template.
5660  UnresolvedSet<8> Matches;
5661  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5662       P != PEnd; ++P) {
5663    NamedDecl *Prev = *P;
5664    if (!HasExplicitTemplateArgs) {
5665      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5666        if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5667          Matches.clear();
5668
5669          Matches.addDecl(Method, P.getAccess());
5670          if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5671            break;
5672        }
5673      }
5674    }
5675
5676    FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5677    if (!FunTmpl)
5678      continue;
5679
5680    TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
5681    FunctionDecl *Specialization = 0;
5682    if (TemplateDeductionResult TDK
5683          = DeduceTemplateArguments(FunTmpl,
5684                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5685                                    R, Specialization, Info)) {
5686      // FIXME: Keep track of almost-matches?
5687      (void)TDK;
5688      continue;
5689    }
5690
5691    Matches.addDecl(Specialization, P.getAccess());
5692  }
5693
5694  // Find the most specialized function template specialization.
5695  UnresolvedSetIterator Result
5696    = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
5697                         D.getIdentifierLoc(),
5698                     PDiag(diag::err_explicit_instantiation_not_known) << Name,
5699                     PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5700                         PDiag(diag::note_explicit_instantiation_candidate));
5701
5702  if (Result == Matches.end())
5703    return true;
5704
5705  // Ignore access control bits, we don't need them for redeclaration checking.
5706  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5707
5708  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
5709    Diag(D.getIdentifierLoc(),
5710         diag::err_explicit_instantiation_member_function_not_instantiated)
5711      << Specialization
5712      << (Specialization->getTemplateSpecializationKind() ==
5713          TSK_ExplicitSpecialization);
5714    Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5715    return true;
5716  }
5717
5718  FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
5719  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5720    PrevDecl = Specialization;
5721
5722  if (PrevDecl) {
5723    bool HasNoEffect = false;
5724    if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
5725                                               PrevDecl,
5726                                     PrevDecl->getTemplateSpecializationKind(),
5727                                          PrevDecl->getPointOfInstantiation(),
5728                                               HasNoEffect))
5729      return true;
5730
5731    // FIXME: We may still want to build some representation of this
5732    // explicit specialization.
5733    if (HasNoEffect)
5734      return (Decl*) 0;
5735  }
5736
5737  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5738
5739  if (TSK == TSK_ExplicitInstantiationDefinition)
5740    InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
5741
5742  // C++0x [temp.explicit]p2:
5743  //   If the explicit instantiation is for a member function, a member class
5744  //   or a static data member of a class template specialization, the name of
5745  //   the class template specialization in the qualified-id for the member
5746  //   name shall be a simple-template-id.
5747  //
5748  // C++98 has the same restriction, just worded differently.
5749  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
5750  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
5751      D.getCXXScopeSpec().isSet() &&
5752      !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5753    Diag(D.getIdentifierLoc(),
5754         diag::ext_explicit_instantiation_without_qualified_id)
5755    << Specialization << D.getCXXScopeSpec().getRange();
5756
5757  CheckExplicitInstantiationScope(*this,
5758                   FunTmpl? (NamedDecl *)FunTmpl
5759                          : Specialization->getInstantiatedFromMemberFunction(),
5760                                  D.getIdentifierLoc(),
5761                                  D.getCXXScopeSpec().isSet());
5762
5763  // FIXME: Create some kind of ExplicitInstantiationDecl here.
5764  return (Decl*) 0;
5765}
5766
5767TypeResult
5768Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5769                        const CXXScopeSpec &SS, IdentifierInfo *Name,
5770                        SourceLocation TagLoc, SourceLocation NameLoc) {
5771  // This has to hold, because SS is expected to be defined.
5772  assert(Name && "Expected a name in a dependent tag");
5773
5774  NestedNameSpecifier *NNS
5775    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5776  if (!NNS)
5777    return true;
5778
5779  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5780
5781  if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5782    Diag(NameLoc, diag::err_dependent_tag_decl)
5783      << (TUK == TUK_Definition) << Kind << SS.getRange();
5784    return true;
5785  }
5786
5787  ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5788  return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
5789}
5790
5791TypeResult
5792Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5793                        const CXXScopeSpec &SS, const IdentifierInfo &II,
5794                        SourceLocation IdLoc) {
5795  NestedNameSpecifier *NNS
5796    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5797  if (!NNS)
5798    return true;
5799
5800  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5801      !getLangOptions().CPlusPlus0x)
5802    Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5803      << FixItHint::CreateRemoval(TypenameLoc);
5804
5805  QualType T = CheckTypenameType(ETK_Typename, NNS, II,
5806                                 TypenameLoc, SS.getRange(), IdLoc);
5807  if (T.isNull())
5808    return true;
5809
5810  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5811  if (isa<DependentNameType>(T)) {
5812    DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5813    TL.setKeywordLoc(TypenameLoc);
5814    TL.setQualifierRange(SS.getRange());
5815    TL.setNameLoc(IdLoc);
5816  } else {
5817    ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
5818    TL.setKeywordLoc(TypenameLoc);
5819    TL.setQualifierRange(SS.getRange());
5820    cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
5821  }
5822
5823  return CreateParsedType(T, TSI);
5824}
5825
5826TypeResult
5827Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5828                        const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5829                        ParsedType Ty) {
5830  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5831      !getLangOptions().CPlusPlus0x)
5832    Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5833      << FixItHint::CreateRemoval(TypenameLoc);
5834
5835  TypeSourceInfo *InnerTSI = 0;
5836  QualType T = GetTypeFromParser(Ty, &InnerTSI);
5837
5838  assert(isa<TemplateSpecializationType>(T) &&
5839         "Expected a template specialization type");
5840
5841  if (computeDeclContext(SS, false)) {
5842    // If we can compute a declaration context, then the "typename"
5843    // keyword was superfluous. Just build an ElaboratedType to keep
5844    // track of the nested-name-specifier.
5845
5846    // Push the inner type, preserving its source locations if possible.
5847    TypeLocBuilder Builder;
5848    if (InnerTSI)
5849      Builder.pushFullCopy(InnerTSI->getTypeLoc());
5850    else
5851      Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5852
5853    /* Note: NNS already embedded in template specialization type T. */
5854    T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
5855    ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5856    TL.setKeywordLoc(TypenameLoc);
5857    TL.setQualifierRange(SS.getRange());
5858
5859    TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
5860    return CreateParsedType(T, TSI);
5861  }
5862
5863  // TODO: it's really silly that we make a template specialization
5864  // type earlier only to drop it again here.
5865  TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5866  DependentTemplateName *DTN =
5867    TST->getTemplateName().getAsDependentTemplateName();
5868  assert(DTN && "dependent template has non-dependent name?");
5869  assert(DTN->getQualifier()
5870         == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5871  T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5872                                                     DTN->getQualifier(),
5873                                                     DTN->getIdentifier(),
5874                                                     TST->getNumArgs(),
5875                                                     TST->getArgs());
5876  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5877  DependentTemplateSpecializationTypeLoc TL =
5878    cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5879  if (InnerTSI) {
5880    TemplateSpecializationTypeLoc TSTL =
5881      cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5882    TL.setLAngleLoc(TSTL.getLAngleLoc());
5883    TL.setRAngleLoc(TSTL.getRAngleLoc());
5884    for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5885      TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5886  } else {
5887    TL.initializeLocal(SourceLocation());
5888  }
5889  TL.setKeywordLoc(TypenameLoc);
5890  TL.setQualifierRange(SS.getRange());
5891  return CreateParsedType(T, TSI);
5892}
5893
5894/// \brief Build the type that describes a C++ typename specifier,
5895/// e.g., "typename T::type".
5896QualType
5897Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5898                        NestedNameSpecifier *NNS, const IdentifierInfo &II,
5899                        SourceLocation KeywordLoc, SourceRange NNSRange,
5900                        SourceLocation IILoc) {
5901  CXXScopeSpec SS;
5902  SS.setScopeRep(NNS);
5903  SS.setRange(NNSRange);
5904
5905  DeclContext *Ctx = computeDeclContext(SS);
5906  if (!Ctx) {
5907    // If the nested-name-specifier is dependent and couldn't be
5908    // resolved to a type, build a typename type.
5909    assert(NNS->isDependent());
5910    return Context.getDependentNameType(Keyword, NNS, &II);
5911  }
5912
5913  // If the nested-name-specifier refers to the current instantiation,
5914  // the "typename" keyword itself is superfluous. In C++03, the
5915  // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5916  // allows such extraneous "typename" keywords, and we retroactively
5917  // apply this DR to C++03 code with only a warning. In any case we continue.
5918
5919  if (RequireCompleteDeclContext(SS, Ctx))
5920    return QualType();
5921
5922  DeclarationName Name(&II);
5923  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
5924  LookupQualifiedName(Result, Ctx);
5925  unsigned DiagID = 0;
5926  Decl *Referenced = 0;
5927  switch (Result.getResultKind()) {
5928  case LookupResult::NotFound:
5929    DiagID = diag::err_typename_nested_not_found;
5930    break;
5931
5932  case LookupResult::FoundUnresolvedValue: {
5933    // We found a using declaration that is a value. Most likely, the using
5934    // declaration itself is meant to have the 'typename' keyword.
5935    SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5936                          IILoc);
5937    Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5938      << Name << Ctx << FullRange;
5939    if (UnresolvedUsingValueDecl *Using
5940          = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5941      SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5942      Diag(Loc, diag::note_using_value_decl_missing_typename)
5943        << FixItHint::CreateInsertion(Loc, "typename ");
5944    }
5945  }
5946  // Fall through to create a dependent typename type, from which we can recover
5947  // better.
5948
5949  case LookupResult::NotFoundInCurrentInstantiation:
5950    // Okay, it's a member of an unknown instantiation.
5951    return Context.getDependentNameType(Keyword, NNS, &II);
5952
5953  case LookupResult::Found:
5954    if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
5955      // We found a type. Build an ElaboratedType, since the
5956      // typename-specifier was just sugar.
5957      return Context.getElaboratedType(ETK_Typename, NNS,
5958                                       Context.getTypeDeclType(Type));
5959    }
5960
5961    DiagID = diag::err_typename_nested_not_type;
5962    Referenced = Result.getFoundDecl();
5963    break;
5964
5965
5966    llvm_unreachable("unresolved using decl in non-dependent context");
5967    return QualType();
5968
5969  case LookupResult::FoundOverloaded:
5970    DiagID = diag::err_typename_nested_not_type;
5971    Referenced = *Result.begin();
5972    break;
5973
5974  case LookupResult::Ambiguous:
5975    return QualType();
5976  }
5977
5978  // If we get here, it's because name lookup did not find a
5979  // type. Emit an appropriate diagnostic and return an error.
5980  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5981                        IILoc);
5982  Diag(IILoc, DiagID) << FullRange << Name << Ctx;
5983  if (Referenced)
5984    Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5985      << Name;
5986  return QualType();
5987}
5988
5989namespace {
5990  // See Sema::RebuildTypeInCurrentInstantiation
5991  class CurrentInstantiationRebuilder
5992    : public TreeTransform<CurrentInstantiationRebuilder> {
5993    SourceLocation Loc;
5994    DeclarationName Entity;
5995
5996  public:
5997    typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5998
5999    CurrentInstantiationRebuilder(Sema &SemaRef,
6000                                  SourceLocation Loc,
6001                                  DeclarationName Entity)
6002    : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
6003      Loc(Loc), Entity(Entity) { }
6004
6005    /// \brief Determine whether the given type \p T has already been
6006    /// transformed.
6007    ///
6008    /// For the purposes of type reconstruction, a type has already been
6009    /// transformed if it is NULL or if it is not dependent.
6010    bool AlreadyTransformed(QualType T) {
6011      return T.isNull() || !T->isDependentType();
6012    }
6013
6014    /// \brief Returns the location of the entity whose type is being
6015    /// rebuilt.
6016    SourceLocation getBaseLocation() { return Loc; }
6017
6018    /// \brief Returns the name of the entity whose type is being rebuilt.
6019    DeclarationName getBaseEntity() { return Entity; }
6020
6021    /// \brief Sets the "base" location and entity when that
6022    /// information is known based on another transformation.
6023    void setBase(SourceLocation Loc, DeclarationName Entity) {
6024      this->Loc = Loc;
6025      this->Entity = Entity;
6026    }
6027  };
6028}
6029
6030/// \brief Rebuilds a type within the context of the current instantiation.
6031///
6032/// The type \p T is part of the type of an out-of-line member definition of
6033/// a class template (or class template partial specialization) that was parsed
6034/// and constructed before we entered the scope of the class template (or
6035/// partial specialization thereof). This routine will rebuild that type now
6036/// that we have entered the declarator's scope, which may produce different
6037/// canonical types, e.g.,
6038///
6039/// \code
6040/// template<typename T>
6041/// struct X {
6042///   typedef T* pointer;
6043///   pointer data();
6044/// };
6045///
6046/// template<typename T>
6047/// typename X<T>::pointer X<T>::data() { ... }
6048/// \endcode
6049///
6050/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
6051/// since we do not know that we can look into X<T> when we parsed the type.
6052/// This function will rebuild the type, performing the lookup of "pointer"
6053/// in X<T> and returning an ElaboratedType whose canonical type is the same
6054/// as the canonical type of T*, allowing the return types of the out-of-line
6055/// definition and the declaration to match.
6056TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6057                                                        SourceLocation Loc,
6058                                                        DeclarationName Name) {
6059  if (!T || !T->getType()->isDependentType())
6060    return T;
6061
6062  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6063  return Rebuilder.TransformType(T);
6064}
6065
6066ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
6067  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6068                                          DeclarationName());
6069  return Rebuilder.TransformExpr(E);
6070}
6071
6072bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6073  if (SS.isInvalid()) return true;
6074
6075  NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6076  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6077                                          DeclarationName());
6078  NestedNameSpecifier *Rebuilt =
6079    Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
6080  if (!Rebuilt) return true;
6081
6082  SS.setScopeRep(Rebuilt);
6083  return false;
6084}
6085
6086/// \brief Produces a formatted string that describes the binding of
6087/// template parameters to template arguments.
6088std::string
6089Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6090                                      const TemplateArgumentList &Args) {
6091  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
6092}
6093
6094std::string
6095Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6096                                      const TemplateArgument *Args,
6097                                      unsigned NumArgs) {
6098  llvm::SmallString<128> Str;
6099  llvm::raw_svector_ostream Out(Str);
6100
6101  if (!Params || Params->size() == 0 || NumArgs == 0)
6102    return std::string();
6103
6104  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6105    if (I >= NumArgs)
6106      break;
6107
6108    if (I == 0)
6109      Out << "[with ";
6110    else
6111      Out << ", ";
6112
6113    if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
6114      Out << Id->getName();
6115    } else {
6116      Out << '$' << I;
6117    }
6118
6119    Out << " = ";
6120    Args[I].print(Context.PrintingPolicy, Out);
6121  }
6122
6123  Out << ']';
6124  return Out.str();
6125}
6126
6127