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