clang API Documentation

SemaTemplate.cpp

Go to the documentation of this file.
00001 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //===----------------------------------------------------------------------===/
00008 //
00009 //  This file implements semantic analysis for C++ templates.
00010 //===----------------------------------------------------------------------===/
00011 
00012 #include "Sema.h"
00013 #include "Lookup.h"
00014 #include "TreeTransform.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/Expr.h"
00017 #include "clang/AST/ExprCXX.h"
00018 #include "clang/AST/DeclFriend.h"
00019 #include "clang/AST/DeclTemplate.h"
00020 #include "clang/Parse/DeclSpec.h"
00021 #include "clang/Parse/Template.h"
00022 #include "clang/Basic/LangOptions.h"
00023 #include "clang/Basic/PartialDiagnostic.h"
00024 #include "llvm/ADT/StringExtras.h"
00025 using namespace clang;
00026 
00027 /// \brief Determine whether the declaration found is acceptable as the name
00028 /// of a template and, if so, return that template declaration. Otherwise,
00029 /// returns NULL.
00030 static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
00031   if (!D)
00032     return 0;
00033 
00034   if (isa<TemplateDecl>(D))
00035     return D;
00036 
00037   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
00038     // C++ [temp.local]p1:
00039     //   Like normal (non-template) classes, class templates have an
00040     //   injected-class-name (Clause 9). The injected-class-name
00041     //   can be used with or without a template-argument-list. When
00042     //   it is used without a template-argument-list, it is
00043     //   equivalent to the injected-class-name followed by the
00044     //   template-parameters of the class template enclosed in
00045     //   <>. When it is used with a template-argument-list, it
00046     //   refers to the specified class template specialization,
00047     //   which could be the current specialization or another
00048     //   specialization.
00049     if (Record->isInjectedClassName()) {
00050       Record = cast<CXXRecordDecl>(Record->getDeclContext());
00051       if (Record->getDescribedClassTemplate())
00052         return Record->getDescribedClassTemplate();
00053 
00054       if (ClassTemplateSpecializationDecl *Spec
00055             = dyn_cast<ClassTemplateSpecializationDecl>(Record))
00056         return Spec->getSpecializedTemplate();
00057     }
00058 
00059     return 0;
00060   }
00061 
00062   return 0;
00063 }
00064 
00065 static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
00066   // The set of class templates we've already seen.
00067   llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
00068   LookupResult::Filter filter = R.makeFilter();
00069   while (filter.hasNext()) {
00070     NamedDecl *Orig = filter.next();
00071     NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
00072     if (!Repl)
00073       filter.erase();
00074     else if (Repl != Orig) {
00075 
00076       // C++ [temp.local]p3:
00077       //   A lookup that finds an injected-class-name (10.2) can result in an 
00078       //   ambiguity in certain cases (for example, if it is found in more than
00079       //   one base class). If all of the injected-class-names that are found 
00080       //   refer to specializations of the same class template, and if the name 
00081       //   is followed by a template-argument-list, the reference refers to the 
00082       //   class template itself and not a specialization thereof, and is not 
00083       //   ambiguous.
00084       //
00085       // FIXME: Will we eventually have to do the same for alias templates?
00086       if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
00087         if (!ClassTemplates.insert(ClassTmpl)) {
00088           filter.erase();
00089           continue;
00090         }
00091           
00092       filter.replace(Repl);
00093     }
00094   }
00095   filter.done();
00096 }
00097 
00098 TemplateNameKind Sema::isTemplateName(Scope *S,
00099                                       CXXScopeSpec &SS,
00100                                       UnqualifiedId &Name,
00101                                       TypeTy *ObjectTypePtr,
00102                                       bool EnteringContext,
00103                                       TemplateTy &TemplateResult) {
00104   assert(getLangOptions().CPlusPlus && "No template names in C!");
00105 
00106   DeclarationName TName;
00107   
00108   switch (Name.getKind()) {
00109   case UnqualifiedId::IK_Identifier:
00110     TName = DeclarationName(Name.Identifier);
00111     break;
00112       
00113   case UnqualifiedId::IK_OperatorFunctionId:
00114     TName = Context.DeclarationNames.getCXXOperatorName(
00115                                               Name.OperatorFunctionId.Operator);
00116     break;
00117 
00118   case UnqualifiedId::IK_LiteralOperatorId:
00119     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
00120     break;
00121 
00122   default:
00123     return TNK_Non_template;
00124   }
00125 
00126   QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
00127 
00128   LookupResult R(*this, TName, Name.getSourceRange().getBegin(), 
00129                  LookupOrdinaryName);
00130   R.suppressDiagnostics();
00131   LookupTemplateName(R, S, SS, ObjectType, EnteringContext);
00132   if (R.empty() || R.isAmbiguous())
00133     return TNK_Non_template;
00134 
00135   TemplateName Template;
00136   TemplateNameKind TemplateKind;
00137 
00138   unsigned ResultCount = R.end() - R.begin();
00139   if (ResultCount > 1) {
00140     // We assume that we'll preserve the qualifier from a function
00141     // template name in other ways.
00142     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
00143     TemplateKind = TNK_Function_template;
00144   } else {
00145     TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
00146 
00147     if (SS.isSet() && !SS.isInvalid()) {
00148       NestedNameSpecifier *Qualifier
00149         = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
00150       Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
00151     } else {
00152       Template = TemplateName(TD);
00153     }
00154 
00155     if (isa<FunctionTemplateDecl>(TD))
00156       TemplateKind = TNK_Function_template;
00157     else {
00158       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
00159       TemplateKind = TNK_Type_template;
00160     }
00161   }
00162 
00163   TemplateResult = TemplateTy::make(Template);
00164   return TemplateKind;
00165 }
00166 
00167 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 
00168                                        SourceLocation IILoc,
00169                                        Scope *S,
00170                                        const CXXScopeSpec *SS,
00171                                        TemplateTy &SuggestedTemplate,
00172                                        TemplateNameKind &SuggestedKind) {
00173   // We can't recover unless there's a dependent scope specifier preceding the
00174   // template name.
00175   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
00176       computeDeclContext(*SS))
00177     return false;
00178   
00179   // The code is missing a 'template' keyword prior to the dependent template
00180   // name.
00181   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
00182   Diag(IILoc, diag::err_template_kw_missing)
00183     << Qualifier << II.getName()
00184     << FixItHint::CreateInsertion(IILoc, "template ");
00185   SuggestedTemplate 
00186     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
00187   SuggestedKind = TNK_Dependent_template_name;
00188   return true;
00189 }
00190 
00191 void Sema::LookupTemplateName(LookupResult &Found,
00192                               Scope *S, CXXScopeSpec &SS,
00193                               QualType ObjectType,
00194                               bool EnteringContext) {
00195   // Determine where to perform name lookup
00196   DeclContext *LookupCtx = 0;
00197   bool isDependent = false;
00198   if (!ObjectType.isNull()) {
00199     // This nested-name-specifier occurs in a member access expression, e.g.,
00200     // x->B::f, and we are looking into the type of the object.
00201     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
00202     LookupCtx = computeDeclContext(ObjectType);
00203     isDependent = ObjectType->isDependentType();
00204     assert((isDependent || !ObjectType->isIncompleteType()) && 
00205            "Caller should have completed object type");
00206   } else if (SS.isSet()) {
00207     // This nested-name-specifier occurs after another nested-name-specifier,
00208     // so long into the context associated with the prior nested-name-specifier.
00209     LookupCtx = computeDeclContext(SS, EnteringContext);
00210     isDependent = isDependentScopeSpecifier(SS);
00211     
00212     // The declaration context must be complete.
00213     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
00214       return;
00215   }
00216 
00217   bool ObjectTypeSearchedInScope = false;
00218   if (LookupCtx) {
00219     // Perform "qualified" name lookup into the declaration context we
00220     // computed, which is either the type of the base of a member access
00221     // expression or the declaration context associated with a prior
00222     // nested-name-specifier.
00223     LookupQualifiedName(Found, LookupCtx);
00224 
00225     if (!ObjectType.isNull() && Found.empty()) {
00226       // C++ [basic.lookup.classref]p1:
00227       //   In a class member access expression (5.2.5), if the . or -> token is
00228       //   immediately followed by an identifier followed by a <, the
00229       //   identifier must be looked up to determine whether the < is the
00230       //   beginning of a template argument list (14.2) or a less-than operator.
00231       //   The identifier is first looked up in the class of the object
00232       //   expression. If the identifier is not found, it is then looked up in
00233       //   the context of the entire postfix-expression and shall name a class
00234       //   or function template.
00235       //
00236       // FIXME: When we're instantiating a template, do we actually have to
00237       // look in the scope of the template? Seems fishy...
00238       if (S) LookupName(Found, S);
00239       ObjectTypeSearchedInScope = true;
00240     }
00241   } else if (isDependent) {
00242     // We cannot look into a dependent object type or nested nme
00243     // specifier.
00244     return;
00245   } else {
00246     // Perform unqualified name lookup in the current scope.
00247     LookupName(Found, S);
00248   }
00249 
00250   if (Found.empty() && !isDependent) {
00251     // If we did not find any names, attempt to correct any typos.
00252     DeclarationName Name = Found.getLookupName();
00253     if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx, 
00254                                                  false, CTC_CXXCasts)) {
00255       FilterAcceptableTemplateNames(Context, Found);
00256       if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
00257         if (LookupCtx)
00258           Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
00259             << Name << LookupCtx << Found.getLookupName() << SS.getRange()
00260             << FixItHint::CreateReplacement(Found.getNameLoc(),
00261                                           Found.getLookupName().getAsString());
00262         else
00263           Diag(Found.getNameLoc(), diag::err_no_template_suggest)
00264             << Name << Found.getLookupName()
00265             << FixItHint::CreateReplacement(Found.getNameLoc(),
00266                                           Found.getLookupName().getAsString());
00267         if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
00268           Diag(Template->getLocation(), diag::note_previous_decl)
00269             << Template->getDeclName();
00270       } else
00271         Found.clear();
00272     } else {
00273       Found.clear();
00274     }
00275   }
00276 
00277   FilterAcceptableTemplateNames(Context, Found);
00278   if (Found.empty())
00279     return;
00280 
00281   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
00282     // C++ [basic.lookup.classref]p1:
00283     //   [...] If the lookup in the class of the object expression finds a
00284     //   template, the name is also looked up in the context of the entire
00285     //   postfix-expression and [...]
00286     //
00287     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
00288                             LookupOrdinaryName);
00289     LookupName(FoundOuter, S);
00290     FilterAcceptableTemplateNames(Context, FoundOuter);
00291     
00292     if (FoundOuter.empty()) {
00293       //   - if the name is not found, the name found in the class of the
00294       //     object expression is used, otherwise
00295     } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
00296       //   - if the name is found in the context of the entire
00297       //     postfix-expression and does not name a class template, the name
00298       //     found in the class of the object expression is used, otherwise
00299     } else {
00300       //   - if the name found is a class template, it must refer to the same
00301       //     entity as the one found in the class of the object expression,
00302       //     otherwise the program is ill-formed.
00303       if (!Found.isSingleResult() ||
00304           Found.getFoundDecl()->getCanonicalDecl()
00305             != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
00306         Diag(Found.getNameLoc(), 
00307              diag::err_nested_name_member_ref_lookup_ambiguous)
00308           << Found.getLookupName();
00309         Diag(Found.getRepresentativeDecl()->getLocation(),
00310              diag::note_ambig_member_ref_object_type)
00311           << ObjectType;
00312         Diag(FoundOuter.getFoundDecl()->getLocation(),
00313              diag::note_ambig_member_ref_scope);
00314 
00315         // Recover by taking the template that we found in the object
00316         // expression's type.
00317       }
00318     }
00319   }
00320 }
00321 
00322 /// ActOnDependentIdExpression - Handle a dependent id-expression that
00323 /// was just parsed.  This is only possible with an explicit scope
00324 /// specifier naming a dependent type.
00325 Sema::OwningExprResult
00326 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
00327                                  DeclarationName Name,
00328                                  SourceLocation NameLoc,
00329                                  bool isAddressOfOperand,
00330                            const TemplateArgumentListInfo *TemplateArgs) {
00331   NestedNameSpecifier *Qualifier
00332     = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
00333     
00334   if (!isAddressOfOperand &&
00335       isa<CXXMethodDecl>(CurContext) &&
00336       cast<CXXMethodDecl>(CurContext)->isInstance()) {
00337     QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
00338     
00339     // Since the 'this' expression is synthesized, we don't need to
00340     // perform the double-lookup check.
00341     NamedDecl *FirstQualifierInScope = 0;
00342 
00343     return Owned(CXXDependentScopeMemberExpr::Create(Context,
00344                                                      /*This*/ 0, ThisType,
00345                                                      /*IsArrow*/ true,
00346                                                      /*Op*/ SourceLocation(),
00347                                                      Qualifier, SS.getRange(),
00348                                                      FirstQualifierInScope,
00349                                                      Name, NameLoc,
00350                                                      TemplateArgs));
00351   }
00352 
00353   return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
00354 }
00355 
00356 Sema::OwningExprResult
00357 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
00358                                 DeclarationName Name,
00359                                 SourceLocation NameLoc,
00360                                 const TemplateArgumentListInfo *TemplateArgs) {
00361   return Owned(DependentScopeDeclRefExpr::Create(Context,
00362                static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
00363                                                  SS.getRange(),
00364                                                  Name, NameLoc,
00365                                                  TemplateArgs));
00366 }
00367 
00368 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
00369 /// that the template parameter 'PrevDecl' is being shadowed by a new
00370 /// declaration at location Loc. Returns true to indicate that this is
00371 /// an error, and false otherwise.
00372 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
00373   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
00374 
00375   // Microsoft Visual C++ permits template parameters to be shadowed.
00376   if (getLangOptions().Microsoft)
00377     return false;
00378 
00379   // C++ [temp.local]p4:
00380   //   A template-parameter shall not be redeclared within its
00381   //   scope (including nested scopes).
00382   Diag(Loc, diag::err_template_param_shadow)
00383     << cast<NamedDecl>(PrevDecl)->getDeclName();
00384   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
00385   return true;
00386 }
00387 
00388 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
00389 /// the parameter D to reference the templated declaration and return a pointer
00390 /// to the template declaration. Otherwise, do nothing to D and return null.
00391 TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
00392   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
00393     D = DeclPtrTy::make(Temp->getTemplatedDecl());
00394     return Temp;
00395   }
00396   return 0;
00397 }
00398 
00399 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
00400                                             const ParsedTemplateArgument &Arg) {
00401   
00402   switch (Arg.getKind()) {
00403   case ParsedTemplateArgument::Type: {
00404     TypeSourceInfo *DI;
00405     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
00406     if (!DI) 
00407       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
00408     return TemplateArgumentLoc(TemplateArgument(T), DI);
00409   }
00410     
00411   case ParsedTemplateArgument::NonType: {
00412     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
00413     return TemplateArgumentLoc(TemplateArgument(E), E);
00414   }
00415     
00416   case ParsedTemplateArgument::Template: {
00417     TemplateName Template
00418       = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
00419     return TemplateArgumentLoc(TemplateArgument(Template),
00420                                Arg.getScopeSpec().getRange(),
00421                                Arg.getLocation());
00422   }
00423   }
00424   
00425   llvm_unreachable("Unhandled parsed template argument");
00426   return TemplateArgumentLoc();
00427 }
00428                                                      
00429 /// \brief Translates template arguments as provided by the parser
00430 /// into template arguments used by semantic analysis.
00431 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
00432                                       TemplateArgumentListInfo &TemplateArgs) {
00433  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
00434    TemplateArgs.addArgument(translateTemplateArgument(*this,
00435                                                       TemplateArgsIn[I]));
00436 }
00437                                                      
00438 /// ActOnTypeParameter - Called when a C++ template type parameter
00439 /// (e.g., "typename T") has been parsed. Typename specifies whether
00440 /// the keyword "typename" was used to declare the type parameter
00441 /// (otherwise, "class" was used), and KeyLoc is the location of the
00442 /// "class" or "typename" keyword. ParamName is the name of the
00443 /// parameter (NULL indicates an unnamed template parameter) and
00444 /// ParamName is the location of the parameter name (if any).
00445 /// If the type parameter has a default argument, it will be added
00446 /// later via ActOnTypeParameterDefault.
00447 Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
00448                                          SourceLocation EllipsisLoc,
00449                                          SourceLocation KeyLoc,
00450                                          IdentifierInfo *ParamName,
00451                                          SourceLocation ParamNameLoc,
00452                                          unsigned Depth, unsigned Position) {
00453   assert(S->isTemplateParamScope() &&
00454          "Template type parameter not in template parameter scope!");
00455   bool Invalid = false;
00456 
00457   if (ParamName) {
00458     NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
00459                                            LookupOrdinaryName,
00460                                            ForRedeclaration);
00461     if (PrevDecl && PrevDecl->isTemplateParameter())
00462       Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
00463                                                            PrevDecl);
00464   }
00465 
00466   SourceLocation Loc = ParamNameLoc;
00467   if (!ParamName)
00468     Loc = KeyLoc;
00469 
00470   TemplateTypeParmDecl *Param
00471     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00472                                    Loc, Depth, Position, ParamName, Typename,
00473                                    Ellipsis);
00474   if (Invalid)
00475     Param->setInvalidDecl();
00476 
00477   if (ParamName) {
00478     // Add the template parameter into the current scope.
00479     S->AddDecl(DeclPtrTy::make(Param));
00480     IdResolver.AddDecl(Param);
00481   }
00482 
00483   return DeclPtrTy::make(Param);
00484 }
00485 
00486 /// ActOnTypeParameterDefault - Adds a default argument (the type
00487 /// Default) to the given template type parameter (TypeParam).
00488 void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
00489                                      SourceLocation EqualLoc,
00490                                      SourceLocation DefaultLoc,
00491                                      TypeTy *DefaultT) {
00492   TemplateTypeParmDecl *Parm
00493     = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
00494 
00495   TypeSourceInfo *DefaultTInfo;
00496   GetTypeFromParser(DefaultT, &DefaultTInfo);
00497 
00498   assert(DefaultTInfo && "expected source information for type");
00499 
00500   // C++0x [temp.param]p9:
00501   // A default template-argument may be specified for any kind of
00502   // template-parameter that is not a template parameter pack.
00503   if (Parm->isParameterPack()) {
00504     Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
00505     return;
00506   }
00507 
00508   // C++ [temp.param]p14:
00509   //   A template-parameter shall not be used in its own default argument.
00510   // FIXME: Implement this check! Needs a recursive walk over the types.
00511 
00512   // Check the template argument itself.
00513   if (CheckTemplateArgument(Parm, DefaultTInfo)) {
00514     Parm->setInvalidDecl();
00515     return;
00516   }
00517 
00518   Parm->setDefaultArgument(DefaultTInfo, false);
00519 }
00520 
00521 /// \brief Check that the type of a non-type template parameter is
00522 /// well-formed.
00523 ///
00524 /// \returns the (possibly-promoted) parameter type if valid;
00525 /// otherwise, produces a diagnostic and returns a NULL type.
00526 QualType
00527 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
00528   // C++ [temp.param]p4:
00529   //
00530   // A non-type template-parameter shall have one of the following
00531   // (optionally cv-qualified) types:
00532   //
00533   //       -- integral or enumeration type,
00534   if (T->isIntegralType() || T->isEnumeralType() ||
00535       //   -- pointer to object or pointer to function,
00536       (T->isPointerType() &&
00537        (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
00538         T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
00539       //   -- reference to object or reference to function,
00540       T->isReferenceType() ||
00541       //   -- pointer to member.
00542       T->isMemberPointerType() ||
00543       // If T is a dependent type, we can't do the check now, so we
00544       // assume that it is well-formed.
00545       T->isDependentType())
00546     return T;
00547   // C++ [temp.param]p8:
00548   //
00549   //   A non-type template-parameter of type "array of T" or
00550   //   "function returning T" is adjusted to be of type "pointer to
00551   //   T" or "pointer to function returning T", respectively.
00552   else if (T->isArrayType())
00553     // FIXME: Keep the type prior to promotion?
00554     return Context.getArrayDecayedType(T);
00555   else if (T->isFunctionType())
00556     // FIXME: Keep the type prior to promotion?
00557     return Context.getPointerType(T);
00558 
00559   Diag(Loc, diag::err_template_nontype_parm_bad_type)
00560     << T;
00561 
00562   return QualType();
00563 }
00564 
00565 /// ActOnNonTypeTemplateParameter - Called when a C++ non-type
00566 /// template parameter (e.g., "int Size" in "template<int Size>
00567 /// class Array") has been parsed. S is the current scope and D is
00568 /// the parsed declarator.
00569 Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
00570                                                     unsigned Depth,
00571                                                     unsigned Position) {
00572   TypeSourceInfo *TInfo = 0;
00573   QualType T = GetTypeForDeclarator(D, S, &TInfo);
00574 
00575   assert(S->isTemplateParamScope() &&
00576          "Non-type template parameter not in template parameter scope!");
00577   bool Invalid = false;
00578 
00579   IdentifierInfo *ParamName = D.getIdentifier();
00580   if (ParamName) {
00581     NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
00582                                            LookupOrdinaryName,
00583                                            ForRedeclaration);
00584     if (PrevDecl && PrevDecl->isTemplateParameter())
00585       Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
00586                                                            PrevDecl);
00587   }
00588 
00589   T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
00590   if (T.isNull()) {
00591     T = Context.IntTy; // Recover with an 'int' type.
00592     Invalid = true;
00593   }
00594 
00595   NonTypeTemplateParmDecl *Param
00596     = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00597                                       D.getIdentifierLoc(),
00598                                       Depth, Position, ParamName, T, TInfo);
00599   if (Invalid)
00600     Param->setInvalidDecl();
00601 
00602   if (D.getIdentifier()) {
00603     // Add the template parameter into the current scope.
00604     S->AddDecl(DeclPtrTy::make(Param));
00605     IdResolver.AddDecl(Param);
00606   }
00607   return DeclPtrTy::make(Param);
00608 }
00609 
00610 /// \brief Adds a default argument to the given non-type template
00611 /// parameter.
00612 void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
00613                                                 SourceLocation EqualLoc,
00614                                                 ExprArg DefaultE) {
00615   NonTypeTemplateParmDecl *TemplateParm
00616     = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
00617   Expr *Default = static_cast<Expr *>(DefaultE.get());
00618 
00619   // C++ [temp.param]p14:
00620   //   A template-parameter shall not be used in its own default argument.
00621   // FIXME: Implement this check! Needs a recursive walk over the types.
00622 
00623   // Check the well-formedness of the default template argument.
00624   TemplateArgument Converted;
00625   if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
00626                             Converted)) {
00627     TemplateParm->setInvalidDecl();
00628     return;
00629   }
00630 
00631   TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
00632 }
00633 
00634 
00635 /// ActOnTemplateTemplateParameter - Called when a C++ template template
00636 /// parameter (e.g. T in template <template <typename> class T> class array)
00637 /// has been parsed. S is the current scope.
00638 Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
00639                                                      SourceLocation TmpLoc,
00640                                                      TemplateParamsTy *Params,
00641                                                      IdentifierInfo *Name,
00642                                                      SourceLocation NameLoc,
00643                                                      unsigned Depth,
00644                                                      unsigned Position) {
00645   assert(S->isTemplateParamScope() &&
00646          "Template template parameter not in template parameter scope!");
00647 
00648   // Construct the parameter object.
00649   TemplateTemplateParmDecl *Param =
00650     TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
00651                                      TmpLoc, Depth, Position, Name,
00652                                      (TemplateParameterList*)Params);
00653 
00654   // Make sure the parameter is valid.
00655   // FIXME: Decl object is not currently invalidated anywhere so this doesn't
00656   // do anything yet. However, if the template parameter list or (eventual)
00657   // default value is ever invalidated, that will propagate here.
00658   bool Invalid = false;
00659   if (Invalid) {
00660     Param->setInvalidDecl();
00661   }
00662 
00663   // If the tt-param has a name, then link the identifier into the scope
00664   // and lookup mechanisms.
00665   if (Name) {
00666     S->AddDecl(DeclPtrTy::make(Param));
00667     IdResolver.AddDecl(Param);
00668   }
00669 
00670   return DeclPtrTy::make(Param);
00671 }
00672 
00673 /// \brief Adds a default argument to the given template template
00674 /// parameter.
00675 void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
00676                                                  SourceLocation EqualLoc,
00677                                         const ParsedTemplateArgument &Default) {
00678   TemplateTemplateParmDecl *TemplateParm
00679     = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
00680   
00681   // C++ [temp.param]p14:
00682   //   A template-parameter shall not be used in its own default argument.
00683   // FIXME: Implement this check! Needs a recursive walk over the types.
00684 
00685   // Check only that we have a template template argument. We don't want to
00686   // try to check well-formedness now, because our template template parameter
00687   // might have dependent types in its template parameters, which we wouldn't
00688   // be able to match now.
00689   //
00690   // If none of the template template parameter's template arguments mention
00691   // other template parameters, we could actually perform more checking here.
00692   // However, it isn't worth doing.
00693   TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
00694   if (DefaultArg.getArgument().getAsTemplate().isNull()) {
00695     Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
00696       << DefaultArg.getSourceRange();
00697     return;
00698   }
00699   
00700   TemplateParm->setDefaultArgument(DefaultArg);
00701 }
00702 
00703 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
00704 /// contains the template parameters in Params/NumParams.
00705 Sema::TemplateParamsTy *
00706 Sema::ActOnTemplateParameterList(unsigned Depth,
00707                                  SourceLocation ExportLoc,
00708                                  SourceLocation TemplateLoc,
00709                                  SourceLocation LAngleLoc,
00710                                  DeclPtrTy *Params, unsigned NumParams,
00711                                  SourceLocation RAngleLoc) {
00712   if (ExportLoc.isValid())
00713     Diag(ExportLoc, diag::warn_template_export_unsupported);
00714 
00715   return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
00716                                        (NamedDecl**)Params, NumParams, 
00717                                        RAngleLoc);
00718 }
00719 
00720 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
00721   if (SS.isSet())
00722     T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
00723                         SS.getRange());
00724 }
00725 
00726 Sema::DeclResult
00727 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
00728                          SourceLocation KWLoc, CXXScopeSpec &SS,
00729                          IdentifierInfo *Name, SourceLocation NameLoc,
00730                          AttributeList *Attr,
00731                          TemplateParameterList *TemplateParams,
00732                          AccessSpecifier AS) {
00733   assert(TemplateParams && TemplateParams->size() > 0 &&
00734          "No template parameters");
00735   assert(TUK != TUK_Reference && "Can only declare or define class templates");
00736   bool Invalid = false;
00737 
00738   // Check that we can declare a template here.
00739   if (CheckTemplateDeclScope(S, TemplateParams))
00740     return true;
00741 
00742   TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
00743   assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type");
00744 
00745   // There is no such thing as an unnamed class template.
00746   if (!Name) {
00747     Diag(KWLoc, diag::err_template_unnamed_class);
00748     return true;
00749   }
00750 
00751   // Find any previous declaration with this name.
00752   DeclContext *SemanticContext;
00753   LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
00754                         ForRedeclaration);
00755   if (SS.isNotEmpty() && !SS.isInvalid()) {
00756     SemanticContext = computeDeclContext(SS, true);
00757     if (!SemanticContext) {
00758       // FIXME: Produce a reasonable diagnostic here
00759       return true;
00760     }
00761 
00762     if (RequireCompleteDeclContext(SS, SemanticContext))
00763       return true;
00764 
00765     LookupQualifiedName(Previous, SemanticContext);
00766   } else {
00767     SemanticContext = CurContext;
00768     LookupName(Previous, S);
00769   }
00770 
00771   if (Previous.isAmbiguous())
00772     return true;
00773   
00774   NamedDecl *PrevDecl = 0;
00775   if (Previous.begin() != Previous.end())
00776     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
00777 
00778   // If there is a previous declaration with the same name, check
00779   // whether this is a valid redeclaration.
00780   ClassTemplateDecl *PrevClassTemplate
00781     = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
00782 
00783   // We may have found the injected-class-name of a class template,
00784   // class template partial specialization, or class template specialization. 
00785   // In these cases, grab the template that is being defined or specialized.
00786   if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 
00787       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
00788     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
00789     PrevClassTemplate 
00790       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
00791     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
00792       PrevClassTemplate
00793         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
00794             ->getSpecializedTemplate();
00795     }
00796   }
00797 
00798   if (TUK == TUK_Friend) {
00799     // C++ [namespace.memdef]p3:
00800     //   [...] When looking for a prior declaration of a class or a function 
00801     //   declared as a friend, and when the name of the friend class or 
00802     //   function is neither a qualified name nor a template-id, scopes outside
00803     //   the innermost enclosing namespace scope are not considered.
00804     if (!SS.isSet()) {
00805       DeclContext *OutermostContext = CurContext;
00806       while (!OutermostContext->isFileContext())
00807         OutermostContext = OutermostContext->getLookupParent();
00808 
00809       if (PrevDecl &&
00810           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
00811            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
00812         SemanticContext = PrevDecl->getDeclContext();
00813       } else {
00814         // Declarations in outer scopes don't matter. However, the outermost
00815         // context we computed is the semantic context for our new 
00816         // declaration.
00817         PrevDecl = PrevClassTemplate = 0;
00818         SemanticContext = OutermostContext;
00819       }
00820     }
00821 
00822     if (CurContext->isDependentContext()) {
00823       // If this is a dependent context, we don't want to link the friend
00824       // class template to the template in scope, because that would perform
00825       // checking of the template parameter lists that can't be performed
00826       // until the outer context is instantiated.
00827       PrevDecl = PrevClassTemplate = 0;
00828     }
00829   } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
00830     PrevDecl = PrevClassTemplate = 0;
00831   
00832   if (PrevClassTemplate) {
00833     // Ensure that the template parameter lists are compatible.
00834     if (!TemplateParameterListsAreEqual(TemplateParams,
00835                                    PrevClassTemplate->getTemplateParameters(),
00836                                         /*Complain=*/true,
00837                                         TPL_TemplateMatch))
00838       return true;
00839 
00840     // C++ [temp.class]p4:
00841     //   In a redeclaration, partial specialization, explicit
00842     //   specialization or explicit instantiation of a class template,
00843     //   the class-key shall agree in kind with the original class
00844     //   template declaration (7.1.5.3).
00845     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
00846     if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
00847       Diag(KWLoc, diag::err_use_with_wrong_tag)
00848         << Name
00849         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
00850       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
00851       Kind = PrevRecordDecl->getTagKind();
00852     }
00853 
00854     // Check for redefinition of this class template.
00855     if (TUK == TUK_Definition) {
00856       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
00857         Diag(NameLoc, diag::err_redefinition) << Name;
00858         Diag(Def->getLocation(), diag::note_previous_definition);
00859         // FIXME: Would it make sense to try to "forget" the previous
00860         // definition, as part of error recovery?
00861         return true;
00862       }
00863     }
00864   } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
00865     // Maybe we will complain about the shadowed template parameter.
00866     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
00867     // Just pretend that we didn't see the previous declaration.
00868     PrevDecl = 0;
00869   } else if (PrevDecl) {
00870     // C++ [temp]p5:
00871     //   A class template shall not have the same name as any other
00872     //   template, class, function, object, enumeration, enumerator,
00873     //   namespace, or type in the same scope (3.3), except as specified
00874     //   in (14.5.4).
00875     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
00876     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00877     return true;
00878   }
00879 
00880   // Check the template parameter list of this declaration, possibly
00881   // merging in the template parameter list from the previous class
00882   // template declaration.
00883   if (CheckTemplateParameterList(TemplateParams,
00884             PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
00885                                  TPC_ClassTemplate))
00886     Invalid = true;
00887 
00888   if (SS.isSet()) {
00889     // If the name of the template was qualified, we must be defining the 
00890     // template out-of-line.
00891     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
00892         !(TUK == TUK_Friend && CurContext->isDependentContext()))
00893       Diag(NameLoc, diag::err_member_def_does_not_match)
00894         << Name << SemanticContext << SS.getRange();
00895   } 
00896   
00897   CXXRecordDecl *NewClass =
00898     CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
00899                           PrevClassTemplate?
00900                             PrevClassTemplate->getTemplatedDecl() : 0,
00901                           /*DelayTypeCreation=*/true);
00902   SetNestedNameSpecifier(NewClass, SS);
00903 
00904   ClassTemplateDecl *NewTemplate
00905     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
00906                                 DeclarationName(Name), TemplateParams,
00907                                 NewClass, PrevClassTemplate);
00908   NewClass->setDescribedClassTemplate(NewTemplate);
00909 
00910   // Build the type for the class template declaration now.
00911   QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
00912   T = Context.getInjectedClassNameType(NewClass, T);
00913   assert(T->isDependentType() && "Class template type is not dependent?");
00914   (void)T;
00915 
00916   // If we are providing an explicit specialization of a member that is a 
00917   // class template, make a note of that.
00918   if (PrevClassTemplate && 
00919       PrevClassTemplate->getInstantiatedFromMemberTemplate())
00920     PrevClassTemplate->setMemberSpecialization();
00921   
00922   // Set the access specifier.
00923   if (!Invalid && TUK != TUK_Friend)
00924     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
00925 
00926   // Set the lexical context of these templates
00927   NewClass->setLexicalDeclContext(CurContext);
00928   NewTemplate->setLexicalDeclContext(CurContext);
00929 
00930   if (TUK == TUK_Definition)
00931     NewClass->startDefinition();
00932 
00933   if (Attr)
00934     ProcessDeclAttributeList(S, NewClass, Attr);
00935 
00936   if (TUK != TUK_Friend)
00937     PushOnScopeChains(NewTemplate, S);
00938   else {
00939     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
00940       NewTemplate->setAccess(PrevClassTemplate->getAccess());
00941       NewClass->setAccess(PrevClassTemplate->getAccess());
00942     }
00943 
00944     NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
00945                                        PrevClassTemplate != NULL);
00946     
00947     // Friend templates are visible in fairly strange ways.
00948     if (!CurContext->isDependentContext()) {
00949       DeclContext *DC = SemanticContext->getLookupContext();
00950       DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
00951       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
00952         PushOnScopeChains(NewTemplate, EnclosingScope,
00953                           /* AddToContext = */ false);      
00954     }
00955     
00956     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
00957                                             NewClass->getLocation(),
00958                                             NewTemplate,
00959                                     /*FIXME:*/NewClass->getLocation());
00960     Friend->setAccess(AS_public);
00961     CurContext->addDecl(Friend);
00962   }
00963 
00964   if (Invalid) {
00965     NewTemplate->setInvalidDecl();
00966     NewClass->setInvalidDecl();
00967   }
00968   return DeclPtrTy::make(NewTemplate);
00969 }
00970 
00971 /// \brief Diagnose the presence of a default template argument on a
00972 /// template parameter, which is ill-formed in certain contexts.
00973 ///
00974 /// \returns true if the default template argument should be dropped.
00975 static bool DiagnoseDefaultTemplateArgument(Sema &S, 
00976                                             Sema::TemplateParamListContext TPC,
00977                                             SourceLocation ParamLoc,
00978                                             SourceRange DefArgRange) {
00979   switch (TPC) {
00980   case Sema::TPC_ClassTemplate:
00981     return false;
00982 
00983   case Sema::TPC_FunctionTemplate:
00984     // C++ [temp.param]p9: 
00985     //   A default template-argument shall not be specified in a
00986     //   function template declaration or a function template
00987     //   definition [...]
00988     // (This sentence is not in C++0x, per DR226).
00989     if (!S.getLangOptions().CPlusPlus0x)
00990       S.Diag(ParamLoc, 
00991              diag::err_template_parameter_default_in_function_template)
00992         << DefArgRange;
00993     return false;
00994 
00995   case Sema::TPC_ClassTemplateMember:
00996     // C++0x [temp.param]p9:
00997     //   A default template-argument shall not be specified in the
00998     //   template-parameter-lists of the definition of a member of a
00999     //   class template that appears outside of the member's class.
01000     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
01001       << DefArgRange;
01002     return true;
01003 
01004   case Sema::TPC_FriendFunctionTemplate:
01005     // C++ [temp.param]p9:
01006     //   A default template-argument shall not be specified in a
01007     //   friend template declaration.
01008     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
01009       << DefArgRange;
01010     return true;
01011 
01012     // FIXME: C++0x [temp.param]p9 allows default template-arguments
01013     // for friend function templates if there is only a single
01014     // declaration (and it is a definition). Strange!
01015   }
01016 
01017   return false;
01018 }
01019 
01020 /// \brief Checks the validity of a template parameter list, possibly
01021 /// considering the template parameter list from a previous
01022 /// declaration.
01023 ///
01024 /// If an "old" template parameter list is provided, it must be
01025 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
01026 /// template parameter list.
01027 ///
01028 /// \param NewParams Template parameter list for a new template
01029 /// declaration. This template parameter list will be updated with any
01030 /// default arguments that are carried through from the previous
01031 /// template parameter list.
01032 ///
01033 /// \param OldParams If provided, template parameter list from a
01034 /// previous declaration of the same template. Default template
01035 /// arguments will be merged from the old template parameter list to
01036 /// the new template parameter list.
01037 ///
01038 /// \param TPC Describes the context in which we are checking the given
01039 /// template parameter list.
01040 ///
01041 /// \returns true if an error occurred, false otherwise.
01042 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
01043                                       TemplateParameterList *OldParams,
01044                                       TemplateParamListContext TPC) {
01045   bool Invalid = false;
01046 
01047   // C++ [temp.param]p10:
01048   //   The set of default template-arguments available for use with a
01049   //   template declaration or definition is obtained by merging the
01050   //   default arguments from the definition (if in scope) and all
01051   //   declarations in scope in the same way default function
01052   //   arguments are (8.3.6).
01053   bool SawDefaultArgument = false;
01054   SourceLocation PreviousDefaultArgLoc;
01055 
01056   bool SawParameterPack = false;
01057   SourceLocation ParameterPackLoc;
01058 
01059   // Dummy initialization to avoid warnings.
01060   TemplateParameterList::iterator OldParam = NewParams->end();
01061   if (OldParams)
01062     OldParam = OldParams->begin();
01063 
01064   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
01065                                     NewParamEnd = NewParams->end();
01066        NewParam != NewParamEnd; ++NewParam) {
01067     // Variables used to diagnose redundant default arguments
01068     bool RedundantDefaultArg = false;
01069     SourceLocation OldDefaultLoc;
01070     SourceLocation NewDefaultLoc;
01071 
01072     // Variables used to diagnose missing default arguments
01073     bool MissingDefaultArg = false;
01074 
01075     // C++0x [temp.param]p11:
01076     // If a template parameter of a class template is a template parameter pack,
01077     // it must be the last template parameter.
01078     if (SawParameterPack) {
01079       Diag(ParameterPackLoc,
01080            diag::err_template_param_pack_must_be_last_template_parameter);
01081       Invalid = true;
01082     }
01083 
01084     if (TemplateTypeParmDecl *NewTypeParm
01085           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
01086       // Check the presence of a default argument here.
01087       if (NewTypeParm->hasDefaultArgument() && 
01088           DiagnoseDefaultTemplateArgument(*this, TPC, 
01089                                           NewTypeParm->getLocation(), 
01090                NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
01091                                                        .getFullSourceRange()))
01092         NewTypeParm->removeDefaultArgument();
01093 
01094       // Merge default arguments for template type parameters.
01095       TemplateTypeParmDecl *OldTypeParm
01096           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
01097 
01098       if (NewTypeParm->isParameterPack()) {
01099         assert(!NewTypeParm->hasDefaultArgument() &&
01100                "Parameter packs can't have a default argument!");
01101         SawParameterPack = true;
01102         ParameterPackLoc = NewTypeParm->getLocation();
01103       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
01104                  NewTypeParm->hasDefaultArgument()) {
01105         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
01106         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
01107         SawDefaultArgument = true;
01108         RedundantDefaultArg = true;
01109         PreviousDefaultArgLoc = NewDefaultLoc;
01110       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
01111         // Merge the default argument from the old declaration to the
01112         // new declaration.
01113         SawDefaultArgument = true;
01114         NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
01115                                         true);
01116         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
01117       } else if (NewTypeParm->hasDefaultArgument()) {
01118         SawDefaultArgument = true;
01119         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
01120       } else if (SawDefaultArgument)
01121         MissingDefaultArg = true;
01122     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
01123                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
01124       // Check the presence of a default argument here.
01125       if (NewNonTypeParm->hasDefaultArgument() && 
01126           DiagnoseDefaultTemplateArgument(*this, TPC, 
01127                                           NewNonTypeParm->getLocation(), 
01128                     NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
01129         NewNonTypeParm->getDefaultArgument()->Destroy(Context);
01130         NewNonTypeParm->setDefaultArgument(0);
01131       }
01132 
01133       // Merge default arguments for non-type template parameters
01134       NonTypeTemplateParmDecl *OldNonTypeParm
01135         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
01136       if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
01137           NewNonTypeParm->hasDefaultArgument()) {
01138         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
01139         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
01140         SawDefaultArgument = true;
01141         RedundantDefaultArg = true;
01142         PreviousDefaultArgLoc = NewDefaultLoc;
01143       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
01144         // Merge the default argument from the old declaration to the
01145         // new declaration.
01146         SawDefaultArgument = true;
01147         // FIXME: We need to create a new kind of "default argument"
01148         // expression that points to a previous template template
01149         // parameter.
01150         NewNonTypeParm->setDefaultArgument(
01151                                         OldNonTypeParm->getDefaultArgument());
01152         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
01153       } else if (NewNonTypeParm->hasDefaultArgument()) {
01154         SawDefaultArgument = true;
01155         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
01156       } else if (SawDefaultArgument)
01157         MissingDefaultArg = true;
01158     } else {
01159       // Check the presence of a default argument here.
01160       TemplateTemplateParmDecl *NewTemplateParm
01161         = cast<TemplateTemplateParmDecl>(*NewParam);
01162       if (NewTemplateParm->hasDefaultArgument() && 
01163           DiagnoseDefaultTemplateArgument(*this, TPC, 
01164                                           NewTemplateParm->getLocation(), 
01165                      NewTemplateParm->getDefaultArgument().getSourceRange()))
01166         NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
01167 
01168       // Merge default arguments for template template parameters
01169       TemplateTemplateParmDecl *OldTemplateParm
01170         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
01171       if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
01172           NewTemplateParm->hasDefaultArgument()) {
01173         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
01174         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
01175         SawDefaultArgument = true;
01176         RedundantDefaultArg = true;
01177         PreviousDefaultArgLoc = NewDefaultLoc;
01178       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
01179         // Merge the default argument from the old declaration to the
01180         // new declaration.
01181         SawDefaultArgument = true;
01182         // FIXME: We need to create a new kind of "default argument" expression
01183         // that points to a previous template template parameter.
01184         NewTemplateParm->setDefaultArgument(
01185                                         OldTemplateParm->getDefaultArgument());
01186         PreviousDefaultArgLoc
01187           = OldTemplateParm->getDefaultArgument().getLocation();
01188       } else if (NewTemplateParm->hasDefaultArgument()) {
01189         SawDefaultArgument = true;
01190         PreviousDefaultArgLoc
01191           = NewTemplateParm->getDefaultArgument().getLocation();
01192       } else if (SawDefaultArgument)
01193         MissingDefaultArg = true;
01194     }
01195 
01196     if (RedundantDefaultArg) {
01197       // C++ [temp.param]p12:
01198       //   A template-parameter shall not be given default arguments
01199       //   by two different declarations in the same scope.
01200       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
01201       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
01202       Invalid = true;
01203     } else if (MissingDefaultArg) {
01204       // C++ [temp.param]p11:
01205       //   If a template-parameter has a default template-argument,
01206       //   all subsequent template-parameters shall have a default
01207       //   template-argument supplied.
01208       Diag((*NewParam)->getLocation(),
01209            diag::err_template_param_default_arg_missing);
01210       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
01211       Invalid = true;
01212     }
01213 
01214     // If we have an old template parameter list that we're merging
01215     // in, move on to the next parameter.
01216     if (OldParams)
01217       ++OldParam;
01218   }
01219 
01220   return Invalid;
01221 }
01222 
01223 /// \brief Match the given template parameter lists to the given scope
01224 /// specifier, returning the template parameter list that applies to the
01225 /// name.
01226 ///
01227 /// \param DeclStartLoc the start of the declaration that has a scope
01228 /// specifier or a template parameter list.
01229 ///
01230 /// \param SS the scope specifier that will be matched to the given template
01231 /// parameter lists. This scope specifier precedes a qualified name that is
01232 /// being declared.
01233 ///
01234 /// \param ParamLists the template parameter lists, from the outermost to the
01235 /// innermost template parameter lists.
01236 ///
01237 /// \param NumParamLists the number of template parameter lists in ParamLists.
01238 ///
01239 /// \param IsFriend Whether to apply the slightly different rules for
01240 /// matching template parameters to scope specifiers in friend
01241 /// declarations.
01242 ///
01243 /// \param IsExplicitSpecialization will be set true if the entity being
01244 /// declared is an explicit specialization, false otherwise.
01245 ///
01246 /// \returns the template parameter list, if any, that corresponds to the
01247 /// name that is preceded by the scope specifier @p SS. This template
01248 /// parameter list may be have template parameters (if we're declaring a
01249 /// template) or may have no template parameters (if we're declaring a
01250 /// template specialization), or may be NULL (if we were's declaring isn't
01251 /// itself a template).
01252 TemplateParameterList *
01253 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
01254                                               const CXXScopeSpec &SS,
01255                                           TemplateParameterList **ParamLists,
01256                                               unsigned NumParamLists,
01257                                               bool IsFriend,
01258                                               bool &IsExplicitSpecialization) {
01259   IsExplicitSpecialization = false;
01260   
01261   // Find the template-ids that occur within the nested-name-specifier. These
01262   // template-ids will match up with the template parameter lists.
01263   llvm::SmallVector<const TemplateSpecializationType *, 4>
01264     TemplateIdsInSpecifier;
01265   llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
01266     ExplicitSpecializationsInSpecifier;
01267   for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
01268        NNS; NNS = NNS->getPrefix()) {
01269     const Type *T = NNS->getAsType();
01270     if (!T) break;
01271 
01272     // C++0x [temp.expl.spec]p17:
01273     //   A member or a member template may be nested within many
01274     //   enclosing class templates. In an explicit specialization for
01275     //   such a member, the member declaration shall be preceded by a
01276     //   template<> for each enclosing class template that is
01277     //   explicitly specialized.
01278     //
01279     // Following the existing practice of GNU and EDG, we allow a typedef of a
01280     // template specialization type.
01281     if (const TypedefType *TT = dyn_cast<TypedefType>(T))
01282       T = TT->LookThroughTypedefs().getTypePtr();
01283 
01284     if (const TemplateSpecializationType *SpecType
01285                                   = dyn_cast<TemplateSpecializationType>(T)) {
01286       TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
01287       if (!Template)
01288         continue; // FIXME: should this be an error? probably...
01289 
01290       if (const RecordType *Record = SpecType->getAs<RecordType>()) {
01291         ClassTemplateSpecializationDecl *SpecDecl
01292           = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
01293         // If the nested name specifier refers to an explicit specialization,
01294         // we don't need a template<> header.
01295         if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
01296           ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
01297           continue;
01298         }
01299       }
01300 
01301       TemplateIdsInSpecifier.push_back(SpecType);
01302     }
01303   }
01304 
01305   // Reverse the list of template-ids in the scope specifier, so that we can
01306   // more easily match up the template-ids and the template parameter lists.
01307   std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
01308 
01309   SourceLocation FirstTemplateLoc = DeclStartLoc;
01310   if (NumParamLists)
01311     FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
01312 
01313   // Match the template-ids found in the specifier to the template parameter
01314   // lists.
01315   unsigned Idx = 0;
01316   for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
01317        Idx != NumTemplateIds; ++Idx) {
01318     QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
01319     bool DependentTemplateId = TemplateId->isDependentType();
01320     if (Idx >= NumParamLists) {
01321       // We have a template-id without a corresponding template parameter
01322       // list.
01323 
01324       // ...which is fine if this is a friend declaration.
01325       if (IsFriend) {
01326         IsExplicitSpecialization = true;
01327         break;
01328       }
01329 
01330       if (DependentTemplateId) {
01331         // FIXME: the location information here isn't great.
01332         Diag(SS.getRange().getBegin(),
01333              diag::err_template_spec_needs_template_parameters)
01334           << TemplateId
01335           << SS.getRange();
01336       } else {
01337         Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
01338           << SS.getRange()
01339           << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
01340         IsExplicitSpecialization = true;
01341       }
01342       return 0;
01343     }
01344 
01345     // Check the template parameter list against its corresponding template-id.
01346     if (DependentTemplateId) {
01347       TemplateParameterList *ExpectedTemplateParams = 0;
01348 
01349       // Are there cases in (e.g.) friends where this won't match?
01350       if (const InjectedClassNameType *Injected
01351             = TemplateId->getAs<InjectedClassNameType>()) {
01352         CXXRecordDecl *Record = Injected->getDecl();
01353         if (ClassTemplatePartialSpecializationDecl *Partial =
01354               dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
01355           ExpectedTemplateParams = Partial->getTemplateParameters();
01356         else
01357           ExpectedTemplateParams = Record->getDescribedClassTemplate()
01358             ->getTemplateParameters();
01359       }
01360 
01361       if (ExpectedTemplateParams)
01362         TemplateParameterListsAreEqual(ParamLists[Idx],
01363                                        ExpectedTemplateParams,
01364                                        true, TPL_TemplateMatch);
01365 
01366       CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
01367     } else if (ParamLists[Idx]->size() > 0)
01368       Diag(ParamLists[Idx]->getTemplateLoc(),
01369            diag::err_template_param_list_matches_nontemplate)
01370         << TemplateId
01371         << ParamLists[Idx]->getSourceRange();
01372     else
01373       IsExplicitSpecialization = true;
01374   }
01375 
01376   // If there were at least as many template-ids as there were template
01377   // parameter lists, then there are no template parameter lists remaining for
01378   // the declaration itself.
01379   if (Idx >= NumParamLists)
01380     return 0;
01381 
01382   // If there were too many template parameter lists, complain about that now.
01383   if (Idx != NumParamLists - 1) {
01384     while (Idx < NumParamLists - 1) {
01385       bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
01386       Diag(ParamLists[Idx]->getTemplateLoc(),
01387            isExplicitSpecHeader? diag::warn_template_spec_extra_headers
01388                                : diag::err_template_spec_extra_headers)
01389         << SourceRange(ParamLists[Idx]->getTemplateLoc(),
01390                        ParamLists[Idx]->getRAngleLoc());
01391 
01392       if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
01393         Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
01394              diag::note_explicit_template_spec_does_not_need_header)
01395           << ExplicitSpecializationsInSpecifier.back();
01396         ExplicitSpecializationsInSpecifier.pop_back();
01397       }
01398         
01399       ++Idx;
01400     }
01401   }
01402 
01403   // Return the last template parameter list, which corresponds to the
01404   // entity being declared.
01405   return ParamLists[NumParamLists - 1];
01406 }
01407 
01408 QualType Sema::CheckTemplateIdType(TemplateName Name,
01409                                    SourceLocation TemplateLoc,
01410                               const TemplateArgumentListInfo &TemplateArgs) {
01411   TemplateDecl *Template = Name.getAsTemplateDecl();
01412   if (!Template) {
01413     // The template name does not resolve to a template, so we just
01414     // build a dependent template-id type.
01415     return Context.getTemplateSpecializationType(Name, TemplateArgs);
01416   }
01417 
01418   // Check that the template argument list is well-formed for this
01419   // template.
01420   TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
01421                                         TemplateArgs.size());
01422   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
01423                                 false, Converted))
01424     return QualType();
01425 
01426   assert((Converted.structuredSize() ==
01427             Template->getTemplateParameters()->size()) &&
01428          "Converted template argument list is too short!");
01429 
01430   QualType CanonType;
01431   bool IsCurrentInstantiation = false;
01432 
01433   if (Name.isDependent() ||
01434       TemplateSpecializationType::anyDependentTemplateArguments(
01435                                                       TemplateArgs)) {
01436     // This class template specialization is a dependent
01437     // type. Therefore, its canonical type is another class template
01438     // specialization type that contains all of the converted
01439     // arguments in canonical form. This ensures that, e.g., A<T> and
01440     // A<T, T> have identical types when A is declared as:
01441     //
01442     //   template<typename T, typename U = T> struct A;
01443     TemplateName CanonName = Context.getCanonicalTemplateName(Name);
01444     CanonType = Context.getTemplateSpecializationType(CanonName,
01445                                                    Converted.getFlatArguments(),
01446                                                    Converted.flatSize());
01447 
01448     // FIXME: CanonType is not actually the canonical type, and unfortunately
01449     // it is a TemplateSpecializationType that we will never use again.
01450     // In the future, we need to teach getTemplateSpecializationType to only
01451     // build the canonical type and return that to us.
01452     CanonType = Context.getCanonicalType(CanonType);
01453 
01454     // This might work out to be a current instantiation, in which
01455     // case the canonical type needs to be the InjectedClassNameType.
01456     //
01457     // TODO: in theory this could be a simple hashtable lookup; most
01458     // changes to CurContext don't change the set of current
01459     // instantiations.
01460     if (isa<ClassTemplateDecl>(Template)) {
01461       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
01462         // If we get out to a namespace, we're done.
01463         if (Ctx->isFileContext()) break;
01464 
01465         // If this isn't a record, keep looking.
01466         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
01467         if (!Record) continue;
01468 
01469         // Look for one of the two cases with InjectedClassNameTypes
01470         // and check whether it's the same template.
01471         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
01472             !Record->getDescribedClassTemplate())
01473           continue;
01474           
01475         // Fetch the injected class name type and check whether its
01476         // injected type is equal to the type we just built.
01477         QualType ICNT = Context.getTypeDeclType(Record);
01478         QualType Injected = cast<InjectedClassNameType>(ICNT)
01479           ->getInjectedSpecializationType();
01480 
01481         if (CanonType != Injected->getCanonicalTypeInternal())
01482           continue;
01483 
01484         // If so, the canonical type of this TST is the injected
01485         // class name type of the record we just found.
01486         assert(ICNT.isCanonical());
01487         CanonType = ICNT;
01488         IsCurrentInstantiation = true;
01489         break;
01490       }
01491     }
01492   } else if (ClassTemplateDecl *ClassTemplate
01493                = dyn_cast<ClassTemplateDecl>(Template)) {
01494     // Find the class template specialization declaration that
01495     // corresponds to these arguments.
01496     llvm::FoldingSetNodeID ID;
01497     ClassTemplateSpecializationDecl::Profile(ID,
01498                                              Converted.getFlatArguments(),
01499                                              Converted.flatSize(),
01500                                              Context);
01501     void *InsertPos = 0;
01502     ClassTemplateSpecializationDecl *Decl
01503       = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
01504     if (!Decl) {
01505       // This is the first time we have referenced this class template
01506       // specialization. Create the canonical declaration and add it to
01507       // the set of specializations.
01508       Decl = ClassTemplateSpecializationDecl::Create(Context,
01509                             ClassTemplate->getTemplatedDecl()->getTagKind(),
01510                                                 ClassTemplate->getDeclContext(),
01511                                                 ClassTemplate->getLocation(),
01512                                                 ClassTemplate,
01513                                                 Converted, 0);
01514       ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
01515       Decl->setLexicalDeclContext(CurContext);
01516     }
01517 
01518     CanonType = Context.getTypeDeclType(Decl);
01519     assert(isa<RecordType>(CanonType) &&
01520            "type of non-dependent specialization is not a RecordType");
01521   }
01522 
01523   // Build the fully-sugared type for this class template
01524   // specialization, which refers back to the class template
01525   // specialization we created or found.
01526   return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
01527                                                IsCurrentInstantiation);
01528 }
01529 
01530 Action::TypeResult
01531 Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
01532                           SourceLocation LAngleLoc,
01533                           ASTTemplateArgsPtr TemplateArgsIn,
01534                           SourceLocation RAngleLoc) {
01535   TemplateName Template = TemplateD.getAsVal<TemplateName>();
01536 
01537   // Translate the parser's template argument list in our AST format.
01538   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
01539   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
01540 
01541   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
01542   TemplateArgsIn.release();
01543 
01544   if (Result.isNull())
01545     return true;
01546 
01547   TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
01548   TemplateSpecializationTypeLoc TL
01549     = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
01550   TL.setTemplateNameLoc(TemplateLoc);
01551   TL.setLAngleLoc(LAngleLoc);
01552   TL.setRAngleLoc(RAngleLoc);
01553   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
01554     TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
01555 
01556   return CreateLocInfoType(Result, DI).getAsOpaquePtr();
01557 }
01558 
01559 Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
01560                                               TagUseKind TUK,
01561                                               DeclSpec::TST TagSpec,
01562                                               SourceLocation TagLoc) {
01563   if (TypeResult.isInvalid())
01564     return Sema::TypeResult();
01565 
01566   // FIXME: preserve source info, ideally without copying the DI.
01567   TypeSourceInfo *DI;
01568   QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
01569 
01570   // Verify the tag specifier.
01571   TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec);
01572 
01573   if (const RecordType *RT = Type->getAs<RecordType>()) {
01574     RecordDecl *D = RT->getDecl();
01575 
01576     IdentifierInfo *Id = D->getIdentifier();
01577     assert(Id && "templated class must have an identifier");
01578 
01579     if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
01580       Diag(TagLoc, diag::err_use_with_wrong_tag)
01581         << Type
01582         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
01583       Diag(D->getLocation(), diag::note_previous_use);
01584     }
01585   }
01586 
01587   QualType ElabType = Context.getElaboratedType(Type, TagKind);
01588 
01589   return ElabType.getAsOpaquePtr();
01590 }
01591 
01592 Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
01593                                                  LookupResult &R,
01594                                                  bool RequiresADL,
01595                                  const TemplateArgumentListInfo &TemplateArgs) {
01596   // FIXME: Can we do any checking at this point? I guess we could check the
01597   // template arguments that we have against the template name, if the template
01598   // name refers to a single template. That's not a terribly common case,
01599   // though.
01600 
01601   // These should be filtered out by our callers.
01602   assert(!R.empty() && "empty lookup results when building templateid");
01603   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
01604 
01605   NestedNameSpecifier *Qualifier = 0;
01606   SourceRange QualifierRange;
01607   if (SS.isSet()) {
01608     Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
01609     QualifierRange = SS.getRange();
01610   }
01611 
01612   // We don't want lookup warnings at this point.
01613   R.suppressDiagnostics();
01614   
01615   bool Dependent
01616     = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
01617                                               &TemplateArgs);
01618   UnresolvedLookupExpr *ULE
01619     = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
01620                                    Qualifier, QualifierRange,
01621                                    R.getLookupName(), R.getNameLoc(),
01622                                    RequiresADL, TemplateArgs);
01623   ULE->addDecls(R.begin(), R.end());
01624 
01625   return Owned(ULE);
01626 }
01627 
01628 // We actually only call this from template instantiation.
01629 Sema::OwningExprResult
01630 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
01631                                    DeclarationName Name,
01632                                    SourceLocation NameLoc,
01633                              const TemplateArgumentListInfo &TemplateArgs) {
01634   DeclContext *DC;
01635   if (!(DC = computeDeclContext(SS, false)) ||
01636       DC->isDependentContext() ||
01637       RequireCompleteDeclContext(SS, DC))
01638     return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
01639 
01640   LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
01641   LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false);
01642 
01643   if (R.isAmbiguous())
01644     return ExprError();
01645   
01646   if (R.empty()) {
01647     Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
01648       << Name << SS.getRange();
01649     return ExprError();
01650   }
01651 
01652   if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
01653     Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
01654       << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
01655     Diag(Temp->getLocation(), diag::note_referenced_class_template);
01656     return ExprError();
01657   }
01658 
01659   return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
01660 }
01661 
01662 /// \brief Form a dependent template name.
01663 ///
01664 /// This action forms a dependent template name given the template
01665 /// name and its (presumably dependent) scope specifier. For
01666 /// example, given "MetaFun::template apply", the scope specifier \p
01667 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
01668 /// of the "template" keyword, and "apply" is the \p Name.
01669 Sema::TemplateTy
01670 Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
01671                                  CXXScopeSpec &SS,
01672                                  UnqualifiedId &Name,
01673                                  TypeTy *ObjectType,
01674                                  bool EnteringContext) {
01675   DeclContext *LookupCtx = 0;
01676   if (SS.isSet())
01677     LookupCtx = computeDeclContext(SS, EnteringContext);
01678   if (!LookupCtx && ObjectType)
01679     LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
01680   if (LookupCtx) {
01681     // C++0x [temp.names]p5:
01682     //   If a name prefixed by the keyword template is not the name of
01683     //   a template, the program is ill-formed. [Note: the keyword
01684     //   template may not be applied to non-template members of class
01685     //   templates. -end note ] [ Note: as is the case with the
01686     //   typename prefix, the template prefix is allowed in cases
01687     //   where it is not strictly necessary; i.e., when the
01688     //   nested-name-specifier or the expression on the left of the ->
01689     //   or . is not dependent on a template-parameter, or the use
01690     //   does not appear in the scope of a template. -end note]
01691     //
01692     // Note: C++03 was more strict here, because it banned the use of
01693     // the "template" keyword prior to a template-name that was not a
01694     // dependent name. C++ DR468 relaxed this requirement (the
01695     // "template" keyword is now permitted). We follow the C++0x
01696     // rules, even in C++03 mode, retroactively applying the DR.
01697     TemplateTy Template;
01698     TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
01699                                           EnteringContext, Template);
01700     if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
01701         isa<CXXRecordDecl>(LookupCtx) &&
01702         cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
01703       // This is a dependent template.
01704     } else if (TNK == TNK_Non_template) {
01705       Diag(Name.getSourceRange().getBegin(), 
01706            diag::err_template_kw_refers_to_non_template)
01707         << GetNameFromUnqualifiedId(Name)
01708         << Name.getSourceRange()
01709         << TemplateKWLoc;
01710       return TemplateTy();
01711     } else {
01712       // We found something; return it.
01713       return Template;
01714     }
01715   }
01716 
01717   NestedNameSpecifier *Qualifier
01718     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
01719   
01720   switch (Name.getKind()) {
01721   case UnqualifiedId::IK_Identifier:
01722     return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 
01723                                                              Name.Identifier));
01724     
01725   case UnqualifiedId::IK_OperatorFunctionId:
01726     return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
01727                                              Name.OperatorFunctionId.Operator));
01728 
01729   case UnqualifiedId::IK_LiteralOperatorId:
01730     assert(false && "We don't support these; Parse shouldn't have allowed propagation");
01731 
01732   default:
01733     break;
01734   }
01735   
01736   Diag(Name.getSourceRange().getBegin(), 
01737        diag::err_template_kw_refers_to_non_template)
01738     << GetNameFromUnqualifiedId(Name)
01739     << Name.getSourceRange()
01740     << TemplateKWLoc;
01741   return TemplateTy();
01742 }
01743 
01744 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
01745                                      const TemplateArgumentLoc &AL,
01746                                      TemplateArgumentListBuilder &Converted) {
01747   const TemplateArgument &Arg = AL.getArgument();
01748 
01749   // Check template type parameter.
01750   switch(Arg.getKind()) {
01751   case TemplateArgument::Type:
01752     // C++ [temp.arg.type]p1:
01753     //   A template-argument for a template-parameter which is a
01754     //   type shall be a type-id.
01755     break;
01756   case TemplateArgument::Template: {
01757     // We have a template type parameter but the template argument
01758     // is a template without any arguments.
01759     SourceRange SR = AL.getSourceRange();
01760     TemplateName Name = Arg.getAsTemplate();
01761     Diag(SR.getBegin(), diag::err_template_missing_args)
01762       << Name << SR;
01763     if (TemplateDecl *Decl = Name.getAsTemplateDecl())
01764       Diag(Decl->getLocation(), diag::note_template_decl_here);
01765 
01766     return true;
01767   }
01768   default: {
01769     // We have a template type parameter but the template argument
01770     // is not a type.
01771     SourceRange SR = AL.getSourceRange();
01772     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
01773     Diag(Param->getLocation(), diag::note_template_param_here);
01774 
01775     return true;
01776   }
01777   }
01778 
01779   if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
01780     return true;
01781 
01782   // Add the converted template type argument.
01783   Converted.Append(
01784                  TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
01785   return false;
01786 }
01787 
01788 /// \brief Substitute template arguments into the default template argument for
01789 /// the given template type parameter.
01790 ///
01791 /// \param SemaRef the semantic analysis object for which we are performing
01792 /// the substitution.
01793 ///
01794 /// \param Template the template that we are synthesizing template arguments 
01795 /// for.
01796 ///
01797 /// \param TemplateLoc the location of the template name that started the
01798 /// template-id we are checking.
01799 ///
01800 /// \param RAngleLoc the location of the right angle bracket ('>') that
01801 /// terminates the template-id.
01802 ///
01803 /// \param Param the template template parameter whose default we are
01804 /// substituting into.
01805 ///
01806 /// \param Converted the list of template arguments provided for template
01807 /// parameters that precede \p Param in the template parameter list.
01808 ///
01809 /// \returns the substituted template argument, or NULL if an error occurred.
01810 static TypeSourceInfo *
01811 SubstDefaultTemplateArgument(Sema &SemaRef,
01812                              TemplateDecl *Template,
01813                              SourceLocation TemplateLoc,
01814                              SourceLocation RAngleLoc,
01815                              TemplateTypeParmDecl *Param,
01816                              TemplateArgumentListBuilder &Converted) {
01817   TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
01818 
01819   // If the argument type is dependent, instantiate it now based
01820   // on the previously-computed template arguments.
01821   if (ArgType->getType()->isDependentType()) {
01822     TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
01823                                       /*TakeArgs=*/false);
01824     
01825     MultiLevelTemplateArgumentList AllTemplateArgs
01826       = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
01827 
01828     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
01829                                      Template, Converted.getFlatArguments(),
01830                                      Converted.flatSize(),
01831                                      SourceRange(TemplateLoc, RAngleLoc));
01832     
01833     ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
01834                                 Param->getDefaultArgumentLoc(),
01835                                 Param->getDeclName());
01836   }
01837 
01838   return ArgType;
01839 }
01840 
01841 /// \brief Substitute template arguments into the default template argument for
01842 /// the given non-type template parameter.
01843 ///
01844 /// \param SemaRef the semantic analysis object for which we are performing
01845 /// the substitution.
01846 ///
01847 /// \param Template the template that we are synthesizing template arguments 
01848 /// for.
01849 ///
01850 /// \param TemplateLoc the location of the template name that started the
01851 /// template-id we are checking.
01852 ///
01853 /// \param RAngleLoc the location of the right angle bracket ('>') that
01854 /// terminates the template-id.
01855 ///
01856 /// \param Param the non-type template parameter whose default we are
01857 /// substituting into.
01858 ///
01859 /// \param Converted the list of template arguments provided for template
01860 /// parameters that precede \p Param in the template parameter list.
01861 ///
01862 /// \returns the substituted template argument, or NULL if an error occurred.
01863 static Sema::OwningExprResult
01864 SubstDefaultTemplateArgument(Sema &SemaRef,
01865                              TemplateDecl *Template,
01866                              SourceLocation TemplateLoc,
01867                              SourceLocation RAngleLoc,
01868                              NonTypeTemplateParmDecl *Param,
01869                              TemplateArgumentListBuilder &Converted) {
01870   TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
01871                                     /*TakeArgs=*/false);
01872     
01873   MultiLevelTemplateArgumentList AllTemplateArgs
01874     = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
01875     
01876   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
01877                                    Template, Converted.getFlatArguments(),
01878                                    Converted.flatSize(),
01879                                    SourceRange(TemplateLoc, RAngleLoc));
01880 
01881   return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
01882 }
01883 
01884 /// \brief Substitute template arguments into the default template argument for
01885 /// the given template template parameter.
01886 ///
01887 /// \param SemaRef the semantic analysis object for which we are performing
01888 /// the substitution.
01889 ///
01890 /// \param Template the template that we are synthesizing template arguments 
01891 /// for.
01892 ///
01893 /// \param TemplateLoc the location of the template name that started the
01894 /// template-id we are checking.
01895 ///
01896 /// \param RAngleLoc the location of the right angle bracket ('>') that
01897 /// terminates the template-id.
01898 ///
01899 /// \param Param the template template parameter whose default we are
01900 /// substituting into.
01901 ///
01902 /// \param Converted the list of template arguments provided for template
01903 /// parameters that precede \p Param in the template parameter list.
01904 ///
01905 /// \returns the substituted template argument, or NULL if an error occurred.
01906 static TemplateName
01907 SubstDefaultTemplateArgument(Sema &SemaRef,
01908                              TemplateDecl *Template,
01909                              SourceLocation TemplateLoc,
01910                              SourceLocation RAngleLoc,
01911                              TemplateTemplateParmDecl *Param,
01912                              TemplateArgumentListBuilder &Converted) {
01913   TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
01914                                     /*TakeArgs=*/false);
01915   
01916   MultiLevelTemplateArgumentList AllTemplateArgs
01917     = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
01918   
01919   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
01920                                    Template, Converted.getFlatArguments(),
01921                                    Converted.flatSize(),
01922                                    SourceRange(TemplateLoc, RAngleLoc));
01923   
01924   return SemaRef.SubstTemplateName(
01925                       Param->getDefaultArgument().getArgument().getAsTemplate(),
01926                               Param->getDefaultArgument().getTemplateNameLoc(), 
01927                                    AllTemplateArgs);
01928 }
01929 
01930 /// \brief If the given template parameter has a default template
01931 /// argument, substitute into that default template argument and
01932 /// return the corresponding template argument.
01933 TemplateArgumentLoc 
01934 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
01935                                               SourceLocation TemplateLoc,
01936                                               SourceLocation RAngleLoc,
01937                                               Decl *Param,
01938                                      TemplateArgumentListBuilder &Converted) {
01939   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
01940     if (!TypeParm->hasDefaultArgument())
01941       return TemplateArgumentLoc();
01942 
01943     TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
01944                                                       TemplateLoc,
01945                                                       RAngleLoc,
01946                                                       TypeParm,
01947                                                       Converted);
01948     if (DI)
01949       return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
01950 
01951     return TemplateArgumentLoc();
01952   }
01953 
01954   if (NonTypeTemplateParmDecl *NonTypeParm
01955         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
01956     if (!NonTypeParm->hasDefaultArgument())
01957       return TemplateArgumentLoc();
01958 
01959     OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
01960                                                         TemplateLoc,
01961                                                         RAngleLoc,
01962                                                         NonTypeParm,
01963                                                         Converted);
01964     if (Arg.isInvalid())
01965       return TemplateArgumentLoc();
01966 
01967     Expr *ArgE = Arg.takeAs<Expr>();
01968     return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
01969   }
01970 
01971   TemplateTemplateParmDecl *TempTempParm
01972     = cast<TemplateTemplateParmDecl>(Param);
01973   if (!TempTempParm->hasDefaultArgument())
01974     return TemplateArgumentLoc();
01975 
01976   TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
01977                                                     TemplateLoc, 
01978                                                     RAngleLoc,
01979                                                     TempTempParm,
01980                                                     Converted);
01981   if (TName.isNull())
01982     return TemplateArgumentLoc();
01983 
01984   return TemplateArgumentLoc(TemplateArgument(TName), 
01985                 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
01986                 TempTempParm->getDefaultArgument().getTemplateNameLoc());
01987 }
01988 
01989 /// \brief Check that the given template argument corresponds to the given
01990 /// template parameter.
01991 bool Sema::CheckTemplateArgument(NamedDecl *Param,
01992                                  const TemplateArgumentLoc &Arg,
01993                                  TemplateDecl *Template,
01994                                  SourceLocation TemplateLoc,
01995                                  SourceLocation RAngleLoc,
01996                                  TemplateArgumentListBuilder &Converted,
01997                                  CheckTemplateArgumentKind CTAK) {
01998   // Check template type parameters.
01999   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
02000     return CheckTemplateTypeArgument(TTP, Arg, Converted);
02001   
02002   // Check non-type template parameters.
02003   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {    
02004     // Do substitution on the type of the non-type template parameter
02005     // with the template arguments we've seen thus far.
02006     QualType NTTPType = NTTP->getType();
02007     if (NTTPType->isDependentType()) {
02008       // Do substitution on the type of the non-type template parameter.
02009       InstantiatingTemplate Inst(*this, TemplateLoc, Template,
02010                                  NTTP, Converted.getFlatArguments(),
02011                                  Converted.flatSize(),
02012                                  SourceRange(TemplateLoc, RAngleLoc));
02013       
02014       TemplateArgumentList TemplateArgs(Context, Converted,
02015                                         /*TakeArgs=*/false);
02016       NTTPType = SubstType(NTTPType,
02017                            MultiLevelTemplateArgumentList(TemplateArgs),
02018                            NTTP->getLocation(),
02019                            NTTP->getDeclName());
02020       // If that worked, check the non-type template parameter type
02021       // for validity.
02022       if (!NTTPType.isNull())
02023         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
02024                                                      NTTP->getLocation());
02025       if (NTTPType.isNull())
02026         return true;
02027     }
02028     
02029     switch (Arg.getArgument().getKind()) {
02030     case TemplateArgument::Null:
02031       assert(false && "Should never see a NULL template argument here");
02032       return true;
02033       
02034     case TemplateArgument::Expression: {
02035       Expr *E = Arg.getArgument().getAsExpr();
02036       TemplateArgument Result;
02037       if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
02038         return true;
02039       
02040       Converted.Append(Result);
02041       break;
02042     }
02043       
02044     case TemplateArgument::Declaration:
02045     case TemplateArgument::Integral:
02046       // We've already checked this template argument, so just copy
02047       // it to the list of converted arguments.
02048       Converted.Append(Arg.getArgument());
02049       break;
02050       
02051     case TemplateArgument::Template:
02052       // We were given a template template argument. It may not be ill-formed;
02053       // see below.
02054       if (DependentTemplateName *DTN
02055             = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
02056         // We have a template argument such as \c T::template X, which we
02057         // parsed as a template template argument. However, since we now
02058         // know that we need a non-type template argument, convert this
02059         // template name into an expression.          
02060         Expr *E = DependentScopeDeclRefExpr::Create(Context,
02061                                                     DTN->getQualifier(),
02062                                                Arg.getTemplateQualifierRange(),
02063                                                     DTN->getIdentifier(),
02064                                                     Arg.getTemplateNameLoc());
02065         
02066         TemplateArgument Result;
02067         if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
02068           return true;
02069         
02070         Converted.Append(Result);
02071         break;
02072       }
02073       
02074       // We have a template argument that actually does refer to a class
02075       // template, template alias, or template template parameter, and
02076       // therefore cannot be a non-type template argument.
02077       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
02078         << Arg.getSourceRange();
02079       
02080       Diag(Param->getLocation(), diag::note_template_param_here);
02081       return true;
02082       
02083     case TemplateArgument::Type: {
02084       // We have a non-type template parameter but the template
02085       // argument is a type.
02086       
02087       // C++ [temp.arg]p2:
02088       //   In a template-argument, an ambiguity between a type-id and
02089       //   an expression is resolved to a type-id, regardless of the
02090       //   form of the corresponding template-parameter.
02091       //
02092       // We warn specifically about this case, since it can be rather
02093       // confusing for users.
02094       QualType T = Arg.getArgument().getAsType();
02095       SourceRange SR = Arg.getSourceRange();
02096       if (T->isFunctionType())
02097         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
02098       else
02099         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
02100       Diag(Param->getLocation(), diag::note_template_param_here);
02101       return true;
02102     }
02103       
02104     case TemplateArgument::Pack:
02105       llvm_unreachable("Caller must expand template argument packs");
02106       break;
02107     }
02108     
02109     return false;
02110   } 
02111   
02112   
02113   // Check template template parameters.
02114   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
02115     
02116   // Substitute into the template parameter list of the template
02117   // template parameter, since previously-supplied template arguments
02118   // may appear within the template template parameter.
02119   {
02120     // Set up a template instantiation context.
02121     LocalInstantiationScope Scope(*this);
02122     InstantiatingTemplate Inst(*this, TemplateLoc, Template,
02123                                TempParm, Converted.getFlatArguments(),
02124                                Converted.flatSize(),
02125                                SourceRange(TemplateLoc, RAngleLoc));
02126     
02127     TemplateArgumentList TemplateArgs(Context, Converted,
02128                                       /*TakeArgs=*/false);
02129     TempParm = cast_or_null<TemplateTemplateParmDecl>(
02130                       SubstDecl(TempParm, CurContext, 
02131                                 MultiLevelTemplateArgumentList(TemplateArgs)));
02132     if (!TempParm)
02133       return true;
02134     
02135     // FIXME: TempParam is leaked.
02136   }
02137     
02138   switch (Arg.getArgument().getKind()) {
02139   case TemplateArgument::Null:
02140     assert(false && "Should never see a NULL template argument here");
02141     return true;
02142     
02143   case TemplateArgument::Template:
02144     if (CheckTemplateArgument(TempParm, Arg))
02145       return true;
02146       
02147     Converted.Append(Arg.getArgument());
02148     break;
02149     
02150   case TemplateArgument::Expression:
02151   case TemplateArgument::Type:
02152     // We have a template template parameter but the template
02153     // argument does not refer to a template.
02154     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
02155     return true;
02156       
02157   case TemplateArgument::Declaration:
02158     llvm_unreachable(
02159                        "Declaration argument with template template parameter");
02160     break;
02161   case TemplateArgument::Integral:
02162     llvm_unreachable(
02163                           "Integral argument with template template parameter");
02164     break;
02165     
02166   case TemplateArgument::Pack:
02167     llvm_unreachable("Caller must expand template argument packs");
02168     break;
02169   }
02170   
02171   return false;
02172 }
02173 
02174 /// \brief Check that the given template argument list is well-formed
02175 /// for specializing the given template.
02176 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
02177                                      SourceLocation TemplateLoc,
02178                                 const TemplateArgumentListInfo &TemplateArgs,
02179                                      bool PartialTemplateArgs,
02180                                      TemplateArgumentListBuilder &Converted) {
02181   TemplateParameterList *Params = Template->getTemplateParameters();
02182   unsigned NumParams = Params->size();
02183   unsigned NumArgs = TemplateArgs.size();
02184   bool Invalid = false;
02185 
02186   SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
02187 
02188   bool HasParameterPack =
02189     NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
02190 
02191   if ((NumArgs > NumParams && !HasParameterPack) ||
02192       (NumArgs < Params->getMinRequiredArguments() &&
02193        !PartialTemplateArgs)) {
02194     // FIXME: point at either the first arg beyond what we can handle,
02195     // or the '>', depending on whether we have too many or too few
02196     // arguments.
02197     SourceRange Range;
02198     if (NumArgs > NumParams)
02199       Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
02200     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
02201       << (NumArgs > NumParams)
02202       << (isa<ClassTemplateDecl>(Template)? 0 :
02203           isa<FunctionTemplateDecl>(Template)? 1 :
02204           isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
02205       << Template << Range;
02206     Diag(Template->getLocation(), diag::note_template_decl_here)
02207       << Params->getSourceRange();
02208     Invalid = true;
02209   }
02210 
02211   // C++ [temp.arg]p1:
02212   //   [...] The type and form of each template-argument specified in
02213   //   a template-id shall match the type and form specified for the
02214   //   corresponding parameter declared by the template in its
02215   //   template-parameter-list.
02216   unsigned ArgIdx = 0;
02217   for (TemplateParameterList::iterator Param = Params->begin(),
02218                                        ParamEnd = Params->end();
02219        Param != ParamEnd; ++Param, ++ArgIdx) {
02220     if (ArgIdx > NumArgs && PartialTemplateArgs)
02221       break;
02222 
02223     // If we have a template parameter pack, check every remaining template
02224     // argument against that template parameter pack.
02225     if ((*Param)->isTemplateParameterPack()) {
02226       Converted.BeginPack();
02227       for (; ArgIdx < NumArgs; ++ArgIdx) {
02228         if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
02229                                   TemplateLoc, RAngleLoc, Converted)) {
02230           Invalid = true;
02231           break;
02232         }
02233       }
02234       Converted.EndPack();
02235       continue;
02236     }
02237     
02238     if (ArgIdx < NumArgs) {
02239       // Check the template argument we were given.
02240       if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 
02241                                 TemplateLoc, RAngleLoc, Converted))
02242         return true;
02243       
02244       continue;
02245     }
02246     
02247     // We have a default template argument that we will use.
02248     TemplateArgumentLoc Arg;
02249     
02250     // Retrieve the default template argument from the template
02251     // parameter. For each kind of template parameter, we substitute the
02252     // template arguments provided thus far and any "outer" template arguments
02253     // (when the template parameter was part of a nested template) into 
02254     // the default argument.
02255     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
02256       if (!TTP->hasDefaultArgument()) {
02257         assert((Invalid || PartialTemplateArgs) && "Missing default argument");
02258         break;
02259       }
02260 
02261       TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 
02262                                                              Template,
02263                                                              TemplateLoc,
02264                                                              RAngleLoc,
02265                                                              TTP,
02266                                                              Converted);
02267       if (!ArgType)
02268         return true;
02269                                                              
02270       Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
02271                                 ArgType);
02272     } else if (NonTypeTemplateParmDecl *NTTP
02273                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
02274       if (!NTTP->hasDefaultArgument()) {
02275         assert((Invalid || PartialTemplateArgs) && "Missing default argument");
02276         break;
02277       }
02278 
02279       Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
02280                                                               TemplateLoc, 
02281                                                               RAngleLoc, 
02282                                                               NTTP, 
02283                                                               Converted);
02284       if (E.isInvalid())
02285         return true;
02286 
02287       Expr *Ex = E.takeAs<Expr>();
02288       Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
02289     } else {
02290       TemplateTemplateParmDecl *TempParm
02291         = cast<TemplateTemplateParmDecl>(*Param);
02292 
02293       if (!TempParm->hasDefaultArgument()) {
02294         assert((Invalid || PartialTemplateArgs) && "Missing default argument");
02295         break;
02296       }
02297 
02298       TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
02299                                                        TemplateLoc, 
02300                                                        RAngleLoc, 
02301                                                        TempParm,
02302                                                        Converted);
02303       if (Name.isNull())
02304         return true;
02305       
02306       Arg = TemplateArgumentLoc(TemplateArgument(Name), 
02307                   TempParm->getDefaultArgument().getTemplateQualifierRange(),
02308                   TempParm->getDefaultArgument().getTemplateNameLoc());
02309     }
02310     
02311     // Introduce an instantiation record that describes where we are using
02312     // the default template argument.
02313     InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
02314                                         Converted.getFlatArguments(),
02315                                         Converted.flatSize(),
02316                                         SourceRange(TemplateLoc, RAngleLoc));    
02317     
02318     // Check the default template argument.
02319     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
02320                               RAngleLoc, Converted))
02321       return true;
02322   }
02323 
02324   return Invalid;
02325 }
02326 
02327 /// \brief Check a template argument against its corresponding
02328 /// template type parameter.
02329 ///
02330 /// This routine implements the semantics of C++ [temp.arg.type]. It
02331 /// returns true if an error occurred, and false otherwise.
02332 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
02333                                  TypeSourceInfo *ArgInfo) {
02334   assert(ArgInfo && "invalid TypeSourceInfo");
02335   QualType Arg = ArgInfo->getType();
02336 
02337   // C++ [temp.arg.type]p2:
02338   //   A local type, a type with no linkage, an unnamed type or a type
02339   //   compounded from any of these types shall not be used as a
02340   //   template-argument for a template type-parameter.
02341   //
02342   // FIXME: Perform the recursive and no-linkage type checks.
02343   const TagType *Tag = 0;
02344   if (const EnumType *EnumT = Arg->getAs<EnumType>())
02345     Tag = EnumT;
02346   else if (const RecordType *RecordT = Arg->getAs<RecordType>())
02347     Tag = RecordT;
02348   if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
02349     SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
02350     return Diag(SR.getBegin(), diag::err_template_arg_local_type)
02351       << QualType(Tag, 0) << SR;
02352   } else if (Tag && !Tag->getDecl()->getDeclName() &&
02353            !Tag->getDecl()->getTypedefForAnonDecl()) {
02354     SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
02355     Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
02356     Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
02357     return true;
02358   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
02359     SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange();
02360     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
02361   }
02362 
02363   return false;
02364 }
02365 
02366 /// \brief Checks whether the given template argument is the address
02367 /// of an object or function according to C++ [temp.arg.nontype]p1.
02368 static bool 
02369 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
02370                                                NonTypeTemplateParmDecl *Param,
02371                                                QualType ParamType,
02372                                                Expr *ArgIn,
02373                                                TemplateArgument &Converted) {
02374   bool Invalid = false;
02375   Expr *Arg = ArgIn;
02376   QualType ArgType = Arg->getType();
02377 
02378   // See through any implicit casts we added to fix the type.
02379   while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
02380     Arg = Cast->getSubExpr();
02381 
02382   // C++ [temp.arg.nontype]p1:
02383   //
02384   //   A template-argument for a non-type, non-template
02385   //   template-parameter shall be one of: [...]
02386   //
02387   //     -- the address of an object or function with external
02388   //        linkage, including function templates and function
02389   //        template-ids but excluding non-static class members,
02390   //        expressed as & id-expression where the & is optional if
02391   //        the name refers to a function or array, or if the
02392   //        corresponding template-parameter is a reference; or
02393   DeclRefExpr *DRE = 0;
02394 
02395   // Ignore (and complain about) any excess parentheses.
02396   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
02397     if (!Invalid) {
02398       S.Diag(Arg->getSourceRange().getBegin(),
02399              diag::err_template_arg_extra_parens)
02400         << Arg->getSourceRange();
02401       Invalid = true;
02402     }
02403 
02404     Arg = Parens->getSubExpr();
02405   }
02406 
02407   bool AddressTaken = false;
02408   SourceLocation AddrOpLoc;
02409   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
02410     if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
02411       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
02412       AddressTaken = true;
02413       AddrOpLoc = UnOp->getOperatorLoc();
02414     }
02415   } else
02416     DRE = dyn_cast<DeclRefExpr>(Arg);
02417 
02418   if (!DRE) {
02419     S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
02420       << Arg->getSourceRange();
02421     S.Diag(Param->getLocation(), diag::note_template_param_here);
02422     return true;
02423   }
02424 
02425   // Stop checking the precise nature of the argument if it is value dependent,
02426   // it should be checked when instantiated.
02427   if (Arg->isValueDependent()) {
02428     Converted = TemplateArgument(ArgIn->Retain());
02429     return false;
02430   }
02431 
02432   if (!isa<ValueDecl>(DRE->getDecl())) {
02433     S.Diag(Arg->getSourceRange().getBegin(),
02434            diag::err_template_arg_not_object_or_func_form)
02435       << Arg->getSourceRange();
02436     S.Diag(Param->getLocation(), diag::note_template_param_here);
02437     return true;
02438   }
02439 
02440   NamedDecl *Entity = 0;
02441 
02442   // Cannot refer to non-static data members
02443   if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
02444     S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
02445       << Field << Arg->getSourceRange();
02446     S.Diag(Param->getLocation(), diag::note_template_param_here);
02447     return true;
02448   }
02449 
02450   // Cannot refer to non-static member functions
02451   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
02452     if (!Method->isStatic()) {
02453       S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
02454         << Method << Arg->getSourceRange();
02455       S.Diag(Param->getLocation(), diag::note_template_param_here);
02456       return true;
02457     }
02458 
02459   // Functions must have external linkage.
02460   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
02461     if (!isExternalLinkage(Func->getLinkage())) {
02462       S.Diag(Arg->getSourceRange().getBegin(),
02463              diag::err_template_arg_function_not_extern)
02464         << Func << Arg->getSourceRange();
02465       S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
02466         << true;
02467       return true;
02468     }
02469 
02470     // Okay: we've named a function with external linkage.
02471     Entity = Func;
02472 
02473     // If the template parameter has pointer type, the function decays.
02474     if (ParamType->isPointerType() && !AddressTaken)
02475       ArgType = S.Context.getPointerType(Func->getType());
02476     else if (AddressTaken && ParamType->isReferenceType()) {
02477       // If we originally had an address-of operator, but the
02478       // parameter has reference type, complain and (if things look
02479       // like they will work) drop the address-of operator.
02480       if (!S.Context.hasSameUnqualifiedType(Func->getType(),
02481                                             ParamType.getNonReferenceType())) {
02482         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
02483           << ParamType;
02484         S.Diag(Param->getLocation(), diag::note_template_param_here);
02485         return true;
02486       }
02487 
02488       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
02489         << ParamType
02490         << FixItHint::CreateRemoval(AddrOpLoc);
02491       S.Diag(Param->getLocation(), diag::note_template_param_here);
02492 
02493       ArgType = Func->getType();
02494     }
02495   } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
02496     if (!isExternalLinkage(Var->getLinkage())) {
02497       S.Diag(Arg->getSourceRange().getBegin(),
02498              diag::err_template_arg_object_not_extern)
02499         << Var << Arg->getSourceRange();
02500       S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
02501         << true;
02502       return true;
02503     }
02504 
02505     // A value of reference type is not an object.
02506     if (Var->getType()->isReferenceType()) {
02507       S.Diag(Arg->getSourceRange().getBegin(), 
02508              diag::err_template_arg_reference_var)
02509         << Var->getType() << Arg->getSourceRange();
02510       S.Diag(Param->getLocation(), diag::note_template_param_here);
02511       return true;
02512     }
02513 
02514     // Okay: we've named an object with external linkage
02515     Entity = Var;
02516 
02517     // If the template parameter has pointer type, we must have taken
02518     // the address of this object.
02519     if (ParamType->isReferenceType()) {
02520       if (AddressTaken) {
02521         // If we originally had an address-of operator, but the
02522         // parameter has reference type, complain and (if things look
02523         // like they will work) drop the address-of operator.
02524         if (!S.Context.hasSameUnqualifiedType(Var->getType(),
02525                                             ParamType.getNonReferenceType())) {
02526           S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
02527             << ParamType;
02528           S.Diag(Param->getLocation(), diag::note_template_param_here);
02529           return true;
02530         }
02531 
02532         S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
02533           << ParamType
02534           << FixItHint::CreateRemoval(AddrOpLoc);
02535         S.Diag(Param->getLocation(), diag::note_template_param_here);
02536 
02537         ArgType = Var->getType();
02538       }
02539     } else if (!AddressTaken && ParamType->isPointerType()) {
02540       if (Var->getType()->isArrayType()) {
02541         // Array-to-pointer decay.
02542         ArgType = S.Context.getArrayDecayedType(Var->getType());
02543       } else {
02544         // If the template parameter has pointer type but the address of
02545         // this object was not taken, complain and (possibly) recover by
02546         // taking the address of the entity.
02547         ArgType = S.Context.getPointerType(Var->getType());
02548         if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
02549           S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
02550             << ParamType;
02551           S.Diag(Param->getLocation(), diag::note_template_param_here);
02552           return true;
02553         }
02554 
02555         S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
02556           << ParamType
02557           << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
02558 
02559         S.Diag(Param->getLocation(), diag::note_template_param_here);
02560       }
02561     }
02562   } else {
02563     // We found something else, but we don't know specifically what it is.
02564     S.Diag(Arg->getSourceRange().getBegin(),
02565            diag::err_template_arg_not_object_or_func)
02566       << Arg->getSourceRange();
02567     S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
02568     return true;
02569   }
02570 
02571   if (ParamType->isPointerType() && 
02572       !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
02573       S.IsQualificationConversion(ArgType, ParamType)) {
02574     // For pointer-to-object types, qualification conversions are
02575     // permitted.
02576   } else {
02577     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
02578       if (!ParamRef->getPointeeType()->isFunctionType()) {
02579         // C++ [temp.arg.nontype]p5b3:
02580         //   For a non-type template-parameter of type reference to
02581         //   object, no conversions apply. The type referred to by the
02582         //   reference may be more cv-qualified than the (otherwise
02583         //   identical) type of the template- argument. The
02584         //   template-parameter is bound directly to the
02585         //   template-argument, which shall be an lvalue.
02586 
02587         // FIXME: Other qualifiers?
02588         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
02589         unsigned ArgQuals = ArgType.getCVRQualifiers();
02590 
02591         if ((ParamQuals | ArgQuals) != ParamQuals) {
02592           S.Diag(Arg->getSourceRange().getBegin(),
02593                  diag::err_template_arg_ref_bind_ignores_quals)
02594             << ParamType << Arg->getType()
02595             << Arg->getSourceRange();
02596           S.Diag(Param->getLocation(), diag::note_template_param_here);
02597           return true;
02598         }     
02599       }
02600     }
02601 
02602     // At this point, the template argument refers to an object or
02603     // function with external linkage. We now need to check whether the
02604     // argument and parameter types are compatible.
02605     if (!S.Context.hasSameUnqualifiedType(ArgType,
02606                                           ParamType.getNonReferenceType())) {
02607       // We can't perform this conversion or binding.
02608       if (ParamType->isReferenceType())
02609         S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
02610           << ParamType << Arg->getType() << Arg->getSourceRange();
02611       else
02612         S.Diag(Arg->getLocStart(),  diag::err_template_arg_not_convertible)
02613           << Arg->getType() << ParamType << Arg->getSourceRange();
02614       S.Diag(Param->getLocation(), diag::note_template_param_here);
02615       return true;
02616     }
02617   }
02618 
02619   // Create the template argument.
02620   Converted = TemplateArgument(Entity->getCanonicalDecl());
02621   S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
02622   return false;
02623 }
02624 
02625 /// \brief Checks whether the given template argument is a pointer to
02626 /// member constant according to C++ [temp.arg.nontype]p1.
02627 bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 
02628                                                 TemplateArgument &Converted) {
02629   bool Invalid = false;
02630 
02631   // See through any implicit casts we added to fix the type.
02632   while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
02633     Arg = Cast->getSubExpr();
02634 
02635   // C++ [temp.arg.nontype]p1:
02636   //
02637   //   A template-argument for a non-type, non-template
02638   //   template-parameter shall be one of: [...]
02639   //
02640   //     -- a pointer to member expressed as described in 5.3.1.
02641   DeclRefExpr *DRE = 0;
02642 
02643   // Ignore (and complain about) any excess parentheses.
02644   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
02645     if (!Invalid) {
02646       Diag(Arg->getSourceRange().getBegin(),
02647            diag::err_template_arg_extra_parens)
02648         << Arg->getSourceRange();
02649       Invalid = true;
02650     }
02651 
02652     Arg = Parens->getSubExpr();
02653   }
02654 
02655   // A pointer-to-member constant written &Class::member.
02656   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
02657     if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
02658       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
02659       if (DRE && !DRE->getQualifier())
02660         DRE = 0;
02661     }
02662   } 
02663   // A constant of pointer-to-member type.
02664   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
02665     if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
02666       if (VD->getType()->isMemberPointerType()) {
02667         if (isa<NonTypeTemplateParmDecl>(VD) ||
02668             (isa<VarDecl>(VD) && 
02669              Context.getCanonicalType(VD->getType()).isConstQualified())) {
02670           if (Arg->isTypeDependent() || Arg->isValueDependent())
02671             Converted = TemplateArgument(Arg->Retain());
02672           else
02673             Converted = TemplateArgument(VD->getCanonicalDecl());
02674           return Invalid;
02675         }
02676       }
02677     }
02678     
02679     DRE = 0;
02680   }
02681   
02682   if (!DRE)
02683     return Diag(Arg->getSourceRange().getBegin(),
02684                 diag::err_template_arg_not_pointer_to_member_form)
02685       << Arg->getSourceRange();
02686 
02687   if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
02688     assert((isa<FieldDecl>(DRE->getDecl()) ||
02689             !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
02690            "Only non-static member pointers can make it here");
02691 
02692     // Okay: this is the address of a non-static member, and therefore
02693     // a member pointer constant.
02694     if (Arg->isTypeDependent() || Arg->isValueDependent())
02695       Converted = TemplateArgument(Arg->Retain());
02696     else
02697       Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
02698     return Invalid;
02699   }
02700 
02701   // We found something else, but we don't know specifically what it is.
02702   Diag(Arg->getSourceRange().getBegin(),
02703        diag::err_template_arg_not_pointer_to_member_form)
02704       << Arg->getSourceRange();
02705   Diag(DRE->getDecl()->getLocation(),
02706        diag::note_template_arg_refers_here);
02707   return true;
02708 }
02709 
02710 /// \brief Check a template argument against its corresponding
02711 /// non-type template parameter.
02712 ///
02713 /// This routine implements the semantics of C++ [temp.arg.nontype].
02714 /// It returns true if an error occurred, and false otherwise. \p
02715 /// InstantiatedParamType is the type of the non-type template
02716 /// parameter after it has been instantiated.
02717 ///
02718 /// If no error was detected, Converted receives the converted template argument.
02719 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
02720                                  QualType InstantiatedParamType, Expr *&Arg,
02721                                  TemplateArgument &Converted,
02722                                  CheckTemplateArgumentKind CTAK) {
02723   SourceLocation StartLoc = Arg->getSourceRange().getBegin();
02724 
02725   // If either the parameter has a dependent type or the argument is
02726   // type-dependent, there's nothing we can check now.
02727   if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
02728     // FIXME: Produce a cloned, canonical expression?
02729     Converted = TemplateArgument(Arg);
02730     return false;
02731   }
02732 
02733   // C++ [temp.arg.nontype]p5:
02734   //   The following conversions are performed on each expression used
02735   //   as a non-type template-argument. If a non-type
02736   //   template-argument cannot be converted to the type of the
02737   //   corresponding template-parameter then the program is
02738   //   ill-formed.
02739   //
02740   //     -- for a non-type template-parameter of integral or
02741   //        enumeration type, integral promotions (4.5) and integral
02742   //        conversions (4.7) are applied.
02743   QualType ParamType = InstantiatedParamType;
02744   QualType ArgType = Arg->getType();
02745   if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
02746     // C++ [temp.arg.nontype]p1:
02747     //   A template-argument for a non-type, non-template
02748     //   template-parameter shall be one of:
02749     //
02750     //     -- an integral constant-expression of integral or enumeration
02751     //        type; or
02752     //     -- the name of a non-type template-parameter; or
02753     SourceLocation NonConstantLoc;
02754     llvm::APSInt Value;
02755     if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
02756       Diag(Arg->getSourceRange().getBegin(),
02757            diag::err_template_arg_not_integral_or_enumeral)
02758         << ArgType << Arg->getSourceRange();
02759       Diag(Param->getLocation(), diag::note_template_param_here);
02760       return true;
02761     } else if (!Arg->isValueDependent() &&
02762                !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
02763       Diag(NonConstantLoc, diag::err_template_arg_not_ice)
02764         << ArgType << Arg->getSourceRange();
02765       return true;
02766     }
02767 
02768     // From here on out, all we care about are the unqualified forms
02769     // of the parameter and argument types.
02770     ParamType = ParamType.getUnqualifiedType();
02771     ArgType = ArgType.getUnqualifiedType();
02772 
02773     // Try to convert the argument to the parameter's type.
02774     if (Context.hasSameType(ParamType, ArgType)) {
02775       // Okay: no conversion necessary
02776     } else if (CTAK == CTAK_Deduced) {
02777       // C++ [temp.deduct.type]p17:
02778       //   If, in the declaration of a function template with a non-type
02779       //   template-parameter, the non-type template- parameter is used
02780       //   in an expression in the function parameter-list and, if the
02781       //   corresponding template-argument is deduced, the
02782       //   template-argument type shall match the type of the
02783       //   template-parameter exactly, except that a template-argument
02784       //   deduced from an array bound may be of any integral type.
02785       Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
02786         << ArgType << ParamType;
02787       Diag(Param->getLocation(), diag::note_template_param_here);
02788       return true;      
02789     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
02790                !ParamType->isEnumeralType()) {
02791       // This is an integral promotion or conversion.
02792       ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
02793     } else {
02794       // We can't perform this conversion.
02795       Diag(Arg->getSourceRange().getBegin(),
02796            diag::err_template_arg_not_convertible)
02797         << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
02798       Diag(Param->getLocation(), diag::note_template_param_here);
02799       return true;
02800     }
02801 
02802     QualType IntegerType = Context.getCanonicalType(ParamType);
02803     if (const EnumType *Enum = IntegerType->getAs<EnumType>())
02804       IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
02805 
02806     if (!Arg->isValueDependent()) {
02807       llvm::APSInt OldValue = Value;
02808       
02809       // Coerce the template argument's value to the value it will have 
02810       // based on the template parameter's type.
02811       unsigned AllowedBits = Context.getTypeSize(IntegerType);
02812       if (Value.getBitWidth() != AllowedBits)
02813         Value.extOrTrunc(AllowedBits);
02814       Value.setIsSigned(IntegerType->isSignedIntegerType());
02815 
02816       // Complain if an unsigned parameter received a negative value.
02817       if (IntegerType->isUnsignedIntegerType()
02818           && (OldValue.isSigned() && OldValue.isNegative())) {
02819         Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
02820           << OldValue.toString(10) << Value.toString(10) << Param->getType()
02821           << Arg->getSourceRange();
02822         Diag(Param->getLocation(), diag::note_template_param_here);
02823       }
02824 
02825       // Complain if we overflowed the template parameter's type.
02826       unsigned RequiredBits;
02827       if (IntegerType->isUnsignedIntegerType())
02828         RequiredBits = OldValue.getActiveBits();
02829       else if (OldValue.isUnsigned())
02830         RequiredBits = OldValue.getActiveBits() + 1;
02831       else
02832         RequiredBits = OldValue.getMinSignedBits();
02833       if (RequiredBits > AllowedBits) {
02834         Diag(Arg->getSourceRange().getBegin(),
02835              diag::warn_template_arg_too_large)
02836           << OldValue.toString(10) << Value.toString(10) << Param->getType()
02837           << Arg->getSourceRange();
02838         Diag(Param->getLocation(), diag::note_template_param_here);
02839       }
02840     }
02841 
02842     // Add the value of this argument to the list of converted
02843     // arguments. We use the bitwidth and signedness of the template
02844     // parameter.
02845     if (Arg->isValueDependent()) {
02846       // The argument is value-dependent. Create a new
02847       // TemplateArgument with the converted expression.
02848       Converted = TemplateArgument(Arg);
02849       return false;
02850     }
02851 
02852     Converted = TemplateArgument(Value,
02853                                  ParamType->isEnumeralType() ? ParamType
02854                                                              : IntegerType);
02855     return false;
02856   }
02857 
02858   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
02859 
02860   // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
02861   // from a template argument of type std::nullptr_t to a non-type
02862   // template parameter of type pointer to object, pointer to
02863   // function, or pointer-to-member, respectively.
02864   if (ArgType->isNullPtrType() && 
02865       (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
02866     Converted = TemplateArgument((NamedDecl *)0);
02867     return false;
02868   }
02869 
02870   // Handle pointer-to-function, reference-to-function, and
02871   // pointer-to-member-function all in (roughly) the same way.
02872   if (// -- For a non-type template-parameter of type pointer to
02873       //    function, only the function-to-pointer conversion (4.3) is
02874       //    applied. If the template-argument represents a set of
02875       //    overloaded functions (or a pointer to such), the matching
02876       //    function is selected from the set (13.4).
02877       (ParamType->isPointerType() &&
02878        ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
02879       // -- For a non-type template-parameter of type reference to
02880       //    function, no conversions apply. If the template-argument
02881       //    represents a set of overloaded functions, the matching
02882       //    function is selected from the set (13.4).
02883       (ParamType->isReferenceType() &&
02884        ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
02885       // -- For a non-type template-parameter of type pointer to
02886       //    member function, no conversions apply. If the
02887       //    template-argument represents a set of overloaded member
02888       //    functions, the matching member function is selected from
02889       //    the set (13.4).
02890       (ParamType->isMemberPointerType() &&
02891        ParamType->getAs<MemberPointerType>()->getPointeeType()
02892          ->isFunctionType())) {
02893 
02894     if (Arg->getType() == Context.OverloadTy) {
02895       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 
02896                                                                 true,
02897                                                                 FoundResult)) {
02898         if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
02899           return true;
02900 
02901         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
02902         ArgType = Arg->getType();
02903       } else
02904         return true;
02905     }
02906         
02907     if (!ParamType->isMemberPointerType())
02908       return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
02909                                                             ParamType, 
02910                                                             Arg, Converted);
02911 
02912     if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
02913       ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
02914                         Arg->isLvalue(Context) == Expr::LV_Valid);
02915     } else if (!Context.hasSameUnqualifiedType(ArgType,
02916                                            ParamType.getNonReferenceType())) {
02917       // We can't perform this conversion.
02918       Diag(Arg->getSourceRange().getBegin(),
02919            diag::err_template_arg_not_convertible)
02920         << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
02921       Diag(Param->getLocation(), diag::note_template_param_here);
02922       return true;
02923     }
02924 
02925     return CheckTemplateArgumentPointerToMember(Arg, Converted);
02926   }
02927 
02928   if (ParamType->isPointerType()) {
02929     //   -- for a non-type template-parameter of type pointer to
02930     //      object, qualification conversions (4.4) and the
02931     //      array-to-pointer conversion (4.2) are applied.
02932     // C++0x also allows a value of std::nullptr_t.
02933     assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
02934            "Only object pointers allowed here");
02935 
02936     return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 
02937                                                           ParamType,
02938                                                           Arg, Converted);
02939   }
02940 
02941   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
02942     //   -- For a non-type template-parameter of type reference to
02943     //      object, no conversions apply. The type referred to by the
02944     //      reference may be more cv-qualified than the (otherwise
02945     //      identical) type of the template-argument. The
02946     //      template-parameter is bound directly to the
02947     //      template-argument, which must be an lvalue.
02948     assert(ParamRefType->getPointeeType()->isObjectType() &&
02949            "Only object references allowed here");
02950 
02951     if (Arg->getType() == Context.OverloadTy) {
02952       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 
02953                                                  ParamRefType->getPointeeType(), 
02954                                                                 true,
02955                                                                 FoundResult)) {
02956         if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
02957           return true;
02958 
02959         Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
02960         ArgType = Arg->getType();
02961       } else
02962         return true;
02963     }
02964     
02965     return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 
02966                                                           ParamType,
02967                                                           Arg, Converted);
02968   }
02969 
02970   //     -- For a non-type template-parameter of type pointer to data
02971   //        member, qualification conversions (4.4) are applied.
02972   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
02973 
02974   if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
02975     // Types match exactly: nothing more to do here.
02976   } else if (IsQualificationConversion(ArgType, ParamType)) {
02977     ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
02978                       Arg->isLvalue(Context) == Expr::LV_Valid);
02979   } else {
02980     // We can't perform this conversion.
02981     Diag(Arg->getSourceRange().getBegin(),
02982          diag::err_template_arg_not_convertible)
02983       << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
02984     Diag(Param->getLocation(), diag::note_template_param_here);
02985     return true;
02986   }
02987 
02988   return CheckTemplateArgumentPointerToMember(Arg, Converted);
02989 }
02990 
02991 /// \brief Check a template argument against its corresponding
02992 /// template template parameter.
02993 ///
02994 /// This routine implements the semantics of C++ [temp.arg.template].
02995 /// It returns true if an error occurred, and false otherwise.
02996 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
02997                                  const TemplateArgumentLoc &Arg) {
02998   TemplateName Name = Arg.getArgument().getAsTemplate();
02999   TemplateDecl *Template = Name.getAsTemplateDecl();
03000   if (!Template) {
03001     // Any dependent template name is fine.
03002     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
03003     return false;
03004   }
03005 
03006   // C++ [temp.arg.template]p1:
03007   //   A template-argument for a template template-parameter shall be
03008   //   the name of a class template, expressed as id-expression. Only
03009   //   primary class templates are considered when matching the
03010   //   template template argument with the corresponding parameter;
03011   //   partial specializations are not considered even if their
03012   //   parameter lists match that of the template template parameter.
03013   //
03014   // Note that we also allow template template parameters here, which
03015   // will happen when we are dealing with, e.g., class template
03016   // partial specializations.
03017   if (!isa<ClassTemplateDecl>(Template) &&
03018       !isa<TemplateTemplateParmDecl>(Template)) {
03019     assert(isa<FunctionTemplateDecl>(Template) &&
03020            "Only function templates are possible here");
03021     Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
03022     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
03023       << Template;
03024   }
03025 
03026   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
03027                                          Param->getTemplateParameters(),
03028                                          true, 
03029                                          TPL_TemplateTemplateArgumentMatch,
03030                                          Arg.getLocation());
03031 }
03032 
03033 /// \brief Given a non-type template argument that refers to a
03034 /// declaration and the type of its corresponding non-type template
03035 /// parameter, produce an expression that properly refers to that
03036 /// declaration.
03037 Sema::OwningExprResult 
03038 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
03039                                               QualType ParamType,
03040                                               SourceLocation Loc) {
03041   assert(Arg.getKind() == TemplateArgument::Declaration &&
03042          "Only declaration template arguments permitted here");
03043   ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
03044 
03045   if (VD->getDeclContext()->isRecord() && 
03046       (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
03047     // If the value is a class member, we might have a pointer-to-member.
03048     // Determine whether the non-type template template parameter is of
03049     // pointer-to-member type. If so, we need to build an appropriate
03050     // expression for a pointer-to-member, since a "normal" DeclRefExpr
03051     // would refer to the member itself.
03052     if (ParamType->isMemberPointerType()) {
03053       QualType ClassType
03054         = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
03055       NestedNameSpecifier *Qualifier
03056         = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
03057       CXXScopeSpec SS;
03058       SS.setScopeRep(Qualifier);
03059       OwningExprResult RefExpr = BuildDeclRefExpr(VD, 
03060                                            VD->getType().getNonReferenceType(), 
03061                                                   Loc,
03062                                                   &SS);
03063       if (RefExpr.isInvalid())
03064         return ExprError();
03065       
03066       RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
03067       
03068       // We might need to perform a trailing qualification conversion, since
03069       // the element type on the parameter could be more qualified than the
03070       // element type in the expression we constructed.
03071       if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
03072                                     ParamType.getUnqualifiedType())) {
03073         Expr *RefE = RefExpr.takeAs<Expr>();
03074         ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
03075                           CastExpr::CK_NoOp);
03076         RefExpr = Owned(RefE);
03077       }
03078       
03079       assert(!RefExpr.isInvalid() &&
03080              Context.hasSameType(((Expr*) RefExpr.get())->getType(),
03081                                  ParamType.getUnqualifiedType()));
03082       return move(RefExpr);
03083     }
03084   }
03085   
03086   QualType T = VD->getType().getNonReferenceType();
03087   if (ParamType->isPointerType()) {
03088     // When the non-type template parameter is a pointer, take the
03089     // address of the declaration.
03090     OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
03091     if (RefExpr.isInvalid())
03092       return ExprError();
03093 
03094     if (T->isFunctionType() || T->isArrayType()) {
03095       // Decay functions and arrays.
03096       Expr *RefE = (Expr *)RefExpr.get();
03097       DefaultFunctionArrayConversion(RefE);
03098       if (RefE != RefExpr.get()) {
03099         RefExpr.release();
03100         RefExpr = Owned(RefE);
03101       }
03102 
03103       return move(RefExpr);
03104     }
03105     
03106     // Take the address of everything else
03107     return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
03108   }
03109 
03110   // If the non-type template parameter has reference type, qualify the
03111   // resulting declaration reference with the extra qualifiers on the
03112   // type that the reference refers to.
03113   if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
03114     T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
03115     
03116   return BuildDeclRefExpr(VD, T, Loc);
03117 }
03118 
03119 /// \brief Construct a new expression that refers to the given
03120 /// integral template argument with the given source-location
03121 /// information.
03122 ///
03123 /// This routine takes care of the mapping from an integral template
03124 /// argument (which may have any integral type) to the appropriate
03125 /// literal value.
03126 Sema::OwningExprResult 
03127 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
03128                                                   SourceLocation Loc) {
03129   assert(Arg.getKind() == TemplateArgument::Integral &&
03130          "Operation is only value for integral template arguments");
03131   QualType T = Arg.getIntegralType();
03132   if (T->isCharType() || T->isWideCharType())
03133     return Owned(new (Context) CharacterLiteral(
03134                                              Arg.getAsIntegral()->getZExtValue(),
03135                                              T->isWideCharType(),
03136                                              T,
03137                                              Loc));
03138   if (T->isBooleanType())
03139     return Owned(new (Context) CXXBoolLiteralExpr(
03140                                             Arg.getAsIntegral()->getBoolValue(),
03141                                             T,
03142                                             Loc));
03143 
03144   return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
03145 }
03146 
03147 
03148 /// \brief Determine whether the given template parameter lists are
03149 /// equivalent.
03150 ///
03151 /// \param New  The new template parameter list, typically written in the
03152 /// source code as part of a new template declaration.
03153 ///
03154 /// \param Old  The old template parameter list, typically found via
03155 /// name lookup of the template declared with this template parameter
03156 /// list.
03157 ///
03158 /// \param Complain  If true, this routine will produce a diagnostic if
03159 /// the template parameter lists are not equivalent.
03160 ///
03161 /// \param Kind describes how we are to match the template parameter lists.
03162 ///
03163 /// \param TemplateArgLoc If this source location is valid, then we
03164 /// are actually checking the template parameter list of a template
03165 /// argument (New) against the template parameter list of its
03166 /// corresponding template template parameter (Old). We produce
03167 /// slightly different diagnostics in this scenario.
03168 ///
03169 /// \returns True if the template parameter lists are equal, false
03170 /// otherwise.
03171 bool
03172 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
03173                                      TemplateParameterList *Old,
03174                                      bool Complain,
03175                                      TemplateParameterListEqualKind Kind,
03176                                      SourceLocation TemplateArgLoc) {
03177   if (Old->size() != New->size()) {
03178     if (Complain) {
03179       unsigned NextDiag = diag::err_template_param_list_different_arity;
03180       if (TemplateArgLoc.isValid()) {
03181         Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
03182         NextDiag = diag::note_template_param_list_different_arity;
03183       }
03184       Diag(New->getTemplateLoc(), NextDiag)
03185           << (New->size() > Old->size())
03186           << (Kind != TPL_TemplateMatch)
03187           << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
03188       Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
03189         << (Kind != TPL_TemplateMatch)
03190         << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
03191     }
03192 
03193     return false;
03194   }
03195 
03196   for (TemplateParameterList::iterator OldParm = Old->begin(),
03197          OldParmEnd = Old->end(), NewParm = New->begin();
03198        OldParm != OldParmEnd; ++OldParm, ++NewParm) {
03199     if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
03200       if (Complain) {
03201         unsigned NextDiag = diag::err_template_param_different_kind;
03202         if (TemplateArgLoc.isValid()) {
03203           Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
03204           NextDiag = diag::note_template_param_different_kind;
03205         }
03206         Diag((*NewParm)->getLocation(), NextDiag)
03207           << (Kind != TPL_TemplateMatch);
03208         Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
03209           << (Kind != TPL_TemplateMatch);
03210       }
03211       return false;
03212     }
03213 
03214     if (isa<TemplateTypeParmDecl>(*OldParm)) {
03215       // Okay; all template type parameters are equivalent (since we
03216       // know we're at the same index).
03217     } else if (NonTypeTemplateParmDecl *OldNTTP
03218                  = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
03219       // The types of non-type template parameters must agree.
03220       NonTypeTemplateParmDecl *NewNTTP
03221         = cast<NonTypeTemplateParmDecl>(*NewParm);
03222       
03223       // If we are matching a template template argument to a template
03224       // template parameter and one of the non-type template parameter types
03225       // is dependent, then we must wait until template instantiation time
03226       // to actually compare the arguments.
03227       if (Kind == TPL_TemplateTemplateArgumentMatch &&
03228           (OldNTTP->getType()->isDependentType() ||
03229            NewNTTP->getType()->isDependentType()))
03230         continue;
03231       
03232       if (Context.getCanonicalType(OldNTTP->getType()) !=
03233             Context.getCanonicalType(NewNTTP->getType())) {
03234         if (Complain) {
03235           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
03236           if (TemplateArgLoc.isValid()) {
03237             Diag(TemplateArgLoc,
03238                  diag::err_template_arg_template_params_mismatch);
03239             NextDiag = diag::note_template_nontype_parm_different_type;
03240           }
03241           Diag(NewNTTP->getLocation(), NextDiag)
03242             << NewNTTP->getType()
03243             << (Kind != TPL_TemplateMatch);
03244           Diag(OldNTTP->getLocation(),
03245                diag::note_template_nontype_parm_prev_declaration)
03246             << OldNTTP->getType();
03247         }
03248         return false;
03249       }
03250     } else {
03251       // The template parameter lists of template template
03252       // parameters must agree.
03253       assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
03254              "Only template template parameters handled here");
03255       TemplateTemplateParmDecl *OldTTP
03256         = cast<TemplateTemplateParmDecl>(*OldParm);
03257       TemplateTemplateParmDecl *NewTTP
03258         = cast<TemplateTemplateParmDecl>(*NewParm);
03259       if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
03260                                           OldTTP->getTemplateParameters(),
03261                                           Complain,
03262               (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
03263                                           TemplateArgLoc))
03264         return false;
03265     }
03266   }
03267 
03268   return true;
03269 }
03270 
03271 /// \brief Check whether a template can be declared within this scope.
03272 ///
03273 /// If the template declaration is valid in this scope, returns
03274 /// false. Otherwise, issues a diagnostic and returns true.
03275 bool
03276 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
03277   // Find the nearest enclosing declaration scope.
03278   while ((S->getFlags() & Scope::DeclScope) == 0 ||
03279          (S->getFlags() & Scope::TemplateParamScope) != 0)
03280     S = S->getParent();
03281 
03282   // C++ [temp]p2:
03283   //   A template-declaration can appear only as a namespace scope or
03284   //   class scope declaration.
03285   DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
03286   if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
03287       cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
03288     return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
03289              << TemplateParams->getSourceRange();
03290 
03291   while (Ctx && isa<LinkageSpecDecl>(Ctx))
03292     Ctx = Ctx->getParent();
03293 
03294   if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
03295     return false;
03296 
03297   return Diag(TemplateParams->getTemplateLoc(),
03298               diag::err_template_outside_namespace_or_class_scope)
03299     << TemplateParams->getSourceRange();
03300 }
03301 
03302 /// \brief Determine what kind of template specialization the given declaration
03303 /// is.
03304 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
03305   if (!D)
03306     return TSK_Undeclared;
03307   
03308   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
03309     return Record->getTemplateSpecializationKind();
03310   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
03311     return Function->getTemplateSpecializationKind();
03312   if (VarDecl *Var = dyn_cast<VarDecl>(D))
03313     return Var->getTemplateSpecializationKind();
03314   
03315   return TSK_Undeclared;
03316 }
03317 
03318 /// \brief Check whether a specialization is well-formed in the current 
03319 /// context.
03320 ///
03321 /// This routine determines whether a template specialization can be declared
03322 /// in the current context (C++ [temp.expl.spec]p2).
03323 ///
03324 /// \param S the semantic analysis object for which this check is being
03325 /// performed.
03326 ///
03327 /// \param Specialized the entity being specialized or instantiated, which
03328 /// may be a kind of template (class template, function template, etc.) or
03329 /// a member of a class template (member function, static data member, 
03330 /// member class).
03331 ///
03332 /// \param PrevDecl the previous declaration of this entity, if any.
03333 ///
03334 /// \param Loc the location of the explicit specialization or instantiation of
03335 /// this entity.
03336 ///
03337 /// \param IsPartialSpecialization whether this is a partial specialization of
03338 /// a class template.
03339 ///
03340 /// \returns true if there was an error that we cannot recover from, false
03341 /// otherwise.
03342 static bool CheckTemplateSpecializationScope(Sema &S,
03343                                              NamedDecl *Specialized,
03344                                              NamedDecl *PrevDecl,
03345                                              SourceLocation Loc,
03346                                              bool IsPartialSpecialization) {
03347   // Keep these "kind" numbers in sync with the %select statements in the
03348   // various diagnostics emitted by this routine.
03349   int EntityKind = 0;
03350   bool isTemplateSpecialization = false;
03351   if (isa<ClassTemplateDecl>(Specialized)) {
03352     EntityKind = IsPartialSpecialization? 1 : 0;
03353     isTemplateSpecialization = true;
03354   } else if (isa<FunctionTemplateDecl>(Specialized)) {
03355     EntityKind = 2;
03356     isTemplateSpecialization = true;
03357   } else if (isa<CXXMethodDecl>(Specialized))
03358     EntityKind = 3;
03359   else if (isa<VarDecl>(Specialized))
03360     EntityKind = 4;
03361   else if (isa<RecordDecl>(Specialized))
03362     EntityKind = 5;
03363   else {
03364     S.Diag(Loc, diag::err_template_spec_unknown_kind);
03365     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
03366     return true;
03367   }
03368 
03369   // C++ [temp.expl.spec]p2:
03370   //   An explicit specialization shall be declared in the namespace
03371   //   of which the template is a member, or, for member templates, in
03372   //   the namespace of which the enclosing class or enclosing class
03373   //   template is a member. An explicit specialization of a member
03374   //   function, member class or static data member of a class
03375   //   template shall be declared in the namespace of which the class
03376   //   template is a member. Such a declaration may also be a
03377   //   definition. If the declaration is not a definition, the
03378   //   specialization may be defined later in the name- space in which
03379   //   the explicit specialization was declared, or in a namespace
03380   //   that encloses the one in which the explicit specialization was
03381   //   declared.
03382   if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
03383     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
03384       << Specialized;
03385     return true;
03386   }
03387 
03388   if (S.CurContext->isRecord() && !IsPartialSpecialization) {
03389     S.Diag(Loc, diag::err_template_spec_decl_class_scope)
03390       << Specialized;
03391     return true;
03392   }
03393   
03394   // C++ [temp.class.spec]p6:
03395   //   A class template partial specialization may be declared or redeclared
03396   //   in any namespace scope in which its definition may be defined (14.5.1 
03397   //   and 14.5.2).  
03398   bool ComplainedAboutScope = false;
03399   DeclContext *SpecializedContext 
03400     = Specialized->getDeclContext()->getEnclosingNamespaceContext();
03401   DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
03402   if ((!PrevDecl || 
03403        getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
03404        getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
03405     // There is no prior declaration of this entity, so this
03406     // specialization must be in the same context as the template
03407     // itself.
03408     if (!DC->Equals(SpecializedContext)) {
03409       if (isa<TranslationUnitDecl>(SpecializedContext))
03410         S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
03411         << EntityKind << Specialized;
03412       else if (isa<NamespaceDecl>(SpecializedContext))
03413         S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
03414         << EntityKind << Specialized
03415         << cast<NamedDecl>(SpecializedContext);
03416       
03417       S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
03418       ComplainedAboutScope = true;
03419     }
03420   }
03421   
03422   // Make sure that this redeclaration (or definition) occurs in an enclosing 
03423   // namespace.
03424   // Note that HandleDeclarator() performs this check for explicit 
03425   // specializations of function templates, static data members, and member
03426   // functions, so we skip the check here for those kinds of entities.
03427   // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
03428   // Should we refactor that check, so that it occurs later?
03429   if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
03430       !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
03431         isa<FunctionDecl>(Specialized))) {
03432     if (isa<TranslationUnitDecl>(SpecializedContext))
03433       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
03434         << EntityKind << Specialized;
03435     else if (isa<NamespaceDecl>(SpecializedContext))
03436       S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
03437         << EntityKind << Specialized
03438         << cast<NamedDecl>(SpecializedContext);
03439   
03440     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
03441   }
03442   
03443   // FIXME: check for specialization-after-instantiation errors and such.
03444   
03445   return false;
03446 }
03447                                              
03448 /// \brief Check the non-type template arguments of a class template
03449 /// partial specialization according to C++ [temp.class.spec]p9.
03450 ///
03451 /// \param TemplateParams the template parameters of the primary class
03452 /// template.
03453 ///
03454 /// \param TemplateArg the template arguments of the class template
03455 /// partial specialization.
03456 ///
03457 /// \param MirrorsPrimaryTemplate will be set true if the class
03458 /// template partial specialization arguments are identical to the
03459 /// implicit template arguments of the primary template. This is not
03460 /// necessarily an error (C++0x), and it is left to the caller to diagnose
03461 /// this condition when it is an error.
03462 ///
03463 /// \returns true if there was an error, false otherwise.
03464 bool Sema::CheckClassTemplatePartialSpecializationArgs(
03465                                         TemplateParameterList *TemplateParams,
03466                              const TemplateArgumentListBuilder &TemplateArgs,
03467                                         bool &MirrorsPrimaryTemplate) {
03468   // FIXME: the interface to this function will have to change to
03469   // accommodate variadic templates.
03470   MirrorsPrimaryTemplate = true;
03471 
03472   const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
03473 
03474   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
03475     // Determine whether the template argument list of the partial
03476     // specialization is identical to the implicit argument list of
03477     // the primary template. The caller may need to diagnostic this as
03478     // an error per C++ [temp.class.spec]p9b3.
03479     if (MirrorsPrimaryTemplate) {
03480       if (TemplateTypeParmDecl *TTP
03481             = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
03482         if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
03483               Context.getCanonicalType(ArgList[I].getAsType()))
03484           MirrorsPrimaryTemplate = false;
03485       } else if (TemplateTemplateParmDecl *TTP
03486                    = dyn_cast<TemplateTemplateParmDecl>(
03487                                                  TemplateParams->getParam(I))) {
03488         TemplateName Name = ArgList[I].getAsTemplate();
03489         TemplateTemplateParmDecl *ArgDecl
03490           = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
03491         if (!ArgDecl ||
03492             ArgDecl->getIndex() != TTP->getIndex() ||
03493             ArgDecl->getDepth() != TTP->getDepth())
03494           MirrorsPrimaryTemplate = false;
03495       }
03496     }
03497 
03498     NonTypeTemplateParmDecl *Param
03499       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
03500     if (!Param) {
03501       continue;
03502     }
03503 
03504     Expr *ArgExpr = ArgList[I].getAsExpr();
03505     if (!ArgExpr) {
03506       MirrorsPrimaryTemplate = false;
03507       continue;
03508     }
03509 
03510     // C++ [temp.class.spec]p8:
03511     //   A non-type argument is non-specialized if it is the name of a
03512     //   non-type parameter. All other non-type arguments are
03513     //   specialized.
03514     //
03515     // Below, we check the two conditions that only apply to
03516     // specialized non-type arguments, so skip any non-specialized
03517     // arguments.
03518     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
03519       if (NonTypeTemplateParmDecl *NTTP
03520             = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
03521         if (MirrorsPrimaryTemplate &&
03522             (Param->getIndex() != NTTP->getIndex() ||
03523              Param->getDepth() != NTTP->getDepth()))
03524           MirrorsPrimaryTemplate = false;
03525 
03526         continue;
03527       }
03528 
03529     // C++ [temp.class.spec]p9:
03530     //   Within the argument list of a class template partial
03531     //   specialization, the following restrictions apply:
03532     //     -- A partially specialized non-type argument expression
03533     //        shall not involve a template parameter of the partial
03534     //        specialization except when the argument expression is a
03535     //        simple identifier.
03536     if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
03537       Diag(ArgExpr->getLocStart(),
03538            diag::err_dependent_non_type_arg_in_partial_spec)
03539         << ArgExpr->getSourceRange();
03540       return true;
03541     }
03542 
03543     //     -- The type of a template parameter corresponding to a
03544     //        specialized non-type argument shall not be dependent on a
03545     //        parameter of the specialization.
03546     if (Param->getType()->isDependentType()) {
03547       Diag(ArgExpr->getLocStart(),
03548            diag::err_dependent_typed_non_type_arg_in_partial_spec)
03549         << Param->getType()
03550         << ArgExpr->getSourceRange();
03551       Diag(Param->getLocation(), diag::note_template_param_here);
03552       return true;
03553     }
03554 
03555     MirrorsPrimaryTemplate = false;
03556   }
03557 
03558   return false;
03559 }
03560 
03561 /// \brief Retrieve the previous declaration of the given declaration.
03562 static NamedDecl *getPreviousDecl(NamedDecl *ND) {
03563   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
03564     return VD->getPreviousDeclaration();
03565   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
03566     return FD->getPreviousDeclaration();
03567   if (TagDecl *TD = dyn_cast<TagDecl>(ND))
03568     return TD->getPreviousDeclaration();
03569   if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
03570     return TD->getPreviousDeclaration();
03571   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
03572     return FTD->getPreviousDeclaration();
03573   if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
03574     return CTD->getPreviousDeclaration();
03575   return 0;
03576 }
03577 
03578 Sema::DeclResult
03579 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
03580                                        TagUseKind TUK,
03581                                        SourceLocation KWLoc,
03582                                        CXXScopeSpec &SS,
03583                                        TemplateTy TemplateD,
03584                                        SourceLocation TemplateNameLoc,
03585                                        SourceLocation LAngleLoc,
03586                                        ASTTemplateArgsPtr TemplateArgsIn,
03587                                        SourceLocation RAngleLoc,
03588                                        AttributeList *Attr,
03589                                MultiTemplateParamsArg TemplateParameterLists) {
03590   assert(TUK != TUK_Reference && "References are not specializations");
03591 
03592   // Find the class template we're specializing
03593   TemplateName Name = TemplateD.getAsVal<TemplateName>();
03594   ClassTemplateDecl *ClassTemplate
03595     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
03596 
03597   if (!ClassTemplate) {
03598     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
03599       << (Name.getAsTemplateDecl() && 
03600           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
03601     return true;
03602   }
03603 
03604   bool isExplicitSpecialization = false;
03605   bool isPartialSpecialization = false;
03606 
03607   // Check the validity of the template headers that introduce this
03608   // template.
03609   // FIXME: We probably shouldn't complain about these headers for
03610   // friend declarations.
03611   TemplateParameterList *TemplateParams
03612     = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
03613                         (TemplateParameterList**)TemplateParameterLists.get(),
03614                                               TemplateParameterLists.size(),
03615                                               TUK == TUK_Friend,
03616                                               isExplicitSpecialization);
03617   if (TemplateParams && TemplateParams->size() > 0) {
03618     isPartialSpecialization = true;
03619 
03620     // C++ [temp.class.spec]p10:
03621     //   The template parameter list of a specialization shall not
03622     //   contain default template argument values.
03623     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
03624       Decl *Param = TemplateParams->getParam(I);
03625       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
03626         if (TTP->hasDefaultArgument()) {
03627           Diag(TTP->getDefaultArgumentLoc(),
03628                diag::err_default_arg_in_partial_spec);
03629           TTP->removeDefaultArgument();
03630         }
03631       } else if (NonTypeTemplateParmDecl *NTTP
03632                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
03633         if (Expr *DefArg = NTTP->getDefaultArgument()) {
03634           Diag(NTTP->getDefaultArgumentLoc(),
03635                diag::err_default_arg_in_partial_spec)
03636             << DefArg->getSourceRange();
03637           NTTP->setDefaultArgument(0);
03638           DefArg->Destroy(Context);
03639         }
03640       } else {
03641         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
03642         if (TTP->hasDefaultArgument()) {
03643           Diag(TTP->getDefaultArgument().getLocation(),
03644                diag::err_default_arg_in_partial_spec)
03645             << TTP->getDefaultArgument().getSourceRange();
03646           TTP->setDefaultArgument(TemplateArgumentLoc());
03647         }
03648       }
03649     }
03650   } else if (TemplateParams) {
03651     if (TUK == TUK_Friend)
03652       Diag(KWLoc, diag::err_template_spec_friend)
03653         << FixItHint::CreateRemoval(
03654                                 SourceRange(TemplateParams->getTemplateLoc(),
03655                                             TemplateParams->getRAngleLoc()))
03656         << SourceRange(LAngleLoc, RAngleLoc);
03657     else
03658       isExplicitSpecialization = true;
03659   } else if (TUK != TUK_Friend) {
03660     Diag(KWLoc, diag::err_template_spec_needs_header)
03661       << FixItHint::CreateInsertion(KWLoc, "template<> ");
03662     isExplicitSpecialization = true;
03663   }
03664 
03665   // Check that the specialization uses the same tag kind as the
03666   // original template.
03667   TagDecl::TagKind Kind;
03668   switch (TagSpec) {
03669   default: assert(0 && "Unknown tag type!");
03670   case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
03671   case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
03672   case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
03673   }
03674   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
03675                                     Kind, KWLoc,
03676                                     *ClassTemplate->getIdentifier())) {
03677     Diag(KWLoc, diag::err_use_with_wrong_tag)
03678       << ClassTemplate
03679       << FixItHint::CreateReplacement(KWLoc,
03680                             ClassTemplate->getTemplatedDecl()->getKindName());
03681     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
03682          diag::note_previous_use);
03683     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
03684   }
03685 
03686   // Translate the parser's template argument list in our AST format.
03687   TemplateArgumentListInfo TemplateArgs;
03688   TemplateArgs.setLAngleLoc(LAngleLoc);
03689   TemplateArgs.setRAngleLoc(RAngleLoc);
03690   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
03691 
03692   // Check that the template argument list is well-formed for this
03693   // template.
03694   TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
03695                                         TemplateArgs.size());
03696   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
03697                                 TemplateArgs, false, Converted))
03698     return true;
03699 
03700   assert((Converted.structuredSize() ==
03701             ClassTemplate->getTemplateParameters()->size()) &&
03702          "Converted template argument list is too short!");
03703 
03704   // Find the class template (partial) specialization declaration that
03705   // corresponds to these arguments.
03706   llvm::FoldingSetNodeID ID;
03707   if (isPartialSpecialization) {
03708     bool MirrorsPrimaryTemplate;
03709     if (CheckClassTemplatePartialSpecializationArgs(
03710                                          ClassTemplate->getTemplateParameters(),
03711                                          Converted, MirrorsPrimaryTemplate))
03712       return true;
03713 
03714     if (MirrorsPrimaryTemplate) {
03715       // C++ [temp.class.spec]p9b3:
03716       //
03717       //   -- The argument list of the specialization shall not be identical
03718       //      to the implicit argument list of the primary template.
03719       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
03720         << (TUK == TUK_Definition)
03721         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
03722       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
03723                                 ClassTemplate->getIdentifier(),
03724                                 TemplateNameLoc,
03725                                 Attr,
03726                                 TemplateParams,
03727                                 AS_none);
03728     }
03729 
03730     // FIXME: Diagnose friend partial specializations
03731 
03732     if (!Name.isDependent() && 
03733         !TemplateSpecializationType::anyDependentTemplateArguments(
03734                                              TemplateArgs.getArgumentArray(), 
03735                                                          TemplateArgs.size())) {
03736       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
03737         << ClassTemplate->getDeclName();
03738       isPartialSpecialization = false;
03739     } else {
03740       // FIXME: Template parameter list matters, too
03741       ClassTemplatePartialSpecializationDecl::Profile(ID,
03742                                                   Converted.getFlatArguments(),
03743                                                       Converted.flatSize(),
03744                                                       Context);
03745     }
03746   }
03747   
03748   if (!isPartialSpecialization)
03749     ClassTemplateSpecializationDecl::Profile(ID,
03750                                              Converted.getFlatArguments(),
03751                                              Converted.flatSize(),
03752                                              Context);
03753   void *InsertPos = 0;
03754   ClassTemplateSpecializationDecl *PrevDecl = 0;
03755 
03756   if (isPartialSpecialization)
03757     PrevDecl
03758       = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
03759                                                                     InsertPos);
03760   else
03761     PrevDecl
03762       = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
03763 
03764   ClassTemplateSpecializationDecl *Specialization = 0;
03765 
03766   // Check whether we can declare a class template specialization in
03767   // the current scope.
03768   if (TUK != TUK_Friend &&
03769       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 
03770                                        TemplateNameLoc, 
03771                                        isPartialSpecialization))
03772     return true;
03773   
03774   // The canonical type
03775   QualType CanonType;
03776   if (PrevDecl && 
03777       (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
03778                TUK == TUK_Friend)) {
03779     // Since the only prior class template specialization with these
03780     // arguments was referenced but not declared, or we're only
03781     // referencing this specialization as a friend, reuse that
03782     // declaration node as our own, updating its source location to
03783     // reflect our new declaration.
03784     Specialization = PrevDecl;
03785     Specialization->setLocation(TemplateNameLoc);
03786     PrevDecl = 0;
03787     CanonType = Context.getTypeDeclType(Specialization);
03788   } else if (isPartialSpecialization) {
03789     // Build the canonical type that describes the converted template
03790     // arguments of the class template partial specialization.
03791     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
03792     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
03793                                                   Converted.getFlatArguments(),
03794                                                   Converted.flatSize());
03795 
03796     // Create a new class template partial specialization declaration node.
03797     ClassTemplatePartialSpecializationDecl *PrevPartial
03798       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
03799     unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
03800                             : ClassTemplate->getPartialSpecializations().size();
03801     ClassTemplatePartialSpecializationDecl *Partial
03802       = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
03803                                              ClassTemplate->getDeclContext(),
03804                                                        TemplateNameLoc,
03805                                                        TemplateParams,
03806                                                        ClassTemplate,
03807                                                        Converted,
03808                                                        TemplateArgs,
03809                                                        CanonType,
03810                                                        PrevPartial,
03811                                                        SequenceNumber);
03812     SetNestedNameSpecifier(Partial, SS);
03813 
03814     if (PrevPartial) {
03815       ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
03816       ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
03817     } else {
03818       ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
03819     }
03820     Specialization = Partial;
03821 
03822     // If we are providing an explicit specialization of a member class 
03823     // template specialization, make a note of that.
03824     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
03825       PrevPartial->setMemberSpecialization();
03826     
03827     // Check that all of the template parameters of the class template
03828     // partial specialization are deducible from the template
03829     // arguments. If not, this class template partial specialization
03830     // will never be used.
03831     llvm::SmallVector<bool, 8> DeducibleParams;
03832     DeducibleParams.resize(TemplateParams->size());
03833     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 
03834                                TemplateParams->getDepth(),
03835                                DeducibleParams);
03836     unsigned NumNonDeducible = 0;
03837     for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
03838       if (!DeducibleParams[I])
03839         ++NumNonDeducible;
03840 
03841     if (NumNonDeducible) {
03842       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
03843         << (NumNonDeducible > 1)
03844         << SourceRange(TemplateNameLoc, RAngleLoc);
03845       for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
03846         if (!DeducibleParams[I]) {
03847           NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
03848           if (Param->getDeclName())
03849             Diag(Param->getLocation(),
03850                  diag::note_partial_spec_unused_parameter)
03851               << Param->getDeclName();
03852           else
03853             Diag(Param->getLocation(),
03854                  diag::note_partial_spec_unused_parameter)
03855               << std::string("<anonymous>");
03856         }
03857       }
03858     }
03859   } else {
03860     // Create a new class template specialization declaration node for
03861     // this explicit specialization or friend declaration.
03862     Specialization
03863       = ClassTemplateSpecializationDecl::Create(Context, Kind,
03864                                              ClassTemplate->getDeclContext(),
03865                                                 TemplateNameLoc,
03866                                                 ClassTemplate,
03867                                                 Converted,
03868                                                 PrevDecl);
03869     SetNestedNameSpecifier(Specialization, SS);
03870 
03871     if (PrevDecl) {
03872       ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
03873       ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
03874     } else {
03875       ClassTemplate->getSpecializations().InsertNode(Specialization,
03876                                                      InsertPos);
03877     }
03878 
03879     CanonType = Context.getTypeDeclType(Specialization);
03880   }
03881 
03882   // C++ [temp.expl.spec]p6:
03883   //   If a template, a member template or the member of a class template is
03884   //   explicitly specialized then that specialization shall be declared 
03885   //   before the first use of that specialization that would cause an implicit
03886   //   instantiation to take place, in every translation unit in which such a 
03887   //   use occurs; no diagnostic is required.
03888   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
03889     bool Okay = false;
03890     for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
03891       // Is there any previous explicit specialization declaration?
03892       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
03893         Okay = true;
03894         break;
03895       }
03896     }
03897 
03898     if (!Okay) {
03899       SourceRange Range(TemplateNameLoc, RAngleLoc);
03900       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
03901         << Context.getTypeDeclType(Specialization) << Range;
03902 
03903       Diag(PrevDecl->getPointOfInstantiation(), 
03904            diag::note_instantiation_required_here)
03905         << (PrevDecl->getTemplateSpecializationKind() 
03906                                                 != TSK_ImplicitInstantiation);
03907       return true;
03908     }
03909   }
03910   
03911   // If this is not a friend, note that this is an explicit specialization.
03912   if (TUK != TUK_Friend)
03913     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
03914 
03915   // Check that this isn't a redefinition of this specialization.
03916   if (TUK == TUK_Definition) {
03917     if (RecordDecl *Def = Specialization->getDefinition()) {
03918       SourceRange Range(TemplateNameLoc, RAngleLoc);
03919       Diag(TemplateNameLoc, diag::err_redefinition)
03920         << Context.getTypeDeclType(Specialization) << Range;
03921       Diag(Def->getLocation(), diag::note_previous_definition);
03922       Specialization->setInvalidDecl();
03923       return true;
03924     }
03925   }
03926 
03927   // Build the fully-sugared type for this class template
03928   // specialization as the user wrote in the specialization
03929   // itself. This means that we'll pretty-print the type retrieved
03930   // from the specialization's declaration the way that the user
03931   // actually wrote the specialization, rather than formatting the
03932   // name based on the "canonical" representation used to store the
03933   // template arguments in the specialization.
03934   TypeSourceInfo *WrittenTy
03935     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
03936                                                 TemplateArgs, CanonType);
03937   if (TUK != TUK_Friend)
03938     Specialization->setTypeAsWritten(WrittenTy);
03939   TemplateArgsIn.release();
03940 
03941   // C++ [temp.expl.spec]p9:
03942   //   A template explicit specialization is in the scope of the
03943   //   namespace in which the template was defined.
03944   //
03945   // We actually implement this paragraph where we set the semantic
03946   // context (in the creation of the ClassTemplateSpecializationDecl),
03947   // but we also maintain the lexical context where the actual
03948   // definition occurs.
03949   Specialization->setLexicalDeclContext(CurContext);
03950 
03951   // We may be starting the definition of this specialization.
03952   if (TUK == TUK_Definition)
03953     Specialization->startDefinition();
03954 
03955   if (TUK == TUK_Friend) {
03956     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
03957                                             TemplateNameLoc,
03958                                             WrittenTy,
03959                                             /*FIXME:*/KWLoc);
03960     Friend->setAccess(AS_public);
03961     CurContext->addDecl(Friend);
03962   } else {
03963     // Add the specialization into its lexical context, so that it can
03964     // be seen when iterating through the list of declarations in that
03965     // context. However, specializations are not found by name lookup.
03966     CurContext->addDecl(Specialization);
03967   }
03968   return DeclPtrTy::make(Specialization);
03969 }
03970 
03971 Sema::DeclPtrTy
03972 Sema::ActOnTemplateDeclarator(Scope *S,
03973                               MultiTemplateParamsArg TemplateParameterLists,
03974                               Declarator &D) {
03975   return HandleDeclarator(S, D, move(TemplateParameterLists), false);
03976 }
03977 
03978 Sema::DeclPtrTy
03979 Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
03980                                MultiTemplateParamsArg TemplateParameterLists,
03981                                       Declarator &D) {
03982   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
03983   assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
03984          "Not a function declarator!");
03985   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
03986 
03987   if (FTI.hasPrototype) {
03988     // FIXME: Diagnose arguments without names in C.
03989   }
03990 
03991   Scope *ParentScope = FnBodyScope->getParent();
03992 
03993   DeclPtrTy DP = HandleDeclarator(ParentScope, D,
03994                                   move(TemplateParameterLists),
03995                                   /*IsFunctionDefinition=*/true);
03996   if (FunctionTemplateDecl *FunctionTemplate
03997         = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
03998     return ActOnStartOfFunctionDef(FnBodyScope,
03999                       DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
04000   if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
04001     return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
04002   return DeclPtrTy();
04003 }
04004 
04005 /// \brief Strips various properties off an implicit instantiation
04006 /// that has just been explicitly specialized.
04007 static void StripImplicitInstantiation(NamedDecl *D) {
04008   D->invalidateAttrs();
04009 
04010   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
04011     FD->setInlineSpecified(false);
04012   }
04013 }
04014 
04015 /// \brief Diagnose cases where we have an explicit template specialization 
04016 /// before/after an explicit template instantiation, producing diagnostics
04017 /// for those cases where they are required and determining whether the 
04018 /// new specialization/instantiation will have any effect.
04019 ///
04020 /// \param NewLoc the location of the new explicit specialization or 
04021 /// instantiation.
04022 ///
04023 /// \param NewTSK the kind of the new explicit specialization or instantiation.
04024 ///
04025 /// \param PrevDecl the previous declaration of the entity.
04026 ///
04027 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
04028 ///
04029 /// \param PrevPointOfInstantiation if valid, indicates where the previus 
04030 /// declaration was instantiated (either implicitly or explicitly).
04031 ///
04032 /// \param SuppressNew will be set to true to indicate that the new 
04033 /// specialization or instantiation has no effect and should be ignored.
04034 ///
04035 /// \returns true if there was an error that should prevent the introduction of
04036 /// the new declaration into the AST, false otherwise.
04037 bool
04038 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
04039                                              TemplateSpecializationKind NewTSK,
04040                                              NamedDecl *PrevDecl,
04041                                              TemplateSpecializationKind PrevTSK,
04042                                         SourceLocation PrevPointOfInstantiation,
04043                                              bool &SuppressNew) {
04044   SuppressNew = false;
04045   
04046   switch (NewTSK) {
04047   case TSK_Undeclared:
04048   case TSK_ImplicitInstantiation:
04049     assert(false && "Don't check implicit instantiations here");
04050     return false;
04051     
04052   case TSK_ExplicitSpecialization:
04053     switch (PrevTSK) {
04054     case TSK_Undeclared:
04055     case TSK_ExplicitSpecialization:
04056       // Okay, we're just specializing something that is either already 
04057       // explicitly specialized or has merely been mentioned without any
04058       // instantiation.
04059       return false;
04060 
04061     case TSK_ImplicitInstantiation:
04062       if (PrevPointOfInstantiation.isInvalid()) {
04063         // The declaration itself has not actually been instantiated, so it is
04064         // still okay to specialize it.
04065         StripImplicitInstantiation(PrevDecl);
04066         return false;
04067       }
04068       // Fall through
04069         
04070     case TSK_ExplicitInstantiationDeclaration:
04071     case TSK_ExplicitInstantiationDefinition:
04072       assert((PrevTSK == TSK_ImplicitInstantiation || 
04073               PrevPointOfInstantiation.isValid()) && 
04074              "Explicit instantiation without point of instantiation?");
04075         
04076       // C++ [temp.expl.spec]p6:
04077       //   If a template, a member template or the member of a class template 
04078       //   is explicitly specialized then that specialization shall be declared
04079       //   before the first use of that specialization that would cause an 
04080       //   implicit instantiation to take place, in every translation unit in
04081       //   which such a use occurs; no diagnostic is required.
04082       for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
04083         // Is there any previous explicit specialization declaration?
04084         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
04085           return false;
04086       }
04087 
04088       Diag(NewLoc, diag::err_specialization_after_instantiation)
04089         << PrevDecl;
04090       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
04091         << (PrevTSK != TSK_ImplicitInstantiation);
04092       
04093       return true;
04094     }
04095     break;
04096       
04097   case TSK_ExplicitInstantiationDeclaration:
04098     switch (PrevTSK) {
04099     case TSK_ExplicitInstantiationDeclaration:
04100       // This explicit instantiation declaration is redundant (that's okay).
04101       SuppressNew = true;
04102       return false;
04103         
04104     case TSK_Undeclared:
04105     case TSK_ImplicitInstantiation:
04106       // We're explicitly instantiating something that may have already been
04107       // implicitly instantiated; that's fine.
04108       return false;
04109         
04110     case TSK_ExplicitSpecialization:
04111       // C++0x [temp.explicit]p4:
04112       //   For a given set of template parameters, if an explicit instantiation
04113       //   of a template appears after a declaration of an explicit 
04114       //   specialization for that template, the explicit instantiation has no
04115       //   effect.
04116       SuppressNew = true;
04117       return false;
04118         
04119     case TSK_ExplicitInstantiationDefinition:
04120       // C++0x [temp.explicit]p10:
04121       //   If an entity is the subject of both an explicit instantiation 
04122       //   declaration and an explicit instantiation definition in the same 
04123       //   translation unit, the definition shall follow the declaration.
04124       Diag(NewLoc, 
04125            diag::err_explicit_instantiation_declaration_after_definition);
04126       Diag(PrevPointOfInstantiation, 
04127            diag::note_explicit_instantiation_definition_here);
04128       assert(PrevPointOfInstantiation.isValid() &&
04129              "Explicit instantiation without point of instantiation?");
04130       SuppressNew = true;
04131       return false;
04132     }
04133     break;
04134       
04135   case TSK_ExplicitInstantiationDefinition:
04136     switch (PrevTSK) {
04137     case TSK_Undeclared:
04138     case TSK_ImplicitInstantiation:
04139       // We're explicitly instantiating something that may have already been
04140       // implicitly instantiated; that's fine.
04141       return false;
04142         
04143     case TSK_ExplicitSpecialization:
04144       // C++ DR 259, C++0x [temp.explicit]p4:
04145       //   For a given set of template parameters, if an explicit
04146       //   instantiation of a template appears after a declaration of
04147       //   an explicit specialization for that template, the explicit
04148       //   instantiation has no effect.
04149       //
04150       // In C++98/03 mode, we only give an extension warning here, because it 
04151       // is not harmful to try to explicitly instantiate something that
04152       // has been explicitly specialized.
04153       if (!getLangOptions().CPlusPlus0x) {
04154         Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
04155           << PrevDecl;
04156         Diag(PrevDecl->getLocation(),
04157              diag::note_previous_template_specialization);
04158       }
04159       SuppressNew = true;
04160       return false;
04161         
04162     case TSK_ExplicitInstantiationDeclaration:
04163       // We're explicity instantiating a definition for something for which we
04164       // were previously asked to suppress instantiations. That's fine. 
04165       return false;
04166         
04167     case TSK_ExplicitInstantiationDefinition:
04168       // C++0x [temp.spec]p5:
04169       //   For a given template and a given set of template-arguments,
04170       //     - an explicit instantiation definition shall appear at most once
04171       //       in a program,
04172       Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
04173         << PrevDecl;
04174       Diag(PrevPointOfInstantiation, 
04175            diag::note_previous_explicit_instantiation);
04176       SuppressNew = true;
04177       return false;        
04178     }
04179     break;
04180   }
04181   
04182   assert(false && "Missing specialization/instantiation case?");
04183          
04184   return false;
04185 }
04186 
04187 /// \brief Perform semantic analysis for the given dependent function
04188 /// template specialization.  The only possible way to get a dependent
04189 /// function template specialization is with a friend declaration,
04190 /// like so:
04191 ///
04192 ///   template <class T> void foo(T);
04193 ///   template <class T> class A {
04194 ///     friend void foo<>(T);
04195 ///   };
04196 ///
04197 /// There really isn't any useful analysis we can do here, so we
04198 /// just store the information.
04199 bool
04200 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
04201                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
04202                                                    LookupResult &Previous) {
04203   // Remove anything from Previous that isn't a function template in
04204   // the correct context.
04205   DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
04206   LookupResult::Filter F = Previous.makeFilter();
04207   while (F.hasNext()) {
04208     NamedDecl *D = F.next()->getUnderlyingDecl();
04209     if (!isa<FunctionTemplateDecl>(D) ||
04210         !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
04211       F.erase();
04212   }
04213   F.done();
04214 
04215   // Should this be diagnosed here?
04216   if (Previous.empty()) return true;
04217 
04218   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
04219                                          ExplicitTemplateArgs);
04220   return false;
04221 }
04222 
04223 /// \brief Perform semantic analysis for the given function template 
04224 /// specialization.
04225 ///
04226 /// This routine performs all of the semantic analysis required for an 
04227 /// explicit function template specialization. On successful completion,
04228 /// the function declaration \p FD will become a function template
04229 /// specialization.
04230 ///
04231 /// \param FD the function declaration, which will be updated to become a
04232 /// function template specialization.
04233 ///
04234 /// \param HasExplicitTemplateArgs whether any template arguments were
04235 /// explicitly provided.
04236 ///
04237 /// \param LAngleLoc the location of the left angle bracket ('<'), if
04238 /// template arguments were explicitly provided.
04239 ///
04240 /// \param ExplicitTemplateArgs the explicitly-provided template arguments, 
04241 /// if any.
04242 ///
04243 /// \param NumExplicitTemplateArgs the number of explicitly-provided template
04244 /// arguments. This number may be zero even when HasExplicitTemplateArgs is
04245 /// true as in, e.g., \c void sort<>(char*, char*);
04246 ///
04247 /// \param RAngleLoc the location of the right angle bracket ('>'), if
04248 /// template arguments were explicitly provided.
04249 /// 
04250 /// \param PrevDecl the set of declarations that 
04251 bool 
04252 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
04253                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
04254                                           LookupResult &Previous) {
04255   // The set of function template specializations that could match this
04256   // explicit function template specialization.
04257   UnresolvedSet<8> Candidates;
04258   
04259   DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
04260   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
04261          I != E; ++I) {
04262     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
04263     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
04264       // Only consider templates found within the same semantic lookup scope as 
04265       // FD.
04266       if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
04267         continue;
04268       
04269       // C++ [temp.expl.spec]p11:
04270       //   A trailing template-argument can be left unspecified in the 
04271       //   template-id naming an explicit function template specialization 
04272       //   provided it can be deduced from the function argument type.
04273       // Perform template argument deduction to determine whether we may be
04274       // specializing this template.
04275       // FIXME: It is somewhat wasteful to build
04276       TemplateDeductionInfo Info(Context, FD->getLocation());
04277       FunctionDecl *Specialization = 0;
04278       if (TemplateDeductionResult TDK
04279             = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
04280                                       FD->getType(),
04281                                       Specialization,
04282                                       Info)) {
04283         // FIXME: Template argument deduction failed; record why it failed, so
04284         // that we can provide nifty diagnostics.
04285         (void)TDK;
04286         continue;
04287       }
04288       
04289       // Record this candidate.
04290       Candidates.addDecl(Specialization, I.getAccess());
04291     }
04292   }
04293   
04294   // Find the most specialized function template.
04295   UnresolvedSetIterator Result
04296     = getMostSpecialized(Candidates.begin(), Candidates.end(),
04297                          TPOC_Other, FD->getLocation(),
04298                   PDiag(diag::err_function_template_spec_no_match) 
04299                     << FD->getDeclName(),
04300                   PDiag(diag::err_function_template_spec_ambiguous)
04301                     << FD->getDeclName() << (ExplicitTemplateArgs != 0),
04302                   PDiag(diag::note_function_template_spec_matched));
04303   if (Result == Candidates.end())
04304     return true;
04305 
04306   // Ignore access information;  it doesn't figure into redeclaration checking.
04307   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
04308   Specialization->setLocation(FD->getLocation());
04309   
04310   // FIXME: Check if the prior specialization has a point of instantiation.
04311   // If so, we have run afoul of .
04312 
04313   // If this is a friend declaration, then we're not really declaring
04314   // an explicit specialization.
04315   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
04316   
04317   // Check the scope of this explicit specialization.
04318   if (!isFriend &&
04319       CheckTemplateSpecializationScope(*this, 
04320                                        Specialization->getPrimaryTemplate(),
04321                                        Specialization, FD->getLocation(), 
04322                                        false))
04323     return true;
04324 
04325   // C++ [temp.expl.spec]p6:
04326   //   If a template, a member template or the member of a class template is
04327   //   explicitly specialized then that specialization shall be declared 
04328   //   before the first use of that specialization that would cause an implicit
04329   //   instantiation to take place, in every translation unit in which such a 
04330   //   use occurs; no diagnostic is required.
04331   FunctionTemplateSpecializationInfo *SpecInfo
04332     = Specialization->getTemplateSpecializationInfo();
04333   assert(SpecInfo && "Function template specialization info missing?");
04334 
04335   bool SuppressNew = false;
04336   if (!isFriend &&
04337       CheckSpecializationInstantiationRedecl(FD->getLocation(),
04338                                              TSK_ExplicitSpecialization,
04339                                              Specialization,
04340                                    SpecInfo->getTemplateSpecializationKind(),
04341                                          SpecInfo->getPointOfInstantiation(),
04342                                              SuppressNew))
04343     return true;
04344   
04345   // Mark the prior declaration as an explicit specialization, so that later
04346   // clients know that this is an explicit specialization.
04347   if (!isFriend)
04348     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
04349   
04350   // Turn the given function declaration into a function template
04351   // specialization, with the template arguments from the previous
04352   // specialization.
04353   FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
04354                          new (Context) TemplateArgumentList(
04355                              *Specialization->getTemplateSpecializationArgs()), 
04356                                         /*InsertPos=*/0, 
04357                                     SpecInfo->getTemplateSpecializationKind());
04358   
04359   // The "previous declaration" for this function template specialization is
04360   // the prior function template specialization.
04361   Previous.clear();
04362   Previous.addDecl(Specialization);
04363   return false;
04364 }
04365 
04366 /// \brief Perform semantic analysis for the given non-template member
04367 /// specialization.
04368 ///
04369 /// This routine performs all of the semantic analysis required for an 
04370 /// explicit member function specialization. On successful completion,
04371 /// the function declaration \p FD will become a member function
04372 /// specialization.
04373 ///
04374 /// \param Member the member declaration, which will be updated to become a
04375 /// specialization.
04376 ///
04377 /// \param Previous the set of declarations, one of which may be specialized
04378 /// by this function specialization;  the set will be modified to contain the
04379 /// redeclared member.
04380 bool 
04381 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
04382   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
04383 
04384   // Try to find the member we are instantiating.
04385   NamedDecl *Instantiation = 0;
04386   NamedDecl *InstantiatedFrom = 0;
04387   MemberSpecializationInfo *MSInfo = 0;
04388 
04389   if (Previous.empty()) {
04390     // Nowhere to look anyway.
04391   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
04392     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
04393            I != E; ++I) {
04394       NamedDecl *D = (*I)->getUnderlyingDecl();
04395       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
04396         if (Context.hasSameType(Function->getType(), Method->getType())) {
04397           Instantiation = Method;
04398           InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
04399           MSInfo = Method->getMemberSpecializationInfo();
04400           break;
04401         }
04402       }
04403     }
04404   } else if (isa<VarDecl>(Member)) {
04405     VarDecl *PrevVar;
04406     if (Previous.isSingleResult() &&
04407         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
04408       if (PrevVar->isStaticDataMember()) {
04409         Instantiation = PrevVar;
04410         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
04411         MSInfo = PrevVar->getMemberSpecializationInfo();
04412       }
04413   } else if (isa<RecordDecl>(Member)) {
04414     CXXRecordDecl *PrevRecord;
04415     if (Previous.isSingleResult() &&
04416         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
04417       Instantiation = PrevRecord;
04418       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
04419       MSInfo = PrevRecord->getMemberSpecializationInfo();
04420     }
04421   }
04422   
04423   if (!Instantiation) {
04424     // There is no previous declaration that matches. Since member
04425     // specializations are always out-of-line, the caller will complain about
04426     // this mismatch later.
04427     return false;
04428   }
04429 
04430   // If this is a friend, just bail out here before we start turning
04431   // things into explicit specializations.
04432   if (Member->getFriendObjectKind() != Decl::FOK_None) {
04433     // Preserve instantiation information.
04434     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
04435       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
04436                                       cast<CXXMethodDecl>(InstantiatedFrom),
04437         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
04438     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
04439       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
04440                                       cast<CXXRecordDecl>(InstantiatedFrom),
04441         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
04442     }
04443 
04444     Previous.clear();
04445     Previous.addDecl(Instantiation);
04446     return false;
04447   }
04448   
04449   // Make sure that this is a specialization of a member.
04450   if (!InstantiatedFrom) {
04451     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
04452       << Member;
04453     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
04454     return true;
04455   }
04456   
04457   // C++ [temp.expl.spec]p6:
04458   //   If a template, a member template or the member of a class template is
04459   //   explicitly specialized then that spe- cialization shall be declared 
04460   //   before the first use of that specialization that would cause an implicit
04461   //   instantiation to take place, in every translation unit in which such a 
04462   //   use occurs; no diagnostic is required.
04463   assert(MSInfo && "Member specialization info missing?");
04464 
04465   bool SuppressNew = false;
04466   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
04467                                              TSK_ExplicitSpecialization,
04468                                              Instantiation,
04469                                      MSInfo->getTemplateSpecializationKind(),
04470                                            MSInfo->getPointOfInstantiation(),
04471                                              SuppressNew))
04472     return true;
04473   
04474   // Check the scope of this explicit specialization.
04475   if (CheckTemplateSpecializationScope(*this, 
04476                                        InstantiatedFrom,
04477                                        Instantiation, Member->getLocation(), 
04478                                        false))
04479     return true;
04480 
04481   // Note that this is an explicit instantiation of a member.
04482   // the original declaration to note that it is an explicit specialization
04483   // (if it was previously an implicit instantiation). This latter step
04484   // makes bookkeeping easier.
04485   if (isa<FunctionDecl>(Member)) {
04486     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
04487     if (InstantiationFunction->getTemplateSpecializationKind() ==
04488           TSK_ImplicitInstantiation) {
04489       InstantiationFunction->setTemplateSpecializationKind(
04490                                                   TSK_ExplicitSpecialization);
04491       InstantiationFunction->setLocation(Member->getLocation());
04492     }
04493     
04494     cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
04495                                         cast<CXXMethodDecl>(InstantiatedFrom),
04496                                                   TSK_ExplicitSpecialization);
04497   } else if (isa<VarDecl>(Member)) {
04498     VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
04499     if (InstantiationVar->getTemplateSpecializationKind() ==
04500           TSK_ImplicitInstantiation) {
04501       InstantiationVar->setTemplateSpecializationKind(
04502                                                   TSK_ExplicitSpecialization);
04503       InstantiationVar->setLocation(Member->getLocation());
04504     }
04505     
04506     Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
04507                                                 cast<VarDecl>(InstantiatedFrom),
04508                                                 TSK_ExplicitSpecialization);
04509   } else {
04510     assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
04511     CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
04512     if (InstantiationClass->getTemplateSpecializationKind() ==
04513           TSK_ImplicitInstantiation) {
04514       InstantiationClass->setTemplateSpecializationKind(
04515                                                    TSK_ExplicitSpecialization);
04516       InstantiationClass->setLocation(Member->getLocation());
04517     }
04518     
04519     cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
04520                                         cast<CXXRecordDecl>(InstantiatedFrom),
04521                                                    TSK_ExplicitSpecialization);
04522   }
04523              
04524   // Save the caller the trouble of having to figure out which declaration
04525   // this specialization matches.
04526   Previous.clear();
04527   Previous.addDecl(Instantiation);
04528   return false;
04529 }
04530 
04531 /// \brief Check the scope of an explicit instantiation.
04532 static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
04533                                             SourceLocation InstLoc,
04534                                             bool WasQualifiedName) {
04535   DeclContext *ExpectedContext
04536     = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
04537   DeclContext *CurContext = S.CurContext->getLookupContext();
04538   
04539   // C++0x [temp.explicit]p2:
04540   //   An explicit instantiation shall appear in an enclosing namespace of its 
04541   //   template.
04542   //
04543   // This is DR275, which we do not retroactively apply to C++98/03.
04544   if (S.getLangOptions().CPlusPlus0x && 
04545       !CurContext->Encloses(ExpectedContext)) {
04546     if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
04547       S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope)
04548         << D << NS;
04549     else
04550       S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global)
04551         << D;
04552     S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
04553     return;
04554   }
04555   
04556   // C++0x [temp.explicit]p2:
04557   //   If the name declared in the explicit instantiation is an unqualified 
04558   //   name, the explicit instantiation shall appear in the namespace where 
04559   //   its template is declared or, if that namespace is inline (7.3.1), any
04560   //   namespace from its enclosing namespace set.
04561   if (WasQualifiedName)
04562     return;
04563   
04564   if (CurContext->Equals(ExpectedContext))
04565     return;
04566   
04567   S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace)
04568     << D << ExpectedContext;
04569   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
04570 }
04571 
04572 /// \brief Determine whether the given scope specifier has a template-id in it.
04573 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
04574   if (!SS.isSet())
04575     return false;
04576   
04577   // C++0x [temp.explicit]p2:
04578   //   If the explicit instantiation is for a member function, a member class 
04579   //   or a static data member of a class template specialization, the name of
04580   //   the class template specialization in the qualified-id for the member
04581   //   name shall be a simple-template-id.
04582   //
04583   // C++98 has the same restriction, just worded differently.
04584   for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
04585        NNS; NNS = NNS->getPrefix())
04586     if (Type *T = NNS->getAsType())
04587       if (isa<TemplateSpecializationType>(T))
04588         return true;
04589 
04590   return false;
04591 }
04592 
04593 // Explicit instantiation of a class template specialization
04594 // FIXME: Implement extern template semantics
04595 Sema::DeclResult
04596 Sema::ActOnExplicitInstantiation(Scope *S,
04597                                  SourceLocation ExternLoc,
04598                                  SourceLocation TemplateLoc,
04599                                  unsigned TagSpec,
04600                                  SourceLocation KWLoc,
04601                                  const CXXScopeSpec &SS,
04602                                  TemplateTy TemplateD,
04603                                  SourceLocation TemplateNameLoc,
04604                                  SourceLocation LAngleLoc,
04605                                  ASTTemplateArgsPtr TemplateArgsIn,
04606                                  SourceLocation RAngleLoc,
04607                                  AttributeList *Attr) {
04608   // Find the class template we're specializing
04609   TemplateName Name = TemplateD.getAsVal<TemplateName>();
04610   ClassTemplateDecl *ClassTemplate
04611     = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
04612 
04613   // Check that the specialization uses the same tag kind as the
04614   // original template.
04615   TagDecl::TagKind Kind;
04616   switch (TagSpec) {
04617   default: assert(0 && "Unknown tag type!");
04618   case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
04619   case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
04620   case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
04621   }
04622   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
04623                                     Kind, KWLoc,
04624                                     *ClassTemplate->getIdentifier())) {
04625     Diag(KWLoc, diag::err_use_with_wrong_tag)
04626       << ClassTemplate
04627       << FixItHint::CreateReplacement(KWLoc,
04628                             ClassTemplate->getTemplatedDecl()->getKindName());
04629     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
04630          diag::note_previous_use);
04631     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
04632   }
04633 
04634   // C++0x [temp.explicit]p2:
04635   //   There are two forms of explicit instantiation: an explicit instantiation
04636   //   definition and an explicit instantiation declaration. An explicit 
04637   //   instantiation declaration begins with the extern keyword. [...]  
04638   TemplateSpecializationKind TSK
04639     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
04640                            : TSK_ExplicitInstantiationDeclaration;
04641   
04642   // Translate the parser's template argument list in our AST format.
04643   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
04644   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
04645 
04646   // Check that the template argument list is well-formed for this
04647   // template.
04648   TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
04649                                         TemplateArgs.size());
04650   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
04651                                 TemplateArgs, false, Converted))
04652     return true;
04653 
04654   assert((Converted.structuredSize() ==
04655             ClassTemplate->getTemplateParameters()->size()) &&
04656          "Converted template argument list is too short!");
04657 
04658   // Find the class template specialization declaration that
04659   // corresponds to these arguments.
04660   llvm::FoldingSetNodeID ID;
04661   ClassTemplateSpecializationDecl::Profile(ID,
04662                                            Converted.getFlatArguments(),
04663                                            Converted.flatSize(),
04664                                            Context);
04665   void *InsertPos = 0;
04666   ClassTemplateSpecializationDecl *PrevDecl
04667     = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
04668 
04669   // C++0x [temp.explicit]p2:
04670   //   [...] An explicit instantiation shall appear in an enclosing
04671   //   namespace of its template. [...]
04672   //
04673   // This is C++ DR 275.
04674   CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
04675                                   SS.isSet());
04676   
04677   ClassTemplateSpecializationDecl *Specialization = 0;
04678 
04679   bool ReusedDecl = false;
04680   if (PrevDecl) {
04681     bool SuppressNew = false;
04682     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
04683                                                PrevDecl, 
04684                                               PrevDecl->getSpecializationKind(), 
04685                                             PrevDecl->getPointOfInstantiation(),
04686                                                SuppressNew))
04687       return DeclPtrTy::make(PrevDecl);
04688 
04689     if (SuppressNew)
04690       return DeclPtrTy::make(PrevDecl);
04691     
04692     if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
04693         PrevDecl->getSpecializationKind() == TSK_Undeclared) {
04694       // Since the only prior class template specialization with these
04695       // arguments was referenced but not declared, reuse that
04696       // declaration node as our own, updating its source location to
04697       // reflect our new declaration.
04698       Specialization = PrevDecl;
04699       Specialization->setLocation(TemplateNameLoc);
04700       PrevDecl = 0;
04701       ReusedDecl = true;
04702     }
04703   }
04704   
04705   if (!Specialization) {
04706     // Create a new class template specialization declaration node for
04707     // this explicit specialization.
04708     Specialization
04709       = ClassTemplateSpecializationDecl::Create(Context, Kind,
04710                                              ClassTemplate->getDeclContext(),
04711                                                 TemplateNameLoc,
04712                                                 ClassTemplate,
04713                                                 Converted, PrevDecl);
04714     SetNestedNameSpecifier(Specialization, SS);
04715 
04716     if (PrevDecl) {
04717       // Remove the previous declaration from the folding set, since we want
04718       // to introduce a new declaration.
04719       ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
04720       ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
04721     } 
04722     
04723     // Insert the new specialization.
04724     ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
04725   }
04726 
04727   // Build the fully-sugared type for this explicit instantiation as
04728   // the user wrote in the explicit instantiation itself. This means
04729   // that we'll pretty-print the type retrieved from the
04730   // specialization's declaration the way that the user actually wrote
04731   // the explicit instantiation, rather than formatting the name based
04732   // on the "canonical" representation used to store the template
04733   // arguments in the specialization.
04734   TypeSourceInfo *WrittenTy
04735     = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
04736                                                 TemplateArgs,
04737                                   Context.getTypeDeclType(Specialization));
04738   Specialization->setTypeAsWritten(WrittenTy);
04739   TemplateArgsIn.release();
04740 
04741   if (!ReusedDecl) {
04742     // Add the explicit instantiation into its lexical context. However,
04743     // since explicit instantiations are never found by name lookup, we
04744     // just put it into the declaration context directly.
04745     Specialization->setLexicalDeclContext(CurContext);
04746     CurContext->addDecl(Specialization);
04747   }
04748 
04749   // C++ [temp.explicit]p3:
04750   //   A definition of a class template or class member template
04751   //   shall be in scope at the point of the explicit instantiation of
04752   //   the class template or class member template.
04753   //
04754   // This check comes when we actually try to perform the
04755   // instantiation.
04756   ClassTemplateSpecializationDecl *Def
04757     = cast_or_null<ClassTemplateSpecializationDecl>(
04758                                               Specialization->getDefinition());
04759   if (!Def)
04760     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
04761   
04762   // Instantiate the members of this class template specialization.
04763   Def = cast_or_null<ClassTemplateSpecializationDecl>(
04764                                        Specialization->getDefinition());
04765   if (Def) {
04766     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
04767 
04768     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
04769     // TSK_ExplicitInstantiationDefinition
04770     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
04771         TSK == TSK_ExplicitInstantiationDefinition)
04772       Def->setTemplateSpecializationKind(TSK);
04773 
04774     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
04775   }
04776 
04777   return DeclPtrTy::make(Specialization);
04778 }
04779 
04780 // Explicit instantiation of a member class of a class template.
04781 Sema::DeclResult
04782 Sema::ActOnExplicitInstantiation(Scope *S,
04783                                  SourceLocation ExternLoc,
04784                                  SourceLocation TemplateLoc,
04785                                  unsigned TagSpec,
04786                                  SourceLocation KWLoc,
04787                                  CXXScopeSpec &SS,
04788                                  IdentifierInfo *Name,
04789                                  SourceLocation NameLoc,
04790                                  AttributeList *Attr) {
04791 
04792   bool Owned = false;
04793   bool IsDependent = false;
04794   DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
04795                             KWLoc, SS, Name, NameLoc, Attr, AS_none,
04796                             MultiTemplateParamsArg(*this, 0, 0),
04797                             Owned, IsDependent);
04798   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
04799 
04800   if (!TagD)
04801     return true;
04802 
04803   TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
04804   if (Tag->isEnum()) {
04805     Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
04806       << Context.getTypeDeclType(Tag);
04807     return true;
04808   }
04809 
04810   if (Tag->isInvalidDecl())
04811     return true;
04812     
04813   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
04814   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
04815   if (!Pattern) {
04816     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
04817       << Context.getTypeDeclType(Record);
04818     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
04819     return true;
04820   }
04821 
04822   // C++0x [temp.explicit]p2:
04823   //   If the explicit instantiation is for a class or member class, the 
04824   //   elaborated-type-specifier in the declaration shall include a 
04825   //   simple-template-id.
04826   //
04827   // C++98 has the same restriction, just worded differently.
04828   if (!ScopeSpecifierHasTemplateId(SS))
04829     Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
04830       << Record << SS.getRange();
04831            
04832   // C++0x [temp.explicit]p2:
04833   //   There are two forms of explicit instantiation: an explicit instantiation
04834   //   definition and an explicit instantiation declaration. An explicit 
04835   //   instantiation declaration begins with the extern keyword. [...]
04836   TemplateSpecializationKind TSK
04837     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
04838                            : TSK_ExplicitInstantiationDeclaration;
04839   
04840   // C++0x [temp.explicit]p2:
04841   //   [...] An explicit instantiation shall appear in an enclosing
04842   //   namespace of its template. [...]
04843   //
04844   // This is C++ DR 275.
04845   CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
04846   
04847   // Verify that it is okay to explicitly instantiate here.
04848   CXXRecordDecl *PrevDecl 
04849     = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
04850   if (!PrevDecl && Record->getDefinition())
04851     PrevDecl = Record;
04852   if (PrevDecl) {
04853     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
04854     bool SuppressNew = false;
04855     assert(MSInfo && "No member specialization information?");
04856     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 
04857                                                PrevDecl,
04858                                         MSInfo->getTemplateSpecializationKind(),
04859                                              MSInfo->getPointOfInstantiation(), 
04860                                                SuppressNew))
04861       return true;
04862     if (SuppressNew)
04863       return TagD;
04864   }
04865   
04866   CXXRecordDecl *RecordDef
04867     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
04868   if (!RecordDef) {
04869     // C++ [temp.explicit]p3:
04870     //   A definition of a member class of a class template shall be in scope 
04871     //   at the point of an explicit instantiation of the member class.
04872     CXXRecordDecl *Def 
04873       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
04874     if (!Def) {
04875       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
04876         << 0 << Record->getDeclName() << Record->getDeclContext();
04877       Diag(Pattern->getLocation(), diag::note_forward_declaration)
04878         << Pattern;
04879       return true;
04880     } else {
04881       if (InstantiateClass(NameLoc, Record, Def,
04882                            getTemplateInstantiationArgs(Record),
04883                            TSK))
04884         return true;
04885 
04886       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
04887       if (!RecordDef)
04888         return true;
04889     }
04890   } 
04891   
04892   // Instantiate all of the members of the class.
04893   InstantiateClassMembers(NameLoc, RecordDef,
04894                           getTemplateInstantiationArgs(Record), TSK);
04895 
04896   // FIXME: We don't have any representation for explicit instantiations of
04897   // member classes. Such a representation is not needed for compilation, but it
04898   // should be available for clients that want to see all of the declarations in
04899   // the source code.
04900   return TagD;
04901 }
04902 
04903 Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
04904                                                   SourceLocation ExternLoc,
04905                                                   SourceLocation TemplateLoc,
04906                                                   Declarator &D) {
04907   // Explicit instantiations always require a name.
04908   DeclarationName Name = GetNameForDeclarator(D);
04909   if (!Name) {
04910     if (!D.isInvalidType())
04911       Diag(D.getDeclSpec().getSourceRange().getBegin(),
04912            diag::err_explicit_instantiation_requires_name)
04913         << D.getDeclSpec().getSourceRange()
04914         << D.getSourceRange();
04915     
04916     return true;
04917   }
04918 
04919   // The scope passed in may not be a decl scope.  Zip up the scope tree until
04920   // we find one that is.
04921   while ((S->getFlags() & Scope::DeclScope) == 0 ||
04922          (S->getFlags() & Scope::TemplateParamScope) != 0)
04923     S = S->getParent();
04924 
04925   // Determine the type of the declaration.
04926   QualType R = GetTypeForDeclarator(D, S, 0);
04927   if (R.isNull())
04928     return true;
04929   
04930   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
04931     // Cannot explicitly instantiate a typedef.
04932     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
04933       << Name;
04934     return true;
04935   }
04936 
04937   // C++0x [temp.explicit]p1:
04938   //   [...] An explicit instantiation of a function template shall not use the
04939   //   inline or constexpr specifiers.
04940   // Presumably, this also applies to member functions of class templates as
04941   // well.
04942   if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
04943     Diag(D.getDeclSpec().getInlineSpecLoc(), 
04944          diag::err_explicit_instantiation_inline)
04945       <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
04946   
04947   // FIXME: check for constexpr specifier.
04948   
04949   // C++0x [temp.explicit]p2:
04950   //   There are two forms of explicit instantiation: an explicit instantiation
04951   //   definition and an explicit instantiation declaration. An explicit 
04952   //   instantiation declaration begins with the extern keyword. [...]  
04953   TemplateSpecializationKind TSK
04954     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
04955                            : TSK_ExplicitInstantiationDeclaration;
04956     
04957   LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
04958   LookupParsedName(Previous, S, &D.getCXXScopeSpec());
04959 
04960   if (!R->isFunctionType()) {
04961     // C++ [temp.explicit]p1:
04962     //   A [...] static data member of a class template can be explicitly 
04963     //   instantiated from the member definition associated with its class 
04964     //   template.
04965     if (Previous.isAmbiguous())
04966       return true;
04967     
04968     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
04969     if (!Prev || !Prev->isStaticDataMember()) {
04970       // We expect to see a data data member here.
04971       Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
04972         << Name;
04973       for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
04974            P != PEnd; ++P)
04975         Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
04976       return true;
04977     }
04978     
04979     if (!Prev->getInstantiatedFromStaticDataMember()) {
04980       // FIXME: Check for explicit specialization?
04981       Diag(D.getIdentifierLoc(), 
04982            diag::err_explicit_instantiation_data_member_not_instantiated)
04983         << Prev;
04984       Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
04985       // FIXME: Can we provide a note showing where this was declared?
04986       return true;
04987     }
04988     
04989     // C++0x [temp.explicit]p2:
04990     //   If the explicit instantiation is for a member function, a member class 
04991     //   or a static data member of a class template specialization, the name of
04992     //   the class template specialization in the qualified-id for the member
04993     //   name shall be a simple-template-id.
04994     //
04995     // C++98 has the same restriction, just worded differently.
04996     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
04997       Diag(D.getIdentifierLoc(), 
04998            diag::err_explicit_instantiation_without_qualified_id)
04999         << Prev << D.getCXXScopeSpec().getRange();
05000     
05001     // Check the scope of this explicit instantiation.
05002     CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
05003     
05004     // Verify that it is okay to explicitly instantiate here.
05005     MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
05006     assert(MSInfo && "Missing static data member specialization info?");
05007     bool SuppressNew = false;
05008     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
05009                                         MSInfo->getTemplateSpecializationKind(),
05010                                               MSInfo->getPointOfInstantiation(), 
05011                                                SuppressNew))
05012       return true;
05013     if (SuppressNew)
05014       return DeclPtrTy();
05015     
05016     // Instantiate static data member.
05017     Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
05018     if (TSK == TSK_ExplicitInstantiationDefinition)
05019       InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
05020                                             /*DefinitionRequired=*/true);
05021     
05022     // FIXME: Create an ExplicitInstantiation node?
05023     return DeclPtrTy();
05024   }
05025   
05026   // If the declarator is a template-id, translate the parser's template 
05027   // argument list into our AST format.
05028   bool HasExplicitTemplateArgs = false;
05029   TemplateArgumentListInfo TemplateArgs;
05030   if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
05031     TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
05032     TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
05033     TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
05034     ASTTemplateArgsPtr TemplateArgsPtr(*this,
05035                                        TemplateId->getTemplateArgs(),
05036                                        TemplateId->NumArgs);
05037     translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
05038     HasExplicitTemplateArgs = true;
05039     TemplateArgsPtr.release();
05040   }
05041     
05042   // C++ [temp.explicit]p1:
05043   //   A [...] function [...] can be explicitly instantiated from its template. 
05044   //   A member function [...] of a class template can be explicitly 
05045   //  instantiated from the member definition associated with its class 
05046   //  template.
05047   UnresolvedSet<8> Matches;
05048   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
05049        P != PEnd; ++P) {
05050     NamedDecl *Prev = *P;
05051     if (!HasExplicitTemplateArgs) {
05052       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
05053         if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
05054           Matches.clear();
05055 
05056           Matches.addDecl(Method, P.getAccess());
05057           if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
05058             break;
05059         }
05060       }
05061     }
05062     
05063     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
05064     if (!FunTmpl)
05065       continue;
05066 
05067     TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
05068     FunctionDecl *Specialization = 0;
05069     if (TemplateDeductionResult TDK
05070           = DeduceTemplateArguments(FunTmpl, 
05071                                (HasExplicitTemplateArgs ? &TemplateArgs : 0),
05072                                     R, Specialization, Info)) {
05073       // FIXME: Keep track of almost-matches?
05074       (void)TDK;
05075       continue;
05076     }
05077     
05078     Matches.addDecl(Specialization, P.getAccess());
05079   }
05080   
05081   // Find the most specialized function template specialization.
05082   UnresolvedSetIterator Result
05083     = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 
05084                          D.getIdentifierLoc(), 
05085                      PDiag(diag::err_explicit_instantiation_not_known) << Name,
05086                      PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
05087                          PDiag(diag::note_explicit_instantiation_candidate));
05088 
05089   if (Result == Matches.end())
05090     return true;
05091 
05092   // Ignore access control bits, we don't need them for redeclaration checking.
05093   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
05094   
05095   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
05096     Diag(D.getIdentifierLoc(), 
05097          diag::err_explicit_instantiation_member_function_not_instantiated)
05098       << Specialization
05099       << (Specialization->getTemplateSpecializationKind() ==
05100           TSK_ExplicitSpecialization);
05101     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
05102     return true;
05103   } 
05104   
05105   FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
05106   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
05107     PrevDecl = Specialization;
05108 
05109   if (PrevDecl) {
05110     bool SuppressNew = false;
05111     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
05112                                                PrevDecl, 
05113                                      PrevDecl->getTemplateSpecializationKind(), 
05114                                           PrevDecl->getPointOfInstantiation(),
05115                                                SuppressNew))
05116       return true;
05117     
05118     // FIXME: We may still want to build some representation of this
05119     // explicit specialization.
05120     if (SuppressNew)
05121       return DeclPtrTy();
05122   }
05123 
05124   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
05125   
05126   if (TSK == TSK_ExplicitInstantiationDefinition)
05127     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization, 
05128                                   false, /*DefinitionRequired=*/true);
05129  
05130   // C++0x [temp.explicit]p2:
05131   //   If the explicit instantiation is for a member function, a member class 
05132   //   or a static data member of a class template specialization, the name of
05133   //   the class template specialization in the qualified-id for the member
05134   //   name shall be a simple-template-id.
05135   //
05136   // C++98 has the same restriction, just worded differently.
05137   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
05138   if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
05139       D.getCXXScopeSpec().isSet() && 
05140       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
05141     Diag(D.getIdentifierLoc(), 
05142          diag::err_explicit_instantiation_without_qualified_id)
05143     << Specialization << D.getCXXScopeSpec().getRange();
05144   
05145   CheckExplicitInstantiationScope(*this,
05146                    FunTmpl? (NamedDecl *)FunTmpl 
05147                           : Specialization->getInstantiatedFromMemberFunction(),
05148                                   D.getIdentifierLoc(), 
05149                                   D.getCXXScopeSpec().isSet());
05150   
05151   // FIXME: Create some kind of ExplicitInstantiationDecl here.
05152   return DeclPtrTy();
05153 }
05154 
05155 Sema::TypeResult
05156 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
05157                         const CXXScopeSpec &SS, IdentifierInfo *Name,
05158                         SourceLocation TagLoc, SourceLocation NameLoc) {
05159   // This has to hold, because SS is expected to be defined.
05160   assert(Name && "Expected a name in a dependent tag");
05161 
05162   NestedNameSpecifier *NNS
05163     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
05164   if (!NNS)
05165     return true;
05166 
05167   ElaboratedTypeKeyword Keyword = ETK_None;
05168   switch (TagDecl::getTagKindForTypeSpec(TagSpec)) {
05169   case TagDecl::TK_struct: Keyword = ETK_Struct; break;
05170   case TagDecl::TK_class: Keyword = ETK_Class; break;
05171   case TagDecl::TK_union: Keyword = ETK_Union; break;
05172   case TagDecl::TK_enum: Keyword = ETK_Enum; break;
05173   }
05174   assert(Keyword != ETK_None && "Invalid tag kind!");
05175 
05176   if (TUK == TUK_Declaration || TUK == TUK_Definition) {
05177     Diag(NameLoc, diag::err_dependent_tag_decl)
05178       << (TUK == TUK_Definition) << TagDecl::getTagKindForTypeSpec(TagSpec)
05179       << SS.getRange();
05180     return true;
05181   }
05182   
05183   return Context.getDependentNameType(Keyword, NNS, Name).getAsOpaquePtr();
05184 }
05185 
05186 static void FillTypeLoc(DependentNameTypeLoc TL,
05187                         SourceLocation TypenameLoc,
05188                         SourceRange QualifierRange) {
05189   // FIXME: typename, qualifier range
05190   TL.setNameLoc(TypenameLoc);
05191 }
05192 
05193 static void FillTypeLoc(QualifiedNameTypeLoc TL,
05194                         SourceLocation TypenameLoc,
05195                         SourceRange QualifierRange) {
05196   // FIXME: typename, qualifier range
05197   TL.setNameLoc(TypenameLoc);
05198 }
05199 
05200 Sema::TypeResult
05201 Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
05202                         const IdentifierInfo &II, SourceLocation IdLoc) {
05203   NestedNameSpecifier *NNS
05204     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
05205   if (!NNS)
05206     return true;
05207 
05208   QualType T = CheckTypenameType(ETK_Typename, NNS, II,
05209                                  SourceRange(TypenameLoc, IdLoc));
05210   if (T.isNull())
05211     return true;
05212 
05213   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
05214   if (isa<DependentNameType>(T)) {
05215     DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
05216     // FIXME: fill inner type loc
05217     FillTypeLoc(TL, TypenameLoc, SS.getRange());
05218   } else {
05219     QualifiedNameTypeLoc TL = cast<QualifiedNameTypeLoc>(TSI->getTypeLoc());
05220     // FIXME: fill inner type loc
05221     FillTypeLoc(TL, TypenameLoc, SS.getRange());
05222   }
05223   
05224   return CreateLocInfoType(T, TSI).getAsOpaquePtr();
05225 }
05226 
05227 Sema::TypeResult
05228 Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
05229                         SourceLocation TemplateLoc, TypeTy *Ty) {
05230   QualType T = GetTypeFromParser(Ty);
05231   NestedNameSpecifier *NNS
05232     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
05233   const TemplateSpecializationType *TemplateId
05234     = T->getAs<TemplateSpecializationType>();
05235   assert(TemplateId && "Expected a template specialization type");
05236 
05237   if (computeDeclContext(SS, false)) {
05238     // If we can compute a declaration context, then the "typename"
05239     // keyword was superfluous. Just build a QualifiedNameType to keep
05240     // track of the nested-name-specifier.
05241 
05242     // FIXME: Note that the QualifiedNameType had the "typename" keyword!
05243     
05244     T = Context.getQualifiedNameType(NNS, T);
05245     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
05246     QualifiedNameTypeLoc TL = cast<QualifiedNameTypeLoc>(TSI->getTypeLoc());
05247     // FIXME: fill inner type loc
05248     FillTypeLoc(TL, TypenameLoc, SS.getRange());
05249     return CreateLocInfoType(T, TSI).getAsOpaquePtr();
05250   }
05251 
05252   T = Context.getDependentNameType(ETK_Typename, NNS, TemplateId);
05253   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
05254   DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
05255   // FIXME: fill inner type loc
05256   FillTypeLoc(TL, TypenameLoc, SS.getRange());
05257   return CreateLocInfoType(T, TSI).getAsOpaquePtr();
05258 }
05259 
05260 /// \brief Build the type that describes a C++ typename specifier,
05261 /// e.g., "typename T::type".
05262 QualType
05263 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
05264                         NestedNameSpecifier *NNS, const IdentifierInfo &II,
05265                         SourceRange Range) {
05266   CXXScopeSpec SS;
05267   SS.setScopeRep(NNS);
05268   SS.setRange(Range);
05269 
05270   DeclContext *Ctx = computeDeclContext(SS);
05271   if (!Ctx) {
05272     // If the nested-name-specifier is dependent and couldn't be
05273     // resolved to a type, build a typename type.
05274     assert(NNS->isDependent());
05275     return Context.getDependentNameType(Keyword, NNS, &II);
05276   }
05277 
05278   // If the nested-name-specifier refers to the current instantiation,
05279   // the "typename" keyword itself is superfluous. In C++03, the
05280   // program is actually ill-formed. However, DR 382 (in C++0x CD1)
05281   // allows such extraneous "typename" keywords, and we retroactively
05282   // apply this DR to C++03 code.  In any case we continue.
05283 
05284   if (RequireCompleteDeclContext(SS, Ctx))
05285     return QualType();
05286 
05287   DeclarationName Name(&II);
05288   LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName);
05289   LookupQualifiedName(Result, Ctx);
05290   unsigned DiagID = 0;
05291   Decl *Referenced = 0;
05292   switch (Result.getResultKind()) {
05293   case LookupResult::NotFound:
05294     DiagID = diag::err_typename_nested_not_found;
05295     break;
05296       
05297   case LookupResult::NotFoundInCurrentInstantiation:
05298     // Okay, it's a member of an unknown instantiation.
05299     return Context.getDependentNameType(Keyword, NNS, &II);
05300 
05301   case LookupResult::Found:
05302     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
05303       // We found a type. Build a QualifiedNameType, since the
05304       // typename-specifier was just sugar. FIXME: Tell
05305       // QualifiedNameType that it has a "typename" prefix.
05306       return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
05307     }
05308 
05309     DiagID = diag::err_typename_nested_not_type;
05310     Referenced = Result.getFoundDecl();
05311     break;
05312 
05313   case LookupResult::FoundUnresolvedValue:
05314     llvm_unreachable("unresolved using decl in non-dependent context");
05315     return QualType();
05316 
05317   case LookupResult::FoundOverloaded:
05318     DiagID = diag::err_typename_nested_not_type;
05319     Referenced = *Result.begin();
05320     break;
05321 
05322   case LookupResult::Ambiguous:
05323     return QualType();
05324   }
05325 
05326   // If we get here, it's because name lookup did not find a
05327   // type. Emit an appropriate diagnostic and return an error.
05328   Diag(Range.getEnd(), DiagID) << Range << Name << Ctx;
05329   if (Referenced)
05330     Diag(Referenced->getLocation(), diag::note_typename_refers_here)
05331       << Name;
05332   return QualType();
05333 }
05334 
05335 namespace {
05336   // See Sema::RebuildTypeInCurrentInstantiation
05337   class CurrentInstantiationRebuilder
05338     : public TreeTransform<CurrentInstantiationRebuilder> {
05339     SourceLocation Loc;
05340     DeclarationName Entity;
05341 
05342   public:
05343     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
05344       
05345     CurrentInstantiationRebuilder(Sema &SemaRef,
05346                                   SourceLocation Loc,
05347                                   DeclarationName Entity)
05348     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
05349       Loc(Loc), Entity(Entity) { }
05350 
05351     /// \brief Determine whether the given type \p T has already been
05352     /// transformed.
05353     ///
05354     /// For the purposes of type reconstruction, a type has already been
05355     /// transformed if it is NULL or if it is not dependent.
05356     bool AlreadyTransformed(QualType T) {
05357       return T.isNull() || !T->isDependentType();
05358     }
05359 
05360     /// \brief Returns the location of the entity whose type is being
05361     /// rebuilt.
05362     SourceLocation getBaseLocation() { return Loc; }
05363 
05364     /// \brief Returns the name of the entity whose type is being rebuilt.
05365     DeclarationName getBaseEntity() { return Entity; }
05366 
05367     /// \brief Sets the "base" location and entity when that
05368     /// information is known based on another transformation.
05369     void setBase(SourceLocation Loc, DeclarationName Entity) {
05370       this->Loc = Loc;
05371       this->Entity = Entity;
05372     }
05373       
05374     /// \brief Transforms an expression by returning the expression itself
05375     /// (an identity function).
05376     ///
05377     /// FIXME: This is completely unsafe; we will need to actually clone the
05378     /// expressions.
05379     Sema::OwningExprResult TransformExpr(Expr *E) {
05380       return getSema().Owned(E->Retain());
05381     }
05382 
05383     /// \brief Transforms a typename type by determining whether the type now
05384     /// refers to a member of the current instantiation, and then
05385     /// type-checking and building a QualifiedNameType (when possible).
05386     QualType TransformDependentNameType(TypeLocBuilder &TLB, DependentNameTypeLoc TL, 
05387                                    QualType ObjectType);
05388   };
05389 }
05390 
05391 QualType
05392 CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
05393                                                      DependentNameTypeLoc TL, 
05394                                                      QualType ObjectType) {
05395   DependentNameType *T = TL.getTypePtr();
05396 
05397   NestedNameSpecifier *NNS
05398     = TransformNestedNameSpecifier(T->getQualifier(),
05399                                    /*FIXME:*/SourceRange(getBaseLocation()),
05400                                    ObjectType);
05401   if (!NNS)
05402     return QualType();
05403 
05404   // If the nested-name-specifier did not change, and we cannot compute the
05405   // context corresponding to the nested-name-specifier, then this
05406   // typename type will not change; exit early.
05407   CXXScopeSpec SS;
05408   SS.setRange(SourceRange(getBaseLocation()));
05409   SS.setScopeRep(NNS);
05410 
05411   QualType Result;
05412   if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
05413     Result = QualType(T, 0);
05414 
05415   // Rebuild the typename type, which will probably turn into a
05416   // QualifiedNameType.
05417   else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
05418     QualType NewTemplateId
05419       = TransformType(QualType(TemplateId, 0));
05420     if (NewTemplateId.isNull())
05421       return QualType();
05422 
05423     if (NNS == T->getQualifier() &&
05424         NewTemplateId == QualType(TemplateId, 0))
05425       Result = QualType(T, 0);
05426     else
05427       Result = getDerived().RebuildDependentNameType(T->getKeyword(), 
05428                                                      NNS, NewTemplateId);
05429   } else
05430     Result = getDerived().RebuildDependentNameType(T->getKeyword(),
05431                                                    NNS, T->getIdentifier(),
05432                                                   SourceRange(TL.getNameLoc()));
05433 
05434   if (Result.isNull())
05435     return QualType();
05436 
05437   DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
05438   NewTL.setNameLoc(TL.getNameLoc());
05439   return Result;
05440 }
05441 
05442 /// \brief Rebuilds a type within the context of the current instantiation.
05443 ///
05444 /// The type \p T is part of the type of an out-of-line member definition of
05445 /// a class template (or class template partial specialization) that was parsed
05446 /// and constructed before we entered the scope of the class template (or
05447 /// partial specialization thereof). This routine will rebuild that type now
05448 /// that we have entered the declarator's scope, which may produce different
05449 /// canonical types, e.g.,
05450 ///
05451 /// \code
05452 /// template<typename T>
05453 /// struct X {
05454 ///   typedef T* pointer;
05455 ///   pointer data();
05456 /// };
05457 ///
05458 /// template<typename T>
05459 /// typename X<T>::pointer X<T>::data() { ... }
05460 /// \endcode
05461 ///
05462 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
05463 /// since we do not know that we can look into X<T> when we parsed the type.
05464 /// This function will rebuild the type, performing the lookup of "pointer"
05465 /// in X<T> and returning a QualifiedNameType whose canonical type is the same
05466 /// as the canonical type of T*, allowing the return types of the out-of-line
05467 /// definition and the declaration to match.
05468 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
05469                                                         SourceLocation Loc,
05470                                                         DeclarationName Name) {
05471   if (!T || !T->getType()->isDependentType())
05472     return T;
05473 
05474   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
05475   return Rebuilder.TransformType(T);
05476 }
05477 
05478 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
05479   if (SS.isInvalid()) return true;
05480 
05481   NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
05482   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
05483                                           DeclarationName());
05484   NestedNameSpecifier *Rebuilt = 
05485     Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
05486   if (!Rebuilt) return true;
05487 
05488   SS.setScopeRep(Rebuilt);
05489   return false;
05490 }
05491 
05492 /// \brief Produces a formatted string that describes the binding of
05493 /// template parameters to template arguments.
05494 std::string
05495 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
05496                                       const TemplateArgumentList &Args) {
05497   // FIXME: For variadic templates, we'll need to get the structured list.
05498   return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
05499                                          Args.flat_size());
05500 }
05501 
05502 std::string
05503 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
05504                                       const TemplateArgument *Args,
05505                                       unsigned NumArgs) {
05506   std::string Result;
05507 
05508   if (!Params || Params->size() == 0 || NumArgs == 0)
05509     return Result;
05510   
05511   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
05512     if (I >= NumArgs)
05513       break;
05514     
05515     if (I == 0)
05516       Result += "[with ";
05517     else
05518       Result += ", ";
05519     
05520     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
05521       Result += Id->getName();
05522     } else {
05523       Result += '$';
05524       Result += llvm::utostr(I);
05525     }
05526     
05527     Result += " = ";
05528     
05529     switch (Args[I].getKind()) {
05530       case TemplateArgument::Null:
05531         Result += "<no value>";
05532         break;
05533         
05534       case TemplateArgument::Type: {
05535         std::string TypeStr;
05536         Args[I].getAsType().getAsStringInternal(TypeStr, 
05537                                                 Context.PrintingPolicy);
05538         Result += TypeStr;
05539         break;
05540       }
05541         
05542       case TemplateArgument::Declaration: {
05543         bool Unnamed = true;
05544         if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
05545           if (ND->getDeclName()) {
05546             Unnamed = false;
05547             Result += ND->getNameAsString();
05548           }
05549         }
05550         
05551         if (Unnamed) {
05552           Result += "<anonymous>";
05553         }
05554         break;
05555       }
05556         
05557       case TemplateArgument::Template: {
05558         std::string Str;
05559         llvm::raw_string_ostream OS(Str);
05560         Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
05561         Result += OS.str();
05562         break;
05563       }
05564         
05565       case TemplateArgument::Integral: {
05566         Result += Args[I].getAsIntegral()->toString(10);
05567         break;
05568       }
05569         
05570       case TemplateArgument::Expression: {
05571         // FIXME: This is non-optimal, since we're regurgitating the
05572         // expression we were given.
05573         std::string Str; 
05574         {
05575           llvm::raw_string_ostream OS(Str);
05576           Args[I].getAsExpr()->printPretty(OS, Context, 0,
05577                                            Context.PrintingPolicy);
05578         }
05579         Result += Str;
05580         break;
05581       }
05582         
05583       case TemplateArgument::Pack:
05584         // FIXME: Format template argument packs
05585         Result += "<template argument pack>";
05586         break;        
05587     }
05588   }
05589   
05590   Result += ']';
05591   return Result;
05592 }