Home | History | Annotate | Download | only in Sema
      1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //===----------------------------------------------------------------------===/
      8 //
      9 //  This file implements C++ template instantiation for declarations.
     10 //
     11 //===----------------------------------------------------------------------===/
     12 #include "clang/Sema/SemaInternal.h"
     13 #include "clang/Sema/Lookup.h"
     14 #include "clang/Sema/PrettyDeclStackTrace.h"
     15 #include "clang/Sema/Template.h"
     16 #include "clang/AST/ASTConsumer.h"
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/DeclTemplate.h"
     19 #include "clang/AST/DeclVisitor.h"
     20 #include "clang/AST/DependentDiagnostic.h"
     21 #include "clang/AST/Expr.h"
     22 #include "clang/AST/ExprCXX.h"
     23 #include "clang/AST/TypeLoc.h"
     24 #include "clang/Lex/Preprocessor.h"
     25 
     26 using namespace clang;
     27 
     28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
     29                                               DeclaratorDecl *NewDecl) {
     30   if (!OldDecl->getQualifierLoc())
     31     return false;
     32 
     33   NestedNameSpecifierLoc NewQualifierLoc
     34     = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
     35                                           TemplateArgs);
     36 
     37   if (!NewQualifierLoc)
     38     return true;
     39 
     40   NewDecl->setQualifierInfo(NewQualifierLoc);
     41   return false;
     42 }
     43 
     44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
     45                                               TagDecl *NewDecl) {
     46   if (!OldDecl->getQualifierLoc())
     47     return false;
     48 
     49   NestedNameSpecifierLoc NewQualifierLoc
     50   = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
     51                                         TemplateArgs);
     52 
     53   if (!NewQualifierLoc)
     54     return true;
     55 
     56   NewDecl->setQualifierInfo(NewQualifierLoc);
     57   return false;
     58 }
     59 
     60 // Include attribute instantiation code.
     61 #include "clang/Sema/AttrTemplateInstantiate.inc"
     62 
     63 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
     64                             const Decl *Tmpl, Decl *New,
     65                             LateInstantiatedAttrVec *LateAttrs,
     66                             LocalInstantiationScope *OuterMostScope) {
     67   for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
     68        i != e; ++i) {
     69     const Attr *TmplAttr = *i;
     70 
     71     // FIXME: This should be generalized to more than just the AlignedAttr.
     72     if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
     73       if (Aligned->isAlignmentDependent()) {
     74         if (Aligned->isAlignmentExpr()) {
     75           // The alignment expression is a constant expression.
     76           EnterExpressionEvaluationContext Unevaluated(*this,
     77                                                        Sema::ConstantEvaluated);
     78 
     79           ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
     80                                         TemplateArgs);
     81           if (!Result.isInvalid())
     82             AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
     83                            Aligned->getIsMSDeclSpec());
     84         } else {
     85           TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
     86                                              TemplateArgs,
     87                                              Aligned->getLocation(),
     88                                              DeclarationName());
     89           if (Result)
     90             AddAlignedAttr(Aligned->getLocation(), New, Result,
     91                            Aligned->getIsMSDeclSpec());
     92         }
     93         continue;
     94       }
     95     }
     96 
     97     if (TmplAttr->isLateParsed() && LateAttrs) {
     98       // Late parsed attributes must be instantiated and attached after the
     99       // enclosing class has been instantiated.  See Sema::InstantiateClass.
    100       LocalInstantiationScope *Saved = 0;
    101       if (CurrentInstantiationScope)
    102         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
    103       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
    104     } else {
    105       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
    106                                                          *this, TemplateArgs);
    107       if (NewAttr)
    108         New->addAttr(NewAttr);
    109     }
    110   }
    111 }
    112 
    113 Decl *
    114 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
    115   llvm_unreachable("Translation units cannot be instantiated");
    116 }
    117 
    118 Decl *
    119 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
    120   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    121                                       D->getIdentifier());
    122   Owner->addDecl(Inst);
    123   return Inst;
    124 }
    125 
    126 Decl *
    127 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
    128   llvm_unreachable("Namespaces cannot be instantiated");
    129 }
    130 
    131 Decl *
    132 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
    133   NamespaceAliasDecl *Inst
    134     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
    135                                  D->getNamespaceLoc(),
    136                                  D->getAliasLoc(),
    137                                  D->getIdentifier(),
    138                                  D->getQualifierLoc(),
    139                                  D->getTargetNameLoc(),
    140                                  D->getNamespace());
    141   Owner->addDecl(Inst);
    142   return Inst;
    143 }
    144 
    145 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
    146                                                            bool IsTypeAlias) {
    147   bool Invalid = false;
    148   TypeSourceInfo *DI = D->getTypeSourceInfo();
    149   if (DI->getType()->isInstantiationDependentType() ||
    150       DI->getType()->isVariablyModifiedType()) {
    151     DI = SemaRef.SubstType(DI, TemplateArgs,
    152                            D->getLocation(), D->getDeclName());
    153     if (!DI) {
    154       Invalid = true;
    155       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
    156     }
    157   } else {
    158     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
    159   }
    160 
    161   // Create the new typedef
    162   TypedefNameDecl *Typedef;
    163   if (IsTypeAlias)
    164     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
    165                                     D->getLocation(), D->getIdentifier(), DI);
    166   else
    167     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
    168                                   D->getLocation(), D->getIdentifier(), DI);
    169   if (Invalid)
    170     Typedef->setInvalidDecl();
    171 
    172   // If the old typedef was the name for linkage purposes of an anonymous
    173   // tag decl, re-establish that relationship for the new typedef.
    174   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
    175     TagDecl *oldTag = oldTagType->getDecl();
    176     if (oldTag->getTypedefNameForAnonDecl() == D) {
    177       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
    178       assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
    179       newTag->setTypedefNameForAnonDecl(Typedef);
    180     }
    181   }
    182 
    183   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
    184     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
    185                                                        TemplateArgs);
    186     if (!InstPrev)
    187       return 0;
    188 
    189     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
    190 
    191     // If the typedef types are not identical, reject them.
    192     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
    193 
    194     Typedef->setPreviousDeclaration(InstPrevTypedef);
    195   }
    196 
    197   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
    198 
    199   Typedef->setAccess(D->getAccess());
    200 
    201   return Typedef;
    202 }
    203 
    204 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
    205   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
    206   Owner->addDecl(Typedef);
    207   return Typedef;
    208 }
    209 
    210 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
    211   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
    212   Owner->addDecl(Typedef);
    213   return Typedef;
    214 }
    215 
    216 Decl *
    217 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
    218   // Create a local instantiation scope for this type alias template, which
    219   // will contain the instantiations of the template parameters.
    220   LocalInstantiationScope Scope(SemaRef);
    221 
    222   TemplateParameterList *TempParams = D->getTemplateParameters();
    223   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
    224   if (!InstParams)
    225     return 0;
    226 
    227   TypeAliasDecl *Pattern = D->getTemplatedDecl();
    228 
    229   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
    230   if (Pattern->getPreviousDecl()) {
    231     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
    232     if (Found.first != Found.second) {
    233       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
    234     }
    235   }
    236 
    237   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
    238     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
    239   if (!AliasInst)
    240     return 0;
    241 
    242   TypeAliasTemplateDecl *Inst
    243     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    244                                     D->getDeclName(), InstParams, AliasInst);
    245   if (PrevAliasTemplate)
    246     Inst->setPreviousDeclaration(PrevAliasTemplate);
    247 
    248   Inst->setAccess(D->getAccess());
    249 
    250   if (!PrevAliasTemplate)
    251     Inst->setInstantiatedFromMemberTemplate(D);
    252 
    253   Owner->addDecl(Inst);
    254 
    255   return Inst;
    256 }
    257 
    258 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
    259   // If this is the variable for an anonymous struct or union,
    260   // instantiate the anonymous struct/union type first.
    261   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
    262     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
    263       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
    264         return 0;
    265 
    266   // Do substitution on the type of the declaration
    267   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
    268                                          TemplateArgs,
    269                                          D->getTypeSpecStartLoc(),
    270                                          D->getDeclName());
    271   if (!DI)
    272     return 0;
    273 
    274   if (DI->getType()->isFunctionType()) {
    275     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
    276       << D->isStaticDataMember() << DI->getType();
    277     return 0;
    278   }
    279 
    280   // Build the instantiated declaration
    281   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
    282                                  D->getInnerLocStart(),
    283                                  D->getLocation(), D->getIdentifier(),
    284                                  DI->getType(), DI,
    285                                  D->getStorageClass(),
    286                                  D->getStorageClassAsWritten());
    287   Var->setThreadSpecified(D->isThreadSpecified());
    288   Var->setInitStyle(D->getInitStyle());
    289   Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
    290   Var->setConstexpr(D->isConstexpr());
    291 
    292   // Substitute the nested name specifier, if any.
    293   if (SubstQualifier(D, Var))
    294     return 0;
    295 
    296   // If we are instantiating a static data member defined
    297   // out-of-line, the instantiation will have the same lexical
    298   // context (which will be a namespace scope) as the template.
    299   if (D->isOutOfLine())
    300     Var->setLexicalDeclContext(D->getLexicalDeclContext());
    301 
    302   Var->setAccess(D->getAccess());
    303 
    304   if (!D->isStaticDataMember()) {
    305     Var->setUsed(D->isUsed(false));
    306     Var->setReferenced(D->isReferenced());
    307   }
    308 
    309   // FIXME: In theory, we could have a previous declaration for variables that
    310   // are not static data members.
    311   // FIXME: having to fake up a LookupResult is dumb.
    312   LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
    313                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
    314   if (D->isStaticDataMember())
    315     SemaRef.LookupQualifiedName(Previous, Owner, false);
    316 
    317   // In ARC, infer 'retaining' for variables of retainable type.
    318   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
    319       SemaRef.inferObjCARCLifetime(Var))
    320     Var->setInvalidDecl();
    321 
    322   SemaRef.CheckVariableDeclaration(Var, Previous);
    323 
    324   if (D->isOutOfLine()) {
    325     D->getLexicalDeclContext()->addDecl(Var);
    326     Owner->makeDeclVisibleInContext(Var);
    327   } else {
    328     Owner->addDecl(Var);
    329     if (Owner->isFunctionOrMethod())
    330       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
    331   }
    332   SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
    333 
    334   // Link instantiations of static data members back to the template from
    335   // which they were instantiated.
    336   if (Var->isStaticDataMember())
    337     SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
    338                                                      TSK_ImplicitInstantiation);
    339 
    340   if (Var->getAnyInitializer()) {
    341     // We already have an initializer in the class.
    342   } else if (D->getInit()) {
    343     if (Var->isStaticDataMember() && !D->isOutOfLine())
    344       SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
    345     else
    346       SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
    347 
    348     // Instantiate the initializer.
    349     ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
    350                                         D->getInitStyle() == VarDecl::CallInit);
    351     if (!Init.isInvalid()) {
    352       bool TypeMayContainAuto = true;
    353       if (Init.get()) {
    354         bool DirectInit = D->isDirectInit();
    355         SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
    356                                      TypeMayContainAuto);
    357       } else
    358         SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
    359     } else {
    360       // FIXME: Not too happy about invalidating the declaration
    361       // because of a bogus initializer.
    362       Var->setInvalidDecl();
    363     }
    364 
    365     SemaRef.PopExpressionEvaluationContext();
    366   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
    367              !Var->isCXXForRangeDecl())
    368     SemaRef.ActOnUninitializedDecl(Var, false);
    369 
    370   // Diagnose unused local variables with dependent types, where the diagnostic
    371   // will have been deferred.
    372   if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
    373       D->getType()->isDependentType())
    374     SemaRef.DiagnoseUnusedDecl(Var);
    375 
    376   return Var;
    377 }
    378 
    379 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
    380   AccessSpecDecl* AD
    381     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
    382                              D->getAccessSpecifierLoc(), D->getColonLoc());
    383   Owner->addHiddenDecl(AD);
    384   return AD;
    385 }
    386 
    387 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
    388   bool Invalid = false;
    389   TypeSourceInfo *DI = D->getTypeSourceInfo();
    390   if (DI->getType()->isInstantiationDependentType() ||
    391       DI->getType()->isVariablyModifiedType())  {
    392     DI = SemaRef.SubstType(DI, TemplateArgs,
    393                            D->getLocation(), D->getDeclName());
    394     if (!DI) {
    395       DI = D->getTypeSourceInfo();
    396       Invalid = true;
    397     } else if (DI->getType()->isFunctionType()) {
    398       // C++ [temp.arg.type]p3:
    399       //   If a declaration acquires a function type through a type
    400       //   dependent on a template-parameter and this causes a
    401       //   declaration that does not use the syntactic form of a
    402       //   function declarator to have function type, the program is
    403       //   ill-formed.
    404       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
    405         << DI->getType();
    406       Invalid = true;
    407     }
    408   } else {
    409     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
    410   }
    411 
    412   Expr *BitWidth = D->getBitWidth();
    413   if (Invalid)
    414     BitWidth = 0;
    415   else if (BitWidth) {
    416     // The bit-width expression is a constant expression.
    417     EnterExpressionEvaluationContext Unevaluated(SemaRef,
    418                                                  Sema::ConstantEvaluated);
    419 
    420     ExprResult InstantiatedBitWidth
    421       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
    422     if (InstantiatedBitWidth.isInvalid()) {
    423       Invalid = true;
    424       BitWidth = 0;
    425     } else
    426       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
    427   }
    428 
    429   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
    430                                             DI->getType(), DI,
    431                                             cast<RecordDecl>(Owner),
    432                                             D->getLocation(),
    433                                             D->isMutable(),
    434                                             BitWidth,
    435                                             D->getInClassInitStyle(),
    436                                             D->getInnerLocStart(),
    437                                             D->getAccess(),
    438                                             0);
    439   if (!Field) {
    440     cast<Decl>(Owner)->setInvalidDecl();
    441     return 0;
    442   }
    443 
    444   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
    445 
    446   if (Invalid)
    447     Field->setInvalidDecl();
    448 
    449   if (!Field->getDeclName()) {
    450     // Keep track of where this decl came from.
    451     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
    452   }
    453   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
    454     if (Parent->isAnonymousStructOrUnion() &&
    455         Parent->getRedeclContext()->isFunctionOrMethod())
    456       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
    457   }
    458 
    459   Field->setImplicit(D->isImplicit());
    460   Field->setAccess(D->getAccess());
    461   Owner->addDecl(Field);
    462 
    463   return Field;
    464 }
    465 
    466 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
    467   NamedDecl **NamedChain =
    468     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
    469 
    470   int i = 0;
    471   for (IndirectFieldDecl::chain_iterator PI =
    472        D->chain_begin(), PE = D->chain_end();
    473        PI != PE; ++PI) {
    474     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
    475                                               TemplateArgs);
    476     if (!Next)
    477       return 0;
    478 
    479     NamedChain[i++] = Next;
    480   }
    481 
    482   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
    483   IndirectFieldDecl* IndirectField
    484     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    485                                 D->getIdentifier(), T,
    486                                 NamedChain, D->getChainingSize());
    487 
    488 
    489   IndirectField->setImplicit(D->isImplicit());
    490   IndirectField->setAccess(D->getAccess());
    491   Owner->addDecl(IndirectField);
    492   return IndirectField;
    493 }
    494 
    495 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
    496   // Handle friend type expressions by simply substituting template
    497   // parameters into the pattern type and checking the result.
    498   if (TypeSourceInfo *Ty = D->getFriendType()) {
    499     TypeSourceInfo *InstTy;
    500     // If this is an unsupported friend, don't bother substituting template
    501     // arguments into it. The actual type referred to won't be used by any
    502     // parts of Clang, and may not be valid for instantiating. Just use the
    503     // same info for the instantiated friend.
    504     if (D->isUnsupportedFriend()) {
    505       InstTy = Ty;
    506     } else {
    507       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
    508                                  D->getLocation(), DeclarationName());
    509     }
    510     if (!InstTy)
    511       return 0;
    512 
    513     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
    514                                                  D->getFriendLoc(), InstTy);
    515     if (!FD)
    516       return 0;
    517 
    518     FD->setAccess(AS_public);
    519     FD->setUnsupportedFriend(D->isUnsupportedFriend());
    520     Owner->addDecl(FD);
    521     return FD;
    522   }
    523 
    524   NamedDecl *ND = D->getFriendDecl();
    525   assert(ND && "friend decl must be a decl or a type!");
    526 
    527   // All of the Visit implementations for the various potential friend
    528   // declarations have to be carefully written to work for friend
    529   // objects, with the most important detail being that the target
    530   // decl should almost certainly not be placed in Owner.
    531   Decl *NewND = Visit(ND);
    532   if (!NewND) return 0;
    533 
    534   FriendDecl *FD =
    535     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
    536                        cast<NamedDecl>(NewND), D->getFriendLoc());
    537   FD->setAccess(AS_public);
    538   FD->setUnsupportedFriend(D->isUnsupportedFriend());
    539   Owner->addDecl(FD);
    540   return FD;
    541 }
    542 
    543 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
    544   Expr *AssertExpr = D->getAssertExpr();
    545 
    546   // The expression in a static assertion is a constant expression.
    547   EnterExpressionEvaluationContext Unevaluated(SemaRef,
    548                                                Sema::ConstantEvaluated);
    549 
    550   ExprResult InstantiatedAssertExpr
    551     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
    552   if (InstantiatedAssertExpr.isInvalid())
    553     return 0;
    554 
    555   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
    556                                               InstantiatedAssertExpr.get(),
    557                                               D->getMessage(),
    558                                               D->getRParenLoc(),
    559                                               D->isFailed());
    560 }
    561 
    562 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
    563   EnumDecl *PrevDecl = 0;
    564   if (D->getPreviousDecl()) {
    565     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
    566                                                    D->getPreviousDecl(),
    567                                                    TemplateArgs);
    568     if (!Prev) return 0;
    569     PrevDecl = cast<EnumDecl>(Prev);
    570   }
    571 
    572   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
    573                                     D->getLocation(), D->getIdentifier(),
    574                                     PrevDecl, D->isScoped(),
    575                                     D->isScopedUsingClassTag(), D->isFixed());
    576   if (D->isFixed()) {
    577     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
    578       // If we have type source information for the underlying type, it means it
    579       // has been explicitly set by the user. Perform substitution on it before
    580       // moving on.
    581       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
    582       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
    583                                                 DeclarationName());
    584       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
    585         Enum->setIntegerType(SemaRef.Context.IntTy);
    586       else
    587         Enum->setIntegerTypeSourceInfo(NewTI);
    588     } else {
    589       assert(!D->getIntegerType()->isDependentType()
    590              && "Dependent type without type source info");
    591       Enum->setIntegerType(D->getIntegerType());
    592     }
    593   }
    594 
    595   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
    596 
    597   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
    598   Enum->setAccess(D->getAccess());
    599   if (SubstQualifier(D, Enum)) return 0;
    600   Owner->addDecl(Enum);
    601 
    602   EnumDecl *Def = D->getDefinition();
    603   if (Def && Def != D) {
    604     // If this is an out-of-line definition of an enum member template, check
    605     // that the underlying types match in the instantiation of both
    606     // declarations.
    607     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
    608       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
    609       QualType DefnUnderlying =
    610         SemaRef.SubstType(TI->getType(), TemplateArgs,
    611                           UnderlyingLoc, DeclarationName());
    612       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
    613                                      DefnUnderlying, Enum);
    614     }
    615   }
    616 
    617   if (D->getDeclContext()->isFunctionOrMethod())
    618     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
    619 
    620   // C++11 [temp.inst]p1: The implicit instantiation of a class template
    621   // specialization causes the implicit instantiation of the declarations, but
    622   // not the definitions of scoped member enumerations.
    623   // FIXME: There appears to be no wording for what happens for an enum defined
    624   // within a block scope, but we treat that much like a member template. Only
    625   // instantiate the definition when visiting the definition in that case, since
    626   // we will visit all redeclarations.
    627   if (!Enum->isScoped() && Def &&
    628       (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
    629     InstantiateEnumDefinition(Enum, Def);
    630 
    631   return Enum;
    632 }
    633 
    634 void TemplateDeclInstantiator::InstantiateEnumDefinition(
    635     EnumDecl *Enum, EnumDecl *Pattern) {
    636   Enum->startDefinition();
    637 
    638   // Update the location to refer to the definition.
    639   Enum->setLocation(Pattern->getLocation());
    640 
    641   SmallVector<Decl*, 4> Enumerators;
    642 
    643   EnumConstantDecl *LastEnumConst = 0;
    644   for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
    645          ECEnd = Pattern->enumerator_end();
    646        EC != ECEnd; ++EC) {
    647     // The specified value for the enumerator.
    648     ExprResult Value = SemaRef.Owned((Expr *)0);
    649     if (Expr *UninstValue = EC->getInitExpr()) {
    650       // The enumerator's value expression is a constant expression.
    651       EnterExpressionEvaluationContext Unevaluated(SemaRef,
    652                                                    Sema::ConstantEvaluated);
    653 
    654       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
    655     }
    656 
    657     // Drop the initial value and continue.
    658     bool isInvalid = false;
    659     if (Value.isInvalid()) {
    660       Value = SemaRef.Owned((Expr *)0);
    661       isInvalid = true;
    662     }
    663 
    664     EnumConstantDecl *EnumConst
    665       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
    666                                   EC->getLocation(), EC->getIdentifier(),
    667                                   Value.get());
    668 
    669     if (isInvalid) {
    670       if (EnumConst)
    671         EnumConst->setInvalidDecl();
    672       Enum->setInvalidDecl();
    673     }
    674 
    675     if (EnumConst) {
    676       SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
    677 
    678       EnumConst->setAccess(Enum->getAccess());
    679       Enum->addDecl(EnumConst);
    680       Enumerators.push_back(EnumConst);
    681       LastEnumConst = EnumConst;
    682 
    683       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
    684           !Enum->isScoped()) {
    685         // If the enumeration is within a function or method, record the enum
    686         // constant as a local.
    687         SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
    688       }
    689     }
    690   }
    691 
    692   // FIXME: Fixup LBraceLoc
    693   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
    694                         Enum->getRBraceLoc(), Enum,
    695                         Enumerators.data(), Enumerators.size(),
    696                         0, 0);
    697 }
    698 
    699 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
    700   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
    701 }
    702 
    703 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
    704   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
    705 
    706   // Create a local instantiation scope for this class template, which
    707   // will contain the instantiations of the template parameters.
    708   LocalInstantiationScope Scope(SemaRef);
    709   TemplateParameterList *TempParams = D->getTemplateParameters();
    710   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
    711   if (!InstParams)
    712     return NULL;
    713 
    714   CXXRecordDecl *Pattern = D->getTemplatedDecl();
    715 
    716   // Instantiate the qualifier.  We have to do this first in case
    717   // we're a friend declaration, because if we are then we need to put
    718   // the new declaration in the appropriate context.
    719   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
    720   if (QualifierLoc) {
    721     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
    722                                                        TemplateArgs);
    723     if (!QualifierLoc)
    724       return 0;
    725   }
    726 
    727   CXXRecordDecl *PrevDecl = 0;
    728   ClassTemplateDecl *PrevClassTemplate = 0;
    729 
    730   if (!isFriend && Pattern->getPreviousDecl()) {
    731     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
    732     if (Found.first != Found.second) {
    733       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
    734       if (PrevClassTemplate)
    735         PrevDecl = PrevClassTemplate->getTemplatedDecl();
    736     }
    737   }
    738 
    739   // If this isn't a friend, then it's a member template, in which
    740   // case we just want to build the instantiation in the
    741   // specialization.  If it is a friend, we want to build it in
    742   // the appropriate context.
    743   DeclContext *DC = Owner;
    744   if (isFriend) {
    745     if (QualifierLoc) {
    746       CXXScopeSpec SS;
    747       SS.Adopt(QualifierLoc);
    748       DC = SemaRef.computeDeclContext(SS);
    749       if (!DC) return 0;
    750     } else {
    751       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
    752                                            Pattern->getDeclContext(),
    753                                            TemplateArgs);
    754     }
    755 
    756     // Look for a previous declaration of the template in the owning
    757     // context.
    758     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
    759                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
    760     SemaRef.LookupQualifiedName(R, DC);
    761 
    762     if (R.isSingleResult()) {
    763       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
    764       if (PrevClassTemplate)
    765         PrevDecl = PrevClassTemplate->getTemplatedDecl();
    766     }
    767 
    768     if (!PrevClassTemplate && QualifierLoc) {
    769       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
    770         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
    771         << QualifierLoc.getSourceRange();
    772       return 0;
    773     }
    774 
    775     bool AdoptedPreviousTemplateParams = false;
    776     if (PrevClassTemplate) {
    777       bool Complain = true;
    778 
    779       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
    780       // template for struct std::tr1::__detail::_Map_base, where the
    781       // template parameters of the friend declaration don't match the
    782       // template parameters of the original declaration. In this one
    783       // case, we don't complain about the ill-formed friend
    784       // declaration.
    785       if (isFriend && Pattern->getIdentifier() &&
    786           Pattern->getIdentifier()->isStr("_Map_base") &&
    787           DC->isNamespace() &&
    788           cast<NamespaceDecl>(DC)->getIdentifier() &&
    789           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
    790         DeclContext *DCParent = DC->getParent();
    791         if (DCParent->isNamespace() &&
    792             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
    793             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
    794           DeclContext *DCParent2 = DCParent->getParent();
    795           if (DCParent2->isNamespace() &&
    796               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
    797               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
    798               DCParent2->getParent()->isTranslationUnit())
    799             Complain = false;
    800         }
    801       }
    802 
    803       TemplateParameterList *PrevParams
    804         = PrevClassTemplate->getTemplateParameters();
    805 
    806       // Make sure the parameter lists match.
    807       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
    808                                                   Complain,
    809                                                   Sema::TPL_TemplateMatch)) {
    810         if (Complain)
    811           return 0;
    812 
    813         AdoptedPreviousTemplateParams = true;
    814         InstParams = PrevParams;
    815       }
    816 
    817       // Do some additional validation, then merge default arguments
    818       // from the existing declarations.
    819       if (!AdoptedPreviousTemplateParams &&
    820           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
    821                                              Sema::TPC_ClassTemplate))
    822         return 0;
    823     }
    824   }
    825 
    826   CXXRecordDecl *RecordInst
    827     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
    828                             Pattern->getLocStart(), Pattern->getLocation(),
    829                             Pattern->getIdentifier(), PrevDecl,
    830                             /*DelayTypeCreation=*/true);
    831 
    832   if (QualifierLoc)
    833     RecordInst->setQualifierInfo(QualifierLoc);
    834 
    835   ClassTemplateDecl *Inst
    836     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
    837                                 D->getIdentifier(), InstParams, RecordInst,
    838                                 PrevClassTemplate);
    839   RecordInst->setDescribedClassTemplate(Inst);
    840 
    841   if (isFriend) {
    842     if (PrevClassTemplate)
    843       Inst->setAccess(PrevClassTemplate->getAccess());
    844     else
    845       Inst->setAccess(D->getAccess());
    846 
    847     Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
    848     // TODO: do we want to track the instantiation progeny of this
    849     // friend target decl?
    850   } else {
    851     Inst->setAccess(D->getAccess());
    852     if (!PrevClassTemplate)
    853       Inst->setInstantiatedFromMemberTemplate(D);
    854   }
    855 
    856   // Trigger creation of the type for the instantiation.
    857   SemaRef.Context.getInjectedClassNameType(RecordInst,
    858                                     Inst->getInjectedClassNameSpecialization());
    859 
    860   // Finish handling of friends.
    861   if (isFriend) {
    862     DC->makeDeclVisibleInContext(Inst);
    863     Inst->setLexicalDeclContext(Owner);
    864     RecordInst->setLexicalDeclContext(Owner);
    865     return Inst;
    866   }
    867 
    868   if (D->isOutOfLine()) {
    869     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
    870     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
    871   }
    872 
    873   Owner->addDecl(Inst);
    874 
    875   if (!PrevClassTemplate) {
    876     // Queue up any out-of-line partial specializations of this member
    877     // class template; the client will force their instantiation once
    878     // the enclosing class has been instantiated.
    879     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
    880     D->getPartialSpecializations(PartialSpecs);
    881     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
    882       if (PartialSpecs[I]->isOutOfLine())
    883         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
    884   }
    885 
    886   return Inst;
    887 }
    888 
    889 Decl *
    890 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
    891                                    ClassTemplatePartialSpecializationDecl *D) {
    892   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
    893 
    894   // Lookup the already-instantiated declaration in the instantiation
    895   // of the class template and return that.
    896   DeclContext::lookup_result Found
    897     = Owner->lookup(ClassTemplate->getDeclName());
    898   if (Found.first == Found.second)
    899     return 0;
    900 
    901   ClassTemplateDecl *InstClassTemplate
    902     = dyn_cast<ClassTemplateDecl>(*Found.first);
    903   if (!InstClassTemplate)
    904     return 0;
    905 
    906   if (ClassTemplatePartialSpecializationDecl *Result
    907         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
    908     return Result;
    909 
    910   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
    911 }
    912 
    913 Decl *
    914 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
    915   // Create a local instantiation scope for this function template, which
    916   // will contain the instantiations of the template parameters and then get
    917   // merged with the local instantiation scope for the function template
    918   // itself.
    919   LocalInstantiationScope Scope(SemaRef);
    920 
    921   TemplateParameterList *TempParams = D->getTemplateParameters();
    922   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
    923   if (!InstParams)
    924     return NULL;
    925 
    926   FunctionDecl *Instantiated = 0;
    927   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
    928     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
    929                                                                  InstParams));
    930   else
    931     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
    932                                                           D->getTemplatedDecl(),
    933                                                                 InstParams));
    934 
    935   if (!Instantiated)
    936     return 0;
    937 
    938   // Link the instantiated function template declaration to the function
    939   // template from which it was instantiated.
    940   FunctionTemplateDecl *InstTemplate
    941     = Instantiated->getDescribedFunctionTemplate();
    942   InstTemplate->setAccess(D->getAccess());
    943   assert(InstTemplate &&
    944          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
    945 
    946   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
    947 
    948   // Link the instantiation back to the pattern *unless* this is a
    949   // non-definition friend declaration.
    950   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
    951       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
    952     InstTemplate->setInstantiatedFromMemberTemplate(D);
    953 
    954   // Make declarations visible in the appropriate context.
    955   if (!isFriend) {
    956     Owner->addDecl(InstTemplate);
    957   } else if (InstTemplate->getDeclContext()->isRecord() &&
    958              !D->getPreviousDecl()) {
    959     SemaRef.CheckFriendAccess(InstTemplate);
    960   }
    961 
    962   return InstTemplate;
    963 }
    964 
    965 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
    966   CXXRecordDecl *PrevDecl = 0;
    967   if (D->isInjectedClassName())
    968     PrevDecl = cast<CXXRecordDecl>(Owner);
    969   else if (D->getPreviousDecl()) {
    970     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
    971                                                    D->getPreviousDecl(),
    972                                                    TemplateArgs);
    973     if (!Prev) return 0;
    974     PrevDecl = cast<CXXRecordDecl>(Prev);
    975   }
    976 
    977   CXXRecordDecl *Record
    978     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
    979                             D->getLocStart(), D->getLocation(),
    980                             D->getIdentifier(), PrevDecl);
    981 
    982   // Substitute the nested name specifier, if any.
    983   if (SubstQualifier(D, Record))
    984     return 0;
    985 
    986   Record->setImplicit(D->isImplicit());
    987   // FIXME: Check against AS_none is an ugly hack to work around the issue that
    988   // the tag decls introduced by friend class declarations don't have an access
    989   // specifier. Remove once this area of the code gets sorted out.
    990   if (D->getAccess() != AS_none)
    991     Record->setAccess(D->getAccess());
    992   if (!D->isInjectedClassName())
    993     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
    994 
    995   // If the original function was part of a friend declaration,
    996   // inherit its namespace state.
    997   if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
    998     Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
    999 
   1000   // Make sure that anonymous structs and unions are recorded.
   1001   if (D->isAnonymousStructOrUnion()) {
   1002     Record->setAnonymousStructOrUnion(true);
   1003     if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
   1004       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
   1005   }
   1006 
   1007   Owner->addDecl(Record);
   1008   return Record;
   1009 }
   1010 
   1011 /// Normal class members are of more specific types and therefore
   1012 /// don't make it here.  This function serves two purposes:
   1013 ///   1) instantiating function templates
   1014 ///   2) substituting friend declarations
   1015 /// FIXME: preserve function definitions in case #2
   1016 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
   1017                                        TemplateParameterList *TemplateParams) {
   1018   // Check whether there is already a function template specialization for
   1019   // this declaration.
   1020   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
   1021   if (FunctionTemplate && !TemplateParams) {
   1022     std::pair<const TemplateArgument *, unsigned> Innermost
   1023       = TemplateArgs.getInnermost();
   1024 
   1025     void *InsertPos = 0;
   1026     FunctionDecl *SpecFunc
   1027       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
   1028                                              InsertPos);
   1029 
   1030     // If we already have a function template specialization, return it.
   1031     if (SpecFunc)
   1032       return SpecFunc;
   1033   }
   1034 
   1035   bool isFriend;
   1036   if (FunctionTemplate)
   1037     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
   1038   else
   1039     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
   1040 
   1041   bool MergeWithParentScope = (TemplateParams != 0) ||
   1042     Owner->isFunctionOrMethod() ||
   1043     !(isa<Decl>(Owner) &&
   1044       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
   1045   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
   1046 
   1047   SmallVector<ParmVarDecl *, 4> Params;
   1048   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
   1049   if (!TInfo)
   1050     return 0;
   1051   QualType T = TInfo->getType();
   1052 
   1053   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
   1054   if (QualifierLoc) {
   1055     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
   1056                                                        TemplateArgs);
   1057     if (!QualifierLoc)
   1058       return 0;
   1059   }
   1060 
   1061   // If we're instantiating a local function declaration, put the result
   1062   // in the owner;  otherwise we need to find the instantiated context.
   1063   DeclContext *DC;
   1064   if (D->getDeclContext()->isFunctionOrMethod())
   1065     DC = Owner;
   1066   else if (isFriend && QualifierLoc) {
   1067     CXXScopeSpec SS;
   1068     SS.Adopt(QualifierLoc);
   1069     DC = SemaRef.computeDeclContext(SS);
   1070     if (!DC) return 0;
   1071   } else {
   1072     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
   1073                                          TemplateArgs);
   1074   }
   1075 
   1076   FunctionDecl *Function =
   1077       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
   1078                            D->getLocation(), D->getDeclName(), T, TInfo,
   1079                            D->getStorageClass(), D->getStorageClassAsWritten(),
   1080                            D->isInlineSpecified(), D->hasWrittenPrototype(),
   1081                            D->isConstexpr());
   1082 
   1083   if (QualifierLoc)
   1084     Function->setQualifierInfo(QualifierLoc);
   1085 
   1086   DeclContext *LexicalDC = Owner;
   1087   if (!isFriend && D->isOutOfLine()) {
   1088     assert(D->getDeclContext()->isFileContext());
   1089     LexicalDC = D->getDeclContext();
   1090   }
   1091 
   1092   Function->setLexicalDeclContext(LexicalDC);
   1093 
   1094   // Attach the parameters
   1095   if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
   1096     // Adopt the already-instantiated parameters into our own context.
   1097     for (unsigned P = 0; P < Params.size(); ++P)
   1098       if (Params[P])
   1099         Params[P]->setOwningFunction(Function);
   1100   } else {
   1101     // Since we were instantiated via a typedef of a function type, create
   1102     // new parameters.
   1103     const FunctionProtoType *Proto
   1104       = Function->getType()->getAs<FunctionProtoType>();
   1105     assert(Proto && "No function prototype in template instantiation?");
   1106     for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
   1107          AE = Proto->arg_type_end(); AI != AE; ++AI) {
   1108       ParmVarDecl *Param
   1109         = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
   1110                                              *AI);
   1111       Param->setScopeInfo(0, Params.size());
   1112       Params.push_back(Param);
   1113     }
   1114   }
   1115   Function->setParams(Params);
   1116 
   1117   SourceLocation InstantiateAtPOI;
   1118   if (TemplateParams) {
   1119     // Our resulting instantiation is actually a function template, since we
   1120     // are substituting only the outer template parameters. For example, given
   1121     //
   1122     //   template<typename T>
   1123     //   struct X {
   1124     //     template<typename U> friend void f(T, U);
   1125     //   };
   1126     //
   1127     //   X<int> x;
   1128     //
   1129     // We are instantiating the friend function template "f" within X<int>,
   1130     // which means substituting int for T, but leaving "f" as a friend function
   1131     // template.
   1132     // Build the function template itself.
   1133     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
   1134                                                     Function->getLocation(),
   1135                                                     Function->getDeclName(),
   1136                                                     TemplateParams, Function);
   1137     Function->setDescribedFunctionTemplate(FunctionTemplate);
   1138 
   1139     FunctionTemplate->setLexicalDeclContext(LexicalDC);
   1140 
   1141     if (isFriend && D->isThisDeclarationADefinition()) {
   1142       // TODO: should we remember this connection regardless of whether
   1143       // the friend declaration provided a body?
   1144       FunctionTemplate->setInstantiatedFromMemberTemplate(
   1145                                            D->getDescribedFunctionTemplate());
   1146     }
   1147   } else if (FunctionTemplate) {
   1148     // Record this function template specialization.
   1149     std::pair<const TemplateArgument *, unsigned> Innermost
   1150       = TemplateArgs.getInnermost();
   1151     Function->setFunctionTemplateSpecialization(FunctionTemplate,
   1152                             TemplateArgumentList::CreateCopy(SemaRef.Context,
   1153                                                              Innermost.first,
   1154                                                              Innermost.second),
   1155                                                 /*InsertPos=*/0);
   1156   } else if (isFriend) {
   1157     // Note, we need this connection even if the friend doesn't have a body.
   1158     // Its body may exist but not have been attached yet due to deferred
   1159     // parsing.
   1160     // FIXME: It might be cleaner to set this when attaching the body to the
   1161     // friend function declaration, however that would require finding all the
   1162     // instantiations and modifying them.
   1163     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
   1164   }
   1165 
   1166   if (InitFunctionInstantiation(Function, D))
   1167     Function->setInvalidDecl();
   1168 
   1169   bool isExplicitSpecialization = false;
   1170 
   1171   LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
   1172                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
   1173 
   1174   if (DependentFunctionTemplateSpecializationInfo *Info
   1175         = D->getDependentSpecializationInfo()) {
   1176     assert(isFriend && "non-friend has dependent specialization info?");
   1177 
   1178     // This needs to be set now for future sanity.
   1179     Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
   1180 
   1181     // Instantiate the explicit template arguments.
   1182     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
   1183                                           Info->getRAngleLoc());
   1184     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
   1185                       ExplicitArgs, TemplateArgs))
   1186       return 0;
   1187 
   1188     // Map the candidate templates to their instantiations.
   1189     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
   1190       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
   1191                                                 Info->getTemplate(I),
   1192                                                 TemplateArgs);
   1193       if (!Temp) return 0;
   1194 
   1195       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
   1196     }
   1197 
   1198     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
   1199                                                     &ExplicitArgs,
   1200                                                     Previous))
   1201       Function->setInvalidDecl();
   1202 
   1203     isExplicitSpecialization = true;
   1204 
   1205   } else if (TemplateParams || !FunctionTemplate) {
   1206     // Look only into the namespace where the friend would be declared to
   1207     // find a previous declaration. This is the innermost enclosing namespace,
   1208     // as described in ActOnFriendFunctionDecl.
   1209     SemaRef.LookupQualifiedName(Previous, DC);
   1210 
   1211     // In C++, the previous declaration we find might be a tag type
   1212     // (class or enum). In this case, the new declaration will hide the
   1213     // tag type. Note that this does does not apply if we're declaring a
   1214     // typedef (C++ [dcl.typedef]p4).
   1215     if (Previous.isSingleTagDecl())
   1216       Previous.clear();
   1217   }
   1218 
   1219   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
   1220                                    isExplicitSpecialization);
   1221 
   1222   NamedDecl *PrincipalDecl = (TemplateParams
   1223                               ? cast<NamedDecl>(FunctionTemplate)
   1224                               : Function);
   1225 
   1226   // If the original function was part of a friend declaration,
   1227   // inherit its namespace state and add it to the owner.
   1228   if (isFriend) {
   1229     NamedDecl *PrevDecl;
   1230     if (TemplateParams)
   1231       PrevDecl = FunctionTemplate->getPreviousDecl();
   1232     else
   1233       PrevDecl = Function->getPreviousDecl();
   1234 
   1235     PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
   1236     DC->makeDeclVisibleInContext(PrincipalDecl);
   1237 
   1238     bool queuedInstantiation = false;
   1239 
   1240     // C++98 [temp.friend]p5: When a function is defined in a friend function
   1241     //   declaration in a class template, the function is defined at each
   1242     //   instantiation of the class template. The function is defined even if it
   1243     //   is never used.
   1244     // C++11 [temp.friend]p4: When a function is defined in a friend function
   1245     //   declaration in a class template, the function is instantiated when the
   1246     //   function is odr-used.
   1247     //
   1248     // If -Wc++98-compat is enabled, we go through the motions of checking for a
   1249     // redefinition, but don't instantiate the function.
   1250     if ((!SemaRef.getLangOpts().CPlusPlus0x ||
   1251          SemaRef.Diags.getDiagnosticLevel(
   1252              diag::warn_cxx98_compat_friend_redefinition,
   1253              Function->getLocation())
   1254            != DiagnosticsEngine::Ignored) &&
   1255         D->isThisDeclarationADefinition()) {
   1256       // Check for a function body.
   1257       const FunctionDecl *Definition = 0;
   1258       if (Function->isDefined(Definition) &&
   1259           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
   1260         SemaRef.Diag(Function->getLocation(),
   1261                      SemaRef.getLangOpts().CPlusPlus0x ?
   1262                        diag::warn_cxx98_compat_friend_redefinition :
   1263                        diag::err_redefinition) << Function->getDeclName();
   1264         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
   1265         if (!SemaRef.getLangOpts().CPlusPlus0x)
   1266           Function->setInvalidDecl();
   1267       }
   1268       // Check for redefinitions due to other instantiations of this or
   1269       // a similar friend function.
   1270       else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
   1271                                            REnd = Function->redecls_end();
   1272                 R != REnd; ++R) {
   1273         if (*R == Function)
   1274           continue;
   1275         switch (R->getFriendObjectKind()) {
   1276         case Decl::FOK_None:
   1277           if (!SemaRef.getLangOpts().CPlusPlus0x &&
   1278               !queuedInstantiation && R->isUsed(false)) {
   1279             if (MemberSpecializationInfo *MSInfo
   1280                 = Function->getMemberSpecializationInfo()) {
   1281               if (MSInfo->getPointOfInstantiation().isInvalid()) {
   1282                 SourceLocation Loc = R->getLocation(); // FIXME
   1283                 MSInfo->setPointOfInstantiation(Loc);
   1284                 SemaRef.PendingLocalImplicitInstantiations.push_back(
   1285                                                  std::make_pair(Function, Loc));
   1286                 queuedInstantiation = true;
   1287               }
   1288             }
   1289           }
   1290           break;
   1291         default:
   1292           if (const FunctionDecl *RPattern
   1293               = R->getTemplateInstantiationPattern())
   1294             if (RPattern->isDefined(RPattern)) {
   1295               SemaRef.Diag(Function->getLocation(),
   1296                            SemaRef.getLangOpts().CPlusPlus0x ?
   1297                              diag::warn_cxx98_compat_friend_redefinition :
   1298                              diag::err_redefinition)
   1299                 << Function->getDeclName();
   1300               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
   1301               if (!SemaRef.getLangOpts().CPlusPlus0x)
   1302                 Function->setInvalidDecl();
   1303               break;
   1304             }
   1305         }
   1306       }
   1307     }
   1308   }
   1309 
   1310   if (Function->isOverloadedOperator() && !DC->isRecord() &&
   1311       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
   1312     PrincipalDecl->setNonMemberOperator();
   1313 
   1314   assert(!D->isDefaulted() && "only methods should be defaulted");
   1315   return Function;
   1316 }
   1317 
   1318 Decl *
   1319 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
   1320                                       TemplateParameterList *TemplateParams,
   1321                                       bool IsClassScopeSpecialization) {
   1322   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
   1323   if (FunctionTemplate && !TemplateParams) {
   1324     // We are creating a function template specialization from a function
   1325     // template. Check whether there is already a function template
   1326     // specialization for this particular set of template arguments.
   1327     std::pair<const TemplateArgument *, unsigned> Innermost
   1328       = TemplateArgs.getInnermost();
   1329 
   1330     void *InsertPos = 0;
   1331     FunctionDecl *SpecFunc
   1332       = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
   1333                                              InsertPos);
   1334 
   1335     // If we already have a function template specialization, return it.
   1336     if (SpecFunc)
   1337       return SpecFunc;
   1338   }
   1339 
   1340   bool isFriend;
   1341   if (FunctionTemplate)
   1342     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
   1343   else
   1344     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
   1345 
   1346   bool MergeWithParentScope = (TemplateParams != 0) ||
   1347     !(isa<Decl>(Owner) &&
   1348       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
   1349   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
   1350 
   1351   // Instantiate enclosing template arguments for friends.
   1352   SmallVector<TemplateParameterList *, 4> TempParamLists;
   1353   unsigned NumTempParamLists = 0;
   1354   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
   1355     TempParamLists.set_size(NumTempParamLists);
   1356     for (unsigned I = 0; I != NumTempParamLists; ++I) {
   1357       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
   1358       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
   1359       if (!InstParams)
   1360         return NULL;
   1361       TempParamLists[I] = InstParams;
   1362     }
   1363   }
   1364 
   1365   SmallVector<ParmVarDecl *, 4> Params;
   1366   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
   1367   if (!TInfo)
   1368     return 0;
   1369   QualType T = TInfo->getType();
   1370 
   1371   // \brief If the type of this function, after ignoring parentheses,
   1372   // is not *directly* a function type, then we're instantiating a function
   1373   // that was declared via a typedef, e.g.,
   1374   //
   1375   //   typedef int functype(int, int);
   1376   //   functype func;
   1377   //
   1378   // In this case, we'll just go instantiate the ParmVarDecls that we
   1379   // synthesized in the method declaration.
   1380   if (!isa<FunctionProtoType>(T.IgnoreParens())) {
   1381     assert(!Params.size() && "Instantiating type could not yield parameters");
   1382     SmallVector<QualType, 4> ParamTypes;
   1383     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
   1384                                D->getNumParams(), TemplateArgs, ParamTypes,
   1385                                &Params))
   1386       return 0;
   1387   }
   1388 
   1389   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
   1390   if (QualifierLoc) {
   1391     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
   1392                                                  TemplateArgs);
   1393     if (!QualifierLoc)
   1394       return 0;
   1395   }
   1396 
   1397   DeclContext *DC = Owner;
   1398   if (isFriend) {
   1399     if (QualifierLoc) {
   1400       CXXScopeSpec SS;
   1401       SS.Adopt(QualifierLoc);
   1402       DC = SemaRef.computeDeclContext(SS);
   1403 
   1404       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
   1405         return 0;
   1406     } else {
   1407       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
   1408                                            D->getDeclContext(),
   1409                                            TemplateArgs);
   1410     }
   1411     if (!DC) return 0;
   1412   }
   1413 
   1414   // Build the instantiated method declaration.
   1415   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
   1416   CXXMethodDecl *Method = 0;
   1417 
   1418   SourceLocation StartLoc = D->getInnerLocStart();
   1419   DeclarationNameInfo NameInfo
   1420     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
   1421   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
   1422     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
   1423                                         StartLoc, NameInfo, T, TInfo,
   1424                                         Constructor->isExplicit(),
   1425                                         Constructor->isInlineSpecified(),
   1426                                         false, Constructor->isConstexpr());
   1427   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
   1428     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
   1429                                        StartLoc, NameInfo, T, TInfo,
   1430                                        Destructor->isInlineSpecified(),
   1431                                        false);
   1432   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
   1433     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
   1434                                        StartLoc, NameInfo, T, TInfo,
   1435                                        Conversion->isInlineSpecified(),
   1436                                        Conversion->isExplicit(),
   1437                                        Conversion->isConstexpr(),
   1438                                        Conversion->getLocEnd());
   1439   } else {
   1440     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
   1441                                    StartLoc, NameInfo, T, TInfo,
   1442                                    D->isStatic(),
   1443                                    D->getStorageClassAsWritten(),
   1444                                    D->isInlineSpecified(),
   1445                                    D->isConstexpr(), D->getLocEnd());
   1446   }
   1447 
   1448   if (QualifierLoc)
   1449     Method->setQualifierInfo(QualifierLoc);
   1450 
   1451   if (TemplateParams) {
   1452     // Our resulting instantiation is actually a function template, since we
   1453     // are substituting only the outer template parameters. For example, given
   1454     //
   1455     //   template<typename T>
   1456     //   struct X {
   1457     //     template<typename U> void f(T, U);
   1458     //   };
   1459     //
   1460     //   X<int> x;
   1461     //
   1462     // We are instantiating the member template "f" within X<int>, which means
   1463     // substituting int for T, but leaving "f" as a member function template.
   1464     // Build the function template itself.
   1465     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
   1466                                                     Method->getLocation(),
   1467                                                     Method->getDeclName(),
   1468                                                     TemplateParams, Method);
   1469     if (isFriend) {
   1470       FunctionTemplate->setLexicalDeclContext(Owner);
   1471       FunctionTemplate->setObjectOfFriendDecl(true);
   1472     } else if (D->isOutOfLine())
   1473       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
   1474     Method->setDescribedFunctionTemplate(FunctionTemplate);
   1475   } else if (FunctionTemplate) {
   1476     // Record this function template specialization.
   1477     std::pair<const TemplateArgument *, unsigned> Innermost
   1478       = TemplateArgs.getInnermost();
   1479     Method->setFunctionTemplateSpecialization(FunctionTemplate,
   1480                          TemplateArgumentList::CreateCopy(SemaRef.Context,
   1481                                                           Innermost.first,
   1482                                                           Innermost.second),
   1483                                               /*InsertPos=*/0);
   1484   } else if (!isFriend) {
   1485     // Record that this is an instantiation of a member function.
   1486     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
   1487   }
   1488 
   1489   // If we are instantiating a member function defined
   1490   // out-of-line, the instantiation will have the same lexical
   1491   // context (which will be a namespace scope) as the template.
   1492   if (isFriend) {
   1493     if (NumTempParamLists)
   1494       Method->setTemplateParameterListsInfo(SemaRef.Context,
   1495                                             NumTempParamLists,
   1496                                             TempParamLists.data());
   1497 
   1498     Method->setLexicalDeclContext(Owner);
   1499     Method->setObjectOfFriendDecl(true);
   1500   } else if (D->isOutOfLine())
   1501     Method->setLexicalDeclContext(D->getLexicalDeclContext());
   1502 
   1503   // Attach the parameters
   1504   for (unsigned P = 0; P < Params.size(); ++P)
   1505     Params[P]->setOwningFunction(Method);
   1506   Method->setParams(Params);
   1507 
   1508   if (InitMethodInstantiation(Method, D))
   1509     Method->setInvalidDecl();
   1510 
   1511   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
   1512                         Sema::ForRedeclaration);
   1513 
   1514   if (!FunctionTemplate || TemplateParams || isFriend) {
   1515     SemaRef.LookupQualifiedName(Previous, Record);
   1516 
   1517     // In C++, the previous declaration we find might be a tag type
   1518     // (class or enum). In this case, the new declaration will hide the
   1519     // tag type. Note that this does does not apply if we're declaring a
   1520     // typedef (C++ [dcl.typedef]p4).
   1521     if (Previous.isSingleTagDecl())
   1522       Previous.clear();
   1523   }
   1524 
   1525   if (!IsClassScopeSpecialization)
   1526     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
   1527 
   1528   if (D->isPure())
   1529     SemaRef.CheckPureMethod(Method, SourceRange());
   1530 
   1531   // Propagate access.  For a non-friend declaration, the access is
   1532   // whatever we're propagating from.  For a friend, it should be the
   1533   // previous declaration we just found.
   1534   if (isFriend && Method->getPreviousDecl())
   1535     Method->setAccess(Method->getPreviousDecl()->getAccess());
   1536   else
   1537     Method->setAccess(D->getAccess());
   1538   if (FunctionTemplate)
   1539     FunctionTemplate->setAccess(Method->getAccess());
   1540 
   1541   SemaRef.CheckOverrideControl(Method);
   1542 
   1543   // If a function is defined as defaulted or deleted, mark it as such now.
   1544   if (D->isDefaulted())
   1545     Method->setDefaulted();
   1546   if (D->isDeletedAsWritten())
   1547     Method->setDeletedAsWritten();
   1548 
   1549   // If there's a function template, let our caller handle it.
   1550   if (FunctionTemplate) {
   1551     // do nothing
   1552 
   1553   // Don't hide a (potentially) valid declaration with an invalid one.
   1554   } else if (Method->isInvalidDecl() && !Previous.empty()) {
   1555     // do nothing
   1556 
   1557   // Otherwise, check access to friends and make them visible.
   1558   } else if (isFriend) {
   1559     // We only need to re-check access for methods which we didn't
   1560     // manage to match during parsing.
   1561     if (!D->getPreviousDecl())
   1562       SemaRef.CheckFriendAccess(Method);
   1563 
   1564     Record->makeDeclVisibleInContext(Method);
   1565 
   1566   // Otherwise, add the declaration.  We don't need to do this for
   1567   // class-scope specializations because we'll have matched them with
   1568   // the appropriate template.
   1569   } else if (!IsClassScopeSpecialization) {
   1570     Owner->addDecl(Method);
   1571   }
   1572 
   1573   if (D->isExplicitlyDefaulted()) {
   1574     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
   1575   } else {
   1576     assert(!D->isDefaulted() &&
   1577            "should not implicitly default uninstantiated function");
   1578   }
   1579 
   1580   return Method;
   1581 }
   1582 
   1583 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
   1584   return VisitCXXMethodDecl(D);
   1585 }
   1586 
   1587 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
   1588   return VisitCXXMethodDecl(D);
   1589 }
   1590 
   1591 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
   1592   return VisitCXXMethodDecl(D);
   1593 }
   1594 
   1595 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
   1596   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
   1597                                   llvm::Optional<unsigned>(),
   1598                                   /*ExpectParameterPack=*/false);
   1599 }
   1600 
   1601 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
   1602                                                     TemplateTypeParmDecl *D) {
   1603   // TODO: don't always clone when decls are refcounted.
   1604   assert(D->getTypeForDecl()->isTemplateTypeParmType());
   1605 
   1606   TemplateTypeParmDecl *Inst =
   1607     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
   1608                                  D->getLocStart(), D->getLocation(),
   1609                                  D->getDepth() - TemplateArgs.getNumLevels(),
   1610                                  D->getIndex(), D->getIdentifier(),
   1611                                  D->wasDeclaredWithTypename(),
   1612                                  D->isParameterPack());
   1613   Inst->setAccess(AS_public);
   1614 
   1615   if (D->hasDefaultArgument())
   1616     Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
   1617 
   1618   // Introduce this template parameter's instantiation into the instantiation
   1619   // scope.
   1620   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
   1621 
   1622   return Inst;
   1623 }
   1624 
   1625 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
   1626                                                  NonTypeTemplateParmDecl *D) {
   1627   // Substitute into the type of the non-type template parameter.
   1628   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
   1629   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
   1630   SmallVector<QualType, 4> ExpandedParameterPackTypes;
   1631   bool IsExpandedParameterPack = false;
   1632   TypeSourceInfo *DI;
   1633   QualType T;
   1634   bool Invalid = false;
   1635 
   1636   if (D->isExpandedParameterPack()) {
   1637     // The non-type template parameter pack is an already-expanded pack
   1638     // expansion of types. Substitute into each of the expanded types.
   1639     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
   1640     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
   1641     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
   1642       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
   1643                                                TemplateArgs,
   1644                                                D->getLocation(),
   1645                                                D->getDeclName());
   1646       if (!NewDI)
   1647         return 0;
   1648 
   1649       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
   1650       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
   1651                                                               D->getLocation());
   1652       if (NewT.isNull())
   1653         return 0;
   1654       ExpandedParameterPackTypes.push_back(NewT);
   1655     }
   1656 
   1657     IsExpandedParameterPack = true;
   1658     DI = D->getTypeSourceInfo();
   1659     T = DI->getType();
   1660   } else if (D->isPackExpansion()) {
   1661     // The non-type template parameter pack's type is a pack expansion of types.
   1662     // Determine whether we need to expand this parameter pack into separate
   1663     // types.
   1664     PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
   1665     TypeLoc Pattern = Expansion.getPatternLoc();
   1666     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   1667     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
   1668 
   1669     // Determine whether the set of unexpanded parameter packs can and should
   1670     // be expanded.
   1671     bool Expand = true;
   1672     bool RetainExpansion = false;
   1673     llvm::Optional<unsigned> OrigNumExpansions
   1674       = Expansion.getTypePtr()->getNumExpansions();
   1675     llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
   1676     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
   1677                                                 Pattern.getSourceRange(),
   1678                                                 Unexpanded,
   1679                                                 TemplateArgs,
   1680                                                 Expand, RetainExpansion,
   1681                                                 NumExpansions))
   1682       return 0;
   1683 
   1684     if (Expand) {
   1685       for (unsigned I = 0; I != *NumExpansions; ++I) {
   1686         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
   1687         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
   1688                                                   D->getLocation(),
   1689                                                   D->getDeclName());
   1690         if (!NewDI)
   1691           return 0;
   1692 
   1693         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
   1694         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
   1695                                                               NewDI->getType(),
   1696                                                               D->getLocation());
   1697         if (NewT.isNull())
   1698           return 0;
   1699         ExpandedParameterPackTypes.push_back(NewT);
   1700       }
   1701 
   1702       // Note that we have an expanded parameter pack. The "type" of this
   1703       // expanded parameter pack is the original expansion type, but callers
   1704       // will end up using the expanded parameter pack types for type-checking.
   1705       IsExpandedParameterPack = true;
   1706       DI = D->getTypeSourceInfo();
   1707       T = DI->getType();
   1708     } else {
   1709       // We cannot fully expand the pack expansion now, so substitute into the
   1710       // pattern and create a new pack expansion type.
   1711       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
   1712       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
   1713                                                      D->getLocation(),
   1714                                                      D->getDeclName());
   1715       if (!NewPattern)
   1716         return 0;
   1717 
   1718       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
   1719                                       NumExpansions);
   1720       if (!DI)
   1721         return 0;
   1722 
   1723       T = DI->getType();
   1724     }
   1725   } else {
   1726     // Simple case: substitution into a parameter that is not a parameter pack.
   1727     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
   1728                            D->getLocation(), D->getDeclName());
   1729     if (!DI)
   1730       return 0;
   1731 
   1732     // Check that this type is acceptable for a non-type template parameter.
   1733     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
   1734                                                   D->getLocation());
   1735     if (T.isNull()) {
   1736       T = SemaRef.Context.IntTy;
   1737       Invalid = true;
   1738     }
   1739   }
   1740 
   1741   NonTypeTemplateParmDecl *Param;
   1742   if (IsExpandedParameterPack)
   1743     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
   1744                                             D->getInnerLocStart(),
   1745                                             D->getLocation(),
   1746                                     D->getDepth() - TemplateArgs.getNumLevels(),
   1747                                             D->getPosition(),
   1748                                             D->getIdentifier(), T,
   1749                                             DI,
   1750                                             ExpandedParameterPackTypes.data(),
   1751                                             ExpandedParameterPackTypes.size(),
   1752                                     ExpandedParameterPackTypesAsWritten.data());
   1753   else
   1754     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
   1755                                             D->getInnerLocStart(),
   1756                                             D->getLocation(),
   1757                                     D->getDepth() - TemplateArgs.getNumLevels(),
   1758                                             D->getPosition(),
   1759                                             D->getIdentifier(), T,
   1760                                             D->isParameterPack(), DI);
   1761 
   1762   Param->setAccess(AS_public);
   1763   if (Invalid)
   1764     Param->setInvalidDecl();
   1765 
   1766   Param->setDefaultArgument(D->getDefaultArgument(), false);
   1767 
   1768   // Introduce this template parameter's instantiation into the instantiation
   1769   // scope.
   1770   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
   1771   return Param;
   1772 }
   1773 
   1774 static void collectUnexpandedParameterPacks(
   1775     Sema &S,
   1776     TemplateParameterList *Params,
   1777     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
   1778   for (TemplateParameterList::const_iterator I = Params->begin(),
   1779                                              E = Params->end(); I != E; ++I) {
   1780     if ((*I)->isTemplateParameterPack())
   1781       continue;
   1782     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
   1783       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
   1784                                         Unexpanded);
   1785     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
   1786       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
   1787                                       Unexpanded);
   1788   }
   1789 }
   1790 
   1791 Decl *
   1792 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
   1793                                                   TemplateTemplateParmDecl *D) {
   1794   // Instantiate the template parameter list of the template template parameter.
   1795   TemplateParameterList *TempParams = D->getTemplateParameters();
   1796   TemplateParameterList *InstParams;
   1797   SmallVector<TemplateParameterList*, 8> ExpandedParams;
   1798 
   1799   bool IsExpandedParameterPack = false;
   1800 
   1801   if (D->isExpandedParameterPack()) {
   1802     // The template template parameter pack is an already-expanded pack
   1803     // expansion of template parameters. Substitute into each of the expanded
   1804     // parameters.
   1805     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
   1806     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
   1807          I != N; ++I) {
   1808       LocalInstantiationScope Scope(SemaRef);
   1809       TemplateParameterList *Expansion =
   1810         SubstTemplateParams(D->getExpansionTemplateParameters(I));
   1811       if (!Expansion)
   1812         return 0;
   1813       ExpandedParams.push_back(Expansion);
   1814     }
   1815 
   1816     IsExpandedParameterPack = true;
   1817     InstParams = TempParams;
   1818   } else if (D->isPackExpansion()) {
   1819     // The template template parameter pack expands to a pack of template
   1820     // template parameters. Determine whether we need to expand this parameter
   1821     // pack into separate parameters.
   1822     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   1823     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
   1824                                     Unexpanded);
   1825 
   1826     // Determine whether the set of unexpanded parameter packs can and should
   1827     // be expanded.
   1828     bool Expand = true;
   1829     bool RetainExpansion = false;
   1830     llvm::Optional<unsigned> NumExpansions;
   1831     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
   1832                                                 TempParams->getSourceRange(),
   1833                                                 Unexpanded,
   1834                                                 TemplateArgs,
   1835                                                 Expand, RetainExpansion,
   1836                                                 NumExpansions))
   1837       return 0;
   1838 
   1839     if (Expand) {
   1840       for (unsigned I = 0; I != *NumExpansions; ++I) {
   1841         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
   1842         LocalInstantiationScope Scope(SemaRef);
   1843         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
   1844         if (!Expansion)
   1845           return 0;
   1846         ExpandedParams.push_back(Expansion);
   1847       }
   1848 
   1849       // Note that we have an expanded parameter pack. The "type" of this
   1850       // expanded parameter pack is the original expansion type, but callers
   1851       // will end up using the expanded parameter pack types for type-checking.
   1852       IsExpandedParameterPack = true;
   1853       InstParams = TempParams;
   1854     } else {
   1855       // We cannot fully expand the pack expansion now, so just substitute
   1856       // into the pattern.
   1857       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
   1858 
   1859       LocalInstantiationScope Scope(SemaRef);
   1860       InstParams = SubstTemplateParams(TempParams);
   1861       if (!InstParams)
   1862         return 0;
   1863     }
   1864   } else {
   1865     // Perform the actual substitution of template parameters within a new,
   1866     // local instantiation scope.
   1867     LocalInstantiationScope Scope(SemaRef);
   1868     InstParams = SubstTemplateParams(TempParams);
   1869     if (!InstParams)
   1870       return 0;
   1871   }
   1872 
   1873   // Build the template template parameter.
   1874   TemplateTemplateParmDecl *Param;
   1875   if (IsExpandedParameterPack)
   1876     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
   1877                                              D->getLocation(),
   1878                                    D->getDepth() - TemplateArgs.getNumLevels(),
   1879                                              D->getPosition(),
   1880                                              D->getIdentifier(), InstParams,
   1881                                              ExpandedParams);
   1882   else
   1883     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
   1884                                              D->getLocation(),
   1885                                    D->getDepth() - TemplateArgs.getNumLevels(),
   1886                                              D->getPosition(),
   1887                                              D->isParameterPack(),
   1888                                              D->getIdentifier(), InstParams);
   1889   Param->setDefaultArgument(D->getDefaultArgument(), false);
   1890   Param->setAccess(AS_public);
   1891 
   1892   // Introduce this template parameter's instantiation into the instantiation
   1893   // scope.
   1894   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
   1895 
   1896   return Param;
   1897 }
   1898 
   1899 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
   1900   // Using directives are never dependent (and never contain any types or
   1901   // expressions), so they require no explicit instantiation work.
   1902 
   1903   UsingDirectiveDecl *Inst
   1904     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
   1905                                  D->getNamespaceKeyLocation(),
   1906                                  D->getQualifierLoc(),
   1907                                  D->getIdentLocation(),
   1908                                  D->getNominatedNamespace(),
   1909                                  D->getCommonAncestor());
   1910 
   1911   // Add the using directive to its declaration context
   1912   // only if this is not a function or method.
   1913   if (!Owner->isFunctionOrMethod())
   1914     Owner->addDecl(Inst);
   1915 
   1916   return Inst;
   1917 }
   1918 
   1919 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
   1920 
   1921   // The nested name specifier may be dependent, for example
   1922   //     template <typename T> struct t {
   1923   //       struct s1 { T f1(); };
   1924   //       struct s2 : s1 { using s1::f1; };
   1925   //     };
   1926   //     template struct t<int>;
   1927   // Here, in using s1::f1, s1 refers to t<T>::s1;
   1928   // we need to substitute for t<int>::s1.
   1929   NestedNameSpecifierLoc QualifierLoc
   1930     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
   1931                                           TemplateArgs);
   1932   if (!QualifierLoc)
   1933     return 0;
   1934 
   1935   // The name info is non-dependent, so no transformation
   1936   // is required.
   1937   DeclarationNameInfo NameInfo = D->getNameInfo();
   1938 
   1939   // We only need to do redeclaration lookups if we're in a class
   1940   // scope (in fact, it's not really even possible in non-class
   1941   // scopes).
   1942   bool CheckRedeclaration = Owner->isRecord();
   1943 
   1944   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
   1945                     Sema::ForRedeclaration);
   1946 
   1947   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
   1948                                        D->getUsingLocation(),
   1949                                        QualifierLoc,
   1950                                        NameInfo,
   1951                                        D->isTypeName());
   1952 
   1953   CXXScopeSpec SS;
   1954   SS.Adopt(QualifierLoc);
   1955   if (CheckRedeclaration) {
   1956     Prev.setHideTags(false);
   1957     SemaRef.LookupQualifiedName(Prev, Owner);
   1958 
   1959     // Check for invalid redeclarations.
   1960     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
   1961                                             D->isTypeName(), SS,
   1962                                             D->getLocation(), Prev))
   1963       NewUD->setInvalidDecl();
   1964 
   1965   }
   1966 
   1967   if (!NewUD->isInvalidDecl() &&
   1968       SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
   1969                                       D->getLocation()))
   1970     NewUD->setInvalidDecl();
   1971 
   1972   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
   1973   NewUD->setAccess(D->getAccess());
   1974   Owner->addDecl(NewUD);
   1975 
   1976   // Don't process the shadow decls for an invalid decl.
   1977   if (NewUD->isInvalidDecl())
   1978     return NewUD;
   1979 
   1980   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
   1981     if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
   1982       NewUD->setInvalidDecl();
   1983     return NewUD;
   1984   }
   1985 
   1986   bool isFunctionScope = Owner->isFunctionOrMethod();
   1987 
   1988   // Process the shadow decls.
   1989   for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
   1990          I != E; ++I) {
   1991     UsingShadowDecl *Shadow = *I;
   1992     NamedDecl *InstTarget =
   1993       cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
   1994                                                           Shadow->getLocation(),
   1995                                                         Shadow->getTargetDecl(),
   1996                                                            TemplateArgs));
   1997     if (!InstTarget)
   1998       return 0;
   1999 
   2000     if (CheckRedeclaration &&
   2001         SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
   2002       continue;
   2003 
   2004     UsingShadowDecl *InstShadow
   2005       = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
   2006     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
   2007 
   2008     if (isFunctionScope)
   2009       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
   2010   }
   2011 
   2012   return NewUD;
   2013 }
   2014 
   2015 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
   2016   // Ignore these;  we handle them in bulk when processing the UsingDecl.
   2017   return 0;
   2018 }
   2019 
   2020 Decl * TemplateDeclInstantiator
   2021     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
   2022   NestedNameSpecifierLoc QualifierLoc
   2023     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
   2024                                           TemplateArgs);
   2025   if (!QualifierLoc)
   2026     return 0;
   2027 
   2028   CXXScopeSpec SS;
   2029   SS.Adopt(QualifierLoc);
   2030 
   2031   // Since NameInfo refers to a typename, it cannot be a C++ special name.
   2032   // Hence, no tranformation is required for it.
   2033   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
   2034   NamedDecl *UD =
   2035     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
   2036                                   D->getUsingLoc(), SS, NameInfo, 0,
   2037                                   /*instantiation*/ true,
   2038                                   /*typename*/ true, D->getTypenameLoc());
   2039   if (UD)
   2040     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
   2041 
   2042   return UD;
   2043 }
   2044 
   2045 Decl * TemplateDeclInstantiator
   2046     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
   2047   NestedNameSpecifierLoc QualifierLoc
   2048       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
   2049   if (!QualifierLoc)
   2050     return 0;
   2051 
   2052   CXXScopeSpec SS;
   2053   SS.Adopt(QualifierLoc);
   2054 
   2055   DeclarationNameInfo NameInfo
   2056     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
   2057 
   2058   NamedDecl *UD =
   2059     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
   2060                                   D->getUsingLoc(), SS, NameInfo, 0,
   2061                                   /*instantiation*/ true,
   2062                                   /*typename*/ false, SourceLocation());
   2063   if (UD)
   2064     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
   2065 
   2066   return UD;
   2067 }
   2068 
   2069 
   2070 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
   2071                                      ClassScopeFunctionSpecializationDecl *Decl) {
   2072   CXXMethodDecl *OldFD = Decl->getSpecialization();
   2073   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
   2074                                                                 0, true));
   2075 
   2076   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
   2077                         Sema::ForRedeclaration);
   2078 
   2079   TemplateArgumentListInfo TemplateArgs;
   2080   TemplateArgumentListInfo* TemplateArgsPtr = 0;
   2081   if (Decl->hasExplicitTemplateArgs()) {
   2082     TemplateArgs = Decl->templateArgs();
   2083     TemplateArgsPtr = &TemplateArgs;
   2084   }
   2085 
   2086   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
   2087   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
   2088                                                   Previous)) {
   2089     NewFD->setInvalidDecl();
   2090     return NewFD;
   2091   }
   2092 
   2093   // Associate the specialization with the pattern.
   2094   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
   2095   assert(Specialization && "Class scope Specialization is null");
   2096   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
   2097 
   2098   return NewFD;
   2099 }
   2100 
   2101 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
   2102                       const MultiLevelTemplateArgumentList &TemplateArgs) {
   2103   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
   2104   if (D->isInvalidDecl())
   2105     return 0;
   2106 
   2107   return Instantiator.Visit(D);
   2108 }
   2109 
   2110 /// \brief Instantiates a nested template parameter list in the current
   2111 /// instantiation context.
   2112 ///
   2113 /// \param L The parameter list to instantiate
   2114 ///
   2115 /// \returns NULL if there was an error
   2116 TemplateParameterList *
   2117 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
   2118   // Get errors for all the parameters before bailing out.
   2119   bool Invalid = false;
   2120 
   2121   unsigned N = L->size();
   2122   typedef SmallVector<NamedDecl *, 8> ParamVector;
   2123   ParamVector Params;
   2124   Params.reserve(N);
   2125   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
   2126        PI != PE; ++PI) {
   2127     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
   2128     Params.push_back(D);
   2129     Invalid = Invalid || !D || D->isInvalidDecl();
   2130   }
   2131 
   2132   // Clean up if we had an error.
   2133   if (Invalid)
   2134     return NULL;
   2135 
   2136   TemplateParameterList *InstL
   2137     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
   2138                                     L->getLAngleLoc(), &Params.front(), N,
   2139                                     L->getRAngleLoc());
   2140   return InstL;
   2141 }
   2142 
   2143 /// \brief Instantiate the declaration of a class template partial
   2144 /// specialization.
   2145 ///
   2146 /// \param ClassTemplate the (instantiated) class template that is partially
   2147 // specialized by the instantiation of \p PartialSpec.
   2148 ///
   2149 /// \param PartialSpec the (uninstantiated) class template partial
   2150 /// specialization that we are instantiating.
   2151 ///
   2152 /// \returns The instantiated partial specialization, if successful; otherwise,
   2153 /// NULL to indicate an error.
   2154 ClassTemplatePartialSpecializationDecl *
   2155 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
   2156                                             ClassTemplateDecl *ClassTemplate,
   2157                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
   2158   // Create a local instantiation scope for this class template partial
   2159   // specialization, which will contain the instantiations of the template
   2160   // parameters.
   2161   LocalInstantiationScope Scope(SemaRef);
   2162 
   2163   // Substitute into the template parameters of the class template partial
   2164   // specialization.
   2165   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
   2166   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
   2167   if (!InstParams)
   2168     return 0;
   2169 
   2170   // Substitute into the template arguments of the class template partial
   2171   // specialization.
   2172   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
   2173   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
   2174                     PartialSpec->getNumTemplateArgsAsWritten(),
   2175                     InstTemplateArgs, TemplateArgs))
   2176     return 0;
   2177 
   2178   // Check that the template argument list is well-formed for this
   2179   // class template.
   2180   SmallVector<TemplateArgument, 4> Converted;
   2181   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
   2182                                         PartialSpec->getLocation(),
   2183                                         InstTemplateArgs,
   2184                                         false,
   2185                                         Converted))
   2186     return 0;
   2187 
   2188   // Figure out where to insert this class template partial specialization
   2189   // in the member template's set of class template partial specializations.
   2190   void *InsertPos = 0;
   2191   ClassTemplateSpecializationDecl *PrevDecl
   2192     = ClassTemplate->findPartialSpecialization(Converted.data(),
   2193                                                Converted.size(), InsertPos);
   2194 
   2195   // Build the canonical type that describes the converted template
   2196   // arguments of the class template partial specialization.
   2197   QualType CanonType
   2198     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
   2199                                                     Converted.data(),
   2200                                                     Converted.size());
   2201 
   2202   // Build the fully-sugared type for this class template
   2203   // specialization as the user wrote in the specialization
   2204   // itself. This means that we'll pretty-print the type retrieved
   2205   // from the specialization's declaration the way that the user
   2206   // actually wrote the specialization, rather than formatting the
   2207   // name based on the "canonical" representation used to store the
   2208   // template arguments in the specialization.
   2209   TypeSourceInfo *WrittenTy
   2210     = SemaRef.Context.getTemplateSpecializationTypeInfo(
   2211                                                     TemplateName(ClassTemplate),
   2212                                                     PartialSpec->getLocation(),
   2213                                                     InstTemplateArgs,
   2214                                                     CanonType);
   2215 
   2216   if (PrevDecl) {
   2217     // We've already seen a partial specialization with the same template
   2218     // parameters and template arguments. This can happen, for example, when
   2219     // substituting the outer template arguments ends up causing two
   2220     // class template partial specializations of a member class template
   2221     // to have identical forms, e.g.,
   2222     //
   2223     //   template<typename T, typename U>
   2224     //   struct Outer {
   2225     //     template<typename X, typename Y> struct Inner;
   2226     //     template<typename Y> struct Inner<T, Y>;
   2227     //     template<typename Y> struct Inner<U, Y>;
   2228     //   };
   2229     //
   2230     //   Outer<int, int> outer; // error: the partial specializations of Inner
   2231     //                          // have the same signature.
   2232     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
   2233       << WrittenTy->getType();
   2234     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
   2235       << SemaRef.Context.getTypeDeclType(PrevDecl);
   2236     return 0;
   2237   }
   2238 
   2239 
   2240   // Create the class template partial specialization declaration.
   2241   ClassTemplatePartialSpecializationDecl *InstPartialSpec
   2242     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
   2243                                                      PartialSpec->getTagKind(),
   2244                                                      Owner,
   2245                                                      PartialSpec->getLocStart(),
   2246                                                      PartialSpec->getLocation(),
   2247                                                      InstParams,
   2248                                                      ClassTemplate,
   2249                                                      Converted.data(),
   2250                                                      Converted.size(),
   2251                                                      InstTemplateArgs,
   2252                                                      CanonType,
   2253                                                      0,
   2254                              ClassTemplate->getNextPartialSpecSequenceNumber());
   2255   // Substitute the nested name specifier, if any.
   2256   if (SubstQualifier(PartialSpec, InstPartialSpec))
   2257     return 0;
   2258 
   2259   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
   2260   InstPartialSpec->setTypeAsWritten(WrittenTy);
   2261 
   2262   // Add this partial specialization to the set of class template partial
   2263   // specializations.
   2264   ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
   2265   return InstPartialSpec;
   2266 }
   2267 
   2268 TypeSourceInfo*
   2269 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
   2270                               SmallVectorImpl<ParmVarDecl *> &Params) {
   2271   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
   2272   assert(OldTInfo && "substituting function without type source info");
   2273   assert(Params.empty() && "parameter vector is non-empty at start");
   2274 
   2275   CXXRecordDecl *ThisContext = 0;
   2276   unsigned ThisTypeQuals = 0;
   2277   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
   2278     ThisContext = Method->getParent();
   2279     ThisTypeQuals = Method->getTypeQualifiers();
   2280   }
   2281 
   2282   TypeSourceInfo *NewTInfo
   2283     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
   2284                                     D->getTypeSpecStartLoc(),
   2285                                     D->getDeclName(),
   2286                                     ThisContext, ThisTypeQuals);
   2287   if (!NewTInfo)
   2288     return 0;
   2289 
   2290   if (NewTInfo != OldTInfo) {
   2291     // Get parameters from the new type info.
   2292     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
   2293     if (FunctionProtoTypeLoc *OldProtoLoc
   2294                                   = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
   2295       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
   2296       FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
   2297       assert(NewProtoLoc && "Missing prototype?");
   2298       unsigned NewIdx = 0;
   2299       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
   2300            OldIdx != NumOldParams; ++OldIdx) {
   2301         ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
   2302         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
   2303 
   2304         llvm::Optional<unsigned> NumArgumentsInExpansion;
   2305         if (OldParam->isParameterPack())
   2306           NumArgumentsInExpansion =
   2307               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
   2308                                                  TemplateArgs);
   2309         if (!NumArgumentsInExpansion) {
   2310           // Simple case: normal parameter, or a parameter pack that's
   2311           // instantiated to a (still-dependent) parameter pack.
   2312           ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
   2313           Params.push_back(NewParam);
   2314           Scope->InstantiatedLocal(OldParam, NewParam);
   2315         } else {
   2316           // Parameter pack expansion: make the instantiation an argument pack.
   2317           Scope->MakeInstantiatedLocalArgPack(OldParam);
   2318           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
   2319             ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
   2320             Params.push_back(NewParam);
   2321             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
   2322           }
   2323         }
   2324       }
   2325     }
   2326   } else {
   2327     // The function type itself was not dependent and therefore no
   2328     // substitution occurred. However, we still need to instantiate
   2329     // the function parameters themselves.
   2330     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
   2331     if (FunctionProtoTypeLoc *OldProtoLoc
   2332                                     = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
   2333       for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
   2334         ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
   2335         if (!Parm)
   2336           return 0;
   2337         Params.push_back(Parm);
   2338       }
   2339     }
   2340   }
   2341   return NewTInfo;
   2342 }
   2343 
   2344 /// Introduce the instantiated function parameters into the local
   2345 /// instantiation scope, and set the parameter names to those used
   2346 /// in the template.
   2347 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
   2348                                              const FunctionDecl *PatternDecl,
   2349                                              LocalInstantiationScope &Scope,
   2350                            const MultiLevelTemplateArgumentList &TemplateArgs) {
   2351   unsigned FParamIdx = 0;
   2352   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
   2353     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
   2354     if (!PatternParam->isParameterPack()) {
   2355       // Simple case: not a parameter pack.
   2356       assert(FParamIdx < Function->getNumParams());
   2357       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
   2358       FunctionParam->setDeclName(PatternParam->getDeclName());
   2359       Scope.InstantiatedLocal(PatternParam, FunctionParam);
   2360       ++FParamIdx;
   2361       continue;
   2362     }
   2363 
   2364     // Expand the parameter pack.
   2365     Scope.MakeInstantiatedLocalArgPack(PatternParam);
   2366     llvm::Optional<unsigned> NumArgumentsInExpansion
   2367       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
   2368     assert(NumArgumentsInExpansion &&
   2369            "should only be called when all template arguments are known");
   2370     for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
   2371       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
   2372       FunctionParam->setDeclName(PatternParam->getDeclName());
   2373       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
   2374       ++FParamIdx;
   2375     }
   2376   }
   2377 }
   2378 
   2379 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
   2380                                      const FunctionProtoType *Proto,
   2381                            const MultiLevelTemplateArgumentList &TemplateArgs) {
   2382   assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
   2383 
   2384   // C++11 [expr.prim.general]p3:
   2385   //   If a declaration declares a member function or member function
   2386   //   template of a class X, the expression this is a prvalue of type
   2387   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
   2388   //   and the end of the function-definition, member-declarator, or
   2389   //   declarator.
   2390   CXXRecordDecl *ThisContext = 0;
   2391   unsigned ThisTypeQuals = 0;
   2392   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
   2393     ThisContext = Method->getParent();
   2394     ThisTypeQuals = Method->getTypeQualifiers();
   2395   }
   2396   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
   2397                                    SemaRef.getLangOpts().CPlusPlus0x);
   2398 
   2399   // The function has an exception specification or a "noreturn"
   2400   // attribute. Substitute into each of the exception types.
   2401   SmallVector<QualType, 4> Exceptions;
   2402   for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
   2403     // FIXME: Poor location information!
   2404     if (const PackExpansionType *PackExpansion
   2405           = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
   2406       // We have a pack expansion. Instantiate it.
   2407       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   2408       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
   2409                                               Unexpanded);
   2410       assert(!Unexpanded.empty() &&
   2411              "Pack expansion without parameter packs?");
   2412 
   2413       bool Expand = false;
   2414       bool RetainExpansion = false;
   2415       llvm::Optional<unsigned> NumExpansions
   2416                                         = PackExpansion->getNumExpansions();
   2417       if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
   2418                                                   SourceRange(),
   2419                                                   Unexpanded,
   2420                                                   TemplateArgs,
   2421                                                   Expand,
   2422                                                   RetainExpansion,
   2423                                                   NumExpansions))
   2424         break;
   2425 
   2426       if (!Expand) {
   2427         // We can't expand this pack expansion into separate arguments yet;
   2428         // just substitute into the pattern and create a new pack expansion
   2429         // type.
   2430         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
   2431         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
   2432                                        TemplateArgs,
   2433                                      New->getLocation(), New->getDeclName());
   2434         if (T.isNull())
   2435           break;
   2436 
   2437         T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
   2438         Exceptions.push_back(T);
   2439         continue;
   2440       }
   2441 
   2442       // Substitute into the pack expansion pattern for each template
   2443       bool Invalid = false;
   2444       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
   2445         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
   2446 
   2447         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
   2448                                        TemplateArgs,
   2449                                      New->getLocation(), New->getDeclName());
   2450         if (T.isNull()) {
   2451           Invalid = true;
   2452           break;
   2453         }
   2454 
   2455         Exceptions.push_back(T);
   2456       }
   2457 
   2458       if (Invalid)
   2459         break;
   2460 
   2461       continue;
   2462     }
   2463 
   2464     QualType T
   2465       = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
   2466                           New->getLocation(), New->getDeclName());
   2467     if (T.isNull() ||
   2468         SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
   2469       continue;
   2470 
   2471     Exceptions.push_back(T);
   2472   }
   2473   Expr *NoexceptExpr = 0;
   2474   if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
   2475     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   2476                                                  Sema::ConstantEvaluated);
   2477     ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
   2478     if (E.isUsable())
   2479       E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
   2480 
   2481     if (E.isUsable()) {
   2482       NoexceptExpr = E.take();
   2483       if (!NoexceptExpr->isTypeDependent() &&
   2484           !NoexceptExpr->isValueDependent())
   2485         NoexceptExpr
   2486           = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
   2487               0, diag::err_noexcept_needs_constant_expression,
   2488               /*AllowFold*/ false).take();
   2489     }
   2490   }
   2491 
   2492   // Rebuild the function type
   2493   const FunctionProtoType *NewProto
   2494     = New->getType()->getAs<FunctionProtoType>();
   2495   assert(NewProto && "Template instantiation without function prototype?");
   2496 
   2497   FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
   2498   EPI.ExceptionSpecType = Proto->getExceptionSpecType();
   2499   EPI.NumExceptions = Exceptions.size();
   2500   EPI.Exceptions = Exceptions.data();
   2501   EPI.NoexceptExpr = NoexceptExpr;
   2502 
   2503   New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
   2504                                                NewProto->arg_type_begin(),
   2505                                                NewProto->getNumArgs(),
   2506                                                EPI));
   2507 }
   2508 
   2509 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
   2510                                     FunctionDecl *Decl) {
   2511   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
   2512   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
   2513     return;
   2514 
   2515   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
   2516                              InstantiatingTemplate::ExceptionSpecification());
   2517   if (Inst) {
   2518     // We hit the instantiation depth limit. Clear the exception specification
   2519     // so that our callers don't have to cope with EST_Uninstantiated.
   2520     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   2521     EPI.ExceptionSpecType = EST_None;
   2522     Decl->setType(Context.getFunctionType(Proto->getResultType(),
   2523                                           Proto->arg_type_begin(),
   2524                                           Proto->getNumArgs(),
   2525                                           EPI));
   2526     return;
   2527   }
   2528 
   2529   // Enter the scope of this instantiation. We don't use
   2530   // PushDeclContext because we don't have a scope.
   2531   Sema::ContextRAII savedContext(*this, Decl);
   2532   LocalInstantiationScope Scope(*this);
   2533 
   2534   MultiLevelTemplateArgumentList TemplateArgs =
   2535     getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
   2536 
   2537   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
   2538   addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
   2539 
   2540   ::InstantiateExceptionSpec(*this, Decl,
   2541                              Template->getType()->castAs<FunctionProtoType>(),
   2542                              TemplateArgs);
   2543 }
   2544 
   2545 /// \brief Initializes the common fields of an instantiation function
   2546 /// declaration (New) from the corresponding fields of its template (Tmpl).
   2547 ///
   2548 /// \returns true if there was an error
   2549 bool
   2550 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
   2551                                                     FunctionDecl *Tmpl) {
   2552   if (Tmpl->isDeleted())
   2553     New->setDeletedAsWritten();
   2554 
   2555   // If we are performing substituting explicitly-specified template arguments
   2556   // or deduced template arguments into a function template and we reach this
   2557   // point, we are now past the point where SFINAE applies and have committed
   2558   // to keeping the new function template specialization. We therefore
   2559   // convert the active template instantiation for the function template
   2560   // into a template instantiation for this specific function template
   2561   // specialization, which is not a SFINAE context, so that we diagnose any
   2562   // further errors in the declaration itself.
   2563   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
   2564   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
   2565   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
   2566       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
   2567     if (FunctionTemplateDecl *FunTmpl
   2568           = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
   2569       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
   2570              "Deduction from the wrong function template?");
   2571       (void) FunTmpl;
   2572       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
   2573       ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
   2574     }
   2575   }
   2576 
   2577   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
   2578   assert(Proto && "Function template without prototype?");
   2579 
   2580   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
   2581     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   2582 
   2583     // DR1330: In C++11, defer instantiation of a non-trivial
   2584     // exception specification.
   2585     if (SemaRef.getLangOpts().CPlusPlus0x &&
   2586         EPI.ExceptionSpecType != EST_None &&
   2587         EPI.ExceptionSpecType != EST_DynamicNone &&
   2588         EPI.ExceptionSpecType != EST_BasicNoexcept) {
   2589       FunctionDecl *ExceptionSpecTemplate = Tmpl;
   2590       if (EPI.ExceptionSpecType == EST_Uninstantiated)
   2591         ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
   2592       assert(EPI.ExceptionSpecType != EST_Unevaluated &&
   2593              "instantiating implicitly-declared special member");
   2594 
   2595       // Mark the function has having an uninstantiated exception specification.
   2596       const FunctionProtoType *NewProto
   2597         = New->getType()->getAs<FunctionProtoType>();
   2598       assert(NewProto && "Template instantiation without function prototype?");
   2599       EPI = NewProto->getExtProtoInfo();
   2600       EPI.ExceptionSpecType = EST_Uninstantiated;
   2601       EPI.ExceptionSpecDecl = New;
   2602       EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
   2603       New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
   2604                                                    NewProto->arg_type_begin(),
   2605                                                    NewProto->getNumArgs(),
   2606                                                    EPI));
   2607     } else {
   2608       ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
   2609     }
   2610   }
   2611 
   2612   // Get the definition. Leaves the variable unchanged if undefined.
   2613   const FunctionDecl *Definition = Tmpl;
   2614   Tmpl->isDefined(Definition);
   2615 
   2616   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
   2617                            LateAttrs, StartingScope);
   2618 
   2619   return false;
   2620 }
   2621 
   2622 /// \brief Initializes common fields of an instantiated method
   2623 /// declaration (New) from the corresponding fields of its template
   2624 /// (Tmpl).
   2625 ///
   2626 /// \returns true if there was an error
   2627 bool
   2628 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
   2629                                                   CXXMethodDecl *Tmpl) {
   2630   if (InitFunctionInstantiation(New, Tmpl))
   2631     return true;
   2632 
   2633   New->setAccess(Tmpl->getAccess());
   2634   if (Tmpl->isVirtualAsWritten())
   2635     New->setVirtualAsWritten(true);
   2636 
   2637   // FIXME: attributes
   2638   // FIXME: New needs a pointer to Tmpl
   2639   return false;
   2640 }
   2641 
   2642 /// \brief Instantiate the definition of the given function from its
   2643 /// template.
   2644 ///
   2645 /// \param PointOfInstantiation the point at which the instantiation was
   2646 /// required. Note that this is not precisely a "point of instantiation"
   2647 /// for the function, but it's close.
   2648 ///
   2649 /// \param Function the already-instantiated declaration of a
   2650 /// function template specialization or member function of a class template
   2651 /// specialization.
   2652 ///
   2653 /// \param Recursive if true, recursively instantiates any functions that
   2654 /// are required by this instantiation.
   2655 ///
   2656 /// \param DefinitionRequired if true, then we are performing an explicit
   2657 /// instantiation where the body of the function is required. Complain if
   2658 /// there is no such body.
   2659 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
   2660                                          FunctionDecl *Function,
   2661                                          bool Recursive,
   2662                                          bool DefinitionRequired) {
   2663   if (Function->isInvalidDecl() || Function->isDefined())
   2664     return;
   2665 
   2666   // Never instantiate an explicit specialization except if it is a class scope
   2667   // explicit specialization.
   2668   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
   2669       !Function->getClassScopeSpecializationPattern())
   2670     return;
   2671 
   2672   // Find the function body that we'll be substituting.
   2673   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
   2674   assert(PatternDecl && "instantiating a non-template");
   2675 
   2676   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
   2677   assert(PatternDecl && "template definition is not a template");
   2678   if (!Pattern) {
   2679     // Try to find a defaulted definition
   2680     PatternDecl->isDefined(PatternDecl);
   2681   }
   2682   assert(PatternDecl && "template definition is not a template");
   2683 
   2684   // Postpone late parsed template instantiations.
   2685   if (PatternDecl->isLateTemplateParsed() &&
   2686       !LateTemplateParser) {
   2687     PendingInstantiations.push_back(
   2688       std::make_pair(Function, PointOfInstantiation));
   2689     return;
   2690   }
   2691 
   2692   // Call the LateTemplateParser callback if there a need to late parse
   2693   // a templated function definition.
   2694   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
   2695       LateTemplateParser) {
   2696     LateTemplateParser(OpaqueParser, PatternDecl);
   2697     Pattern = PatternDecl->getBody(PatternDecl);
   2698   }
   2699 
   2700   if (!Pattern && !PatternDecl->isDefaulted()) {
   2701     if (DefinitionRequired) {
   2702       if (Function->getPrimaryTemplate())
   2703         Diag(PointOfInstantiation,
   2704              diag::err_explicit_instantiation_undefined_func_template)
   2705           << Function->getPrimaryTemplate();
   2706       else
   2707         Diag(PointOfInstantiation,
   2708              diag::err_explicit_instantiation_undefined_member)
   2709           << 1 << Function->getDeclName() << Function->getDeclContext();
   2710 
   2711       if (PatternDecl)
   2712         Diag(PatternDecl->getLocation(),
   2713              diag::note_explicit_instantiation_here);
   2714       Function->setInvalidDecl();
   2715     } else if (Function->getTemplateSpecializationKind()
   2716                  == TSK_ExplicitInstantiationDefinition) {
   2717       PendingInstantiations.push_back(
   2718         std::make_pair(Function, PointOfInstantiation));
   2719     }
   2720 
   2721     return;
   2722   }
   2723 
   2724   // C++0x [temp.explicit]p9:
   2725   //   Except for inline functions, other explicit instantiation declarations
   2726   //   have the effect of suppressing the implicit instantiation of the entity
   2727   //   to which they refer.
   2728   if (Function->getTemplateSpecializationKind()
   2729         == TSK_ExplicitInstantiationDeclaration &&
   2730       !PatternDecl->isInlined())
   2731     return;
   2732 
   2733   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
   2734   if (Inst)
   2735     return;
   2736 
   2737   // Copy the inner loc start from the pattern.
   2738   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
   2739 
   2740   // If we're performing recursive template instantiation, create our own
   2741   // queue of pending implicit instantiations that we will instantiate later,
   2742   // while we're still within our own instantiation context.
   2743   SmallVector<VTableUse, 16> SavedVTableUses;
   2744   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
   2745   if (Recursive) {
   2746     VTableUses.swap(SavedVTableUses);
   2747     PendingInstantiations.swap(SavedPendingInstantiations);
   2748   }
   2749 
   2750   EnterExpressionEvaluationContext EvalContext(*this,
   2751                                                Sema::PotentiallyEvaluated);
   2752   ActOnStartOfFunctionDef(0, Function);
   2753 
   2754   // Introduce a new scope where local variable instantiations will be
   2755   // recorded, unless we're actually a member function within a local
   2756   // class, in which case we need to merge our results with the parent
   2757   // scope (of the enclosing function).
   2758   bool MergeWithParentScope = false;
   2759   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
   2760     MergeWithParentScope = Rec->isLocalClass();
   2761 
   2762   LocalInstantiationScope Scope(*this, MergeWithParentScope);
   2763 
   2764   // Enter the scope of this instantiation. We don't use
   2765   // PushDeclContext because we don't have a scope.
   2766   Sema::ContextRAII savedContext(*this, Function);
   2767 
   2768   MultiLevelTemplateArgumentList TemplateArgs =
   2769     getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
   2770 
   2771   addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
   2772                                    TemplateArgs);
   2773 
   2774   if (PatternDecl->isDefaulted()) {
   2775     ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
   2776 
   2777     SetDeclDefaulted(Function, PatternDecl->getLocation());
   2778   } else {
   2779     // If this is a constructor, instantiate the member initializers.
   2780     if (const CXXConstructorDecl *Ctor =
   2781           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
   2782       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
   2783                                  TemplateArgs);
   2784     }
   2785 
   2786     // Instantiate the function body.
   2787     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
   2788 
   2789     if (Body.isInvalid())
   2790       Function->setInvalidDecl();
   2791 
   2792     ActOnFinishFunctionBody(Function, Body.get(),
   2793                             /*IsInstantiation=*/true);
   2794   }
   2795 
   2796   PerformDependentDiagnostics(PatternDecl, TemplateArgs);
   2797 
   2798   savedContext.pop();
   2799 
   2800   DeclGroupRef DG(Function);
   2801   Consumer.HandleTopLevelDecl(DG);
   2802 
   2803   // This class may have local implicit instantiations that need to be
   2804   // instantiation within this scope.
   2805   PerformPendingInstantiations(/*LocalOnly=*/true);
   2806   Scope.Exit();
   2807 
   2808   if (Recursive) {
   2809     // Define any pending vtables.
   2810     DefineUsedVTables();
   2811 
   2812     // Instantiate any pending implicit instantiations found during the
   2813     // instantiation of this template.
   2814     PerformPendingInstantiations();
   2815 
   2816     // Restore the set of pending vtables.
   2817     assert(VTableUses.empty() &&
   2818            "VTableUses should be empty before it is discarded.");
   2819     VTableUses.swap(SavedVTableUses);
   2820 
   2821     // Restore the set of pending implicit instantiations.
   2822     assert(PendingInstantiations.empty() &&
   2823            "PendingInstantiations should be empty before it is discarded.");
   2824     PendingInstantiations.swap(SavedPendingInstantiations);
   2825   }
   2826 }
   2827 
   2828 /// \brief Instantiate the definition of the given variable from its
   2829 /// template.
   2830 ///
   2831 /// \param PointOfInstantiation the point at which the instantiation was
   2832 /// required. Note that this is not precisely a "point of instantiation"
   2833 /// for the function, but it's close.
   2834 ///
   2835 /// \param Var the already-instantiated declaration of a static member
   2836 /// variable of a class template specialization.
   2837 ///
   2838 /// \param Recursive if true, recursively instantiates any functions that
   2839 /// are required by this instantiation.
   2840 ///
   2841 /// \param DefinitionRequired if true, then we are performing an explicit
   2842 /// instantiation where an out-of-line definition of the member variable
   2843 /// is required. Complain if there is no such definition.
   2844 void Sema::InstantiateStaticDataMemberDefinition(
   2845                                           SourceLocation PointOfInstantiation,
   2846                                                  VarDecl *Var,
   2847                                                  bool Recursive,
   2848                                                  bool DefinitionRequired) {
   2849   if (Var->isInvalidDecl())
   2850     return;
   2851 
   2852   // Find the out-of-line definition of this static data member.
   2853   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
   2854   assert(Def && "This data member was not instantiated from a template?");
   2855   assert(Def->isStaticDataMember() && "Not a static data member?");
   2856   Def = Def->getOutOfLineDefinition();
   2857 
   2858   if (!Def) {
   2859     // We did not find an out-of-line definition of this static data member,
   2860     // so we won't perform any instantiation. Rather, we rely on the user to
   2861     // instantiate this definition (or provide a specialization for it) in
   2862     // another translation unit.
   2863     if (DefinitionRequired) {
   2864       Def = Var->getInstantiatedFromStaticDataMember();
   2865       Diag(PointOfInstantiation,
   2866            diag::err_explicit_instantiation_undefined_member)
   2867         << 2 << Var->getDeclName() << Var->getDeclContext();
   2868       Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
   2869     } else if (Var->getTemplateSpecializationKind()
   2870                  == TSK_ExplicitInstantiationDefinition) {
   2871       PendingInstantiations.push_back(
   2872         std::make_pair(Var, PointOfInstantiation));
   2873     }
   2874 
   2875     return;
   2876   }
   2877 
   2878   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
   2879 
   2880   // Never instantiate an explicit specialization.
   2881   if (TSK == TSK_ExplicitSpecialization)
   2882     return;
   2883 
   2884   // C++0x [temp.explicit]p9:
   2885   //   Except for inline functions, other explicit instantiation declarations
   2886   //   have the effect of suppressing the implicit instantiation of the entity
   2887   //   to which they refer.
   2888   if (TSK == TSK_ExplicitInstantiationDeclaration)
   2889     return;
   2890 
   2891   Consumer.HandleCXXStaticMemberVarInstantiation(Var);
   2892 
   2893   // If we already have a definition, we're done.
   2894   if (VarDecl *Def = Var->getDefinition()) {
   2895     // We may be explicitly instantiating something we've already implicitly
   2896     // instantiated.
   2897     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
   2898                                        PointOfInstantiation);
   2899     return;
   2900   }
   2901 
   2902   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
   2903   if (Inst)
   2904     return;
   2905 
   2906   // If we're performing recursive template instantiation, create our own
   2907   // queue of pending implicit instantiations that we will instantiate later,
   2908   // while we're still within our own instantiation context.
   2909   SmallVector<VTableUse, 16> SavedVTableUses;
   2910   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
   2911   if (Recursive) {
   2912     VTableUses.swap(SavedVTableUses);
   2913     PendingInstantiations.swap(SavedPendingInstantiations);
   2914   }
   2915 
   2916   // Enter the scope of this instantiation. We don't use
   2917   // PushDeclContext because we don't have a scope.
   2918   ContextRAII previousContext(*this, Var->getDeclContext());
   2919   LocalInstantiationScope Local(*this);
   2920 
   2921   VarDecl *OldVar = Var;
   2922   Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
   2923                                         getTemplateInstantiationArgs(Var)));
   2924 
   2925   previousContext.pop();
   2926 
   2927   if (Var) {
   2928     MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
   2929     assert(MSInfo && "Missing member specialization information?");
   2930     Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
   2931                                        MSInfo->getPointOfInstantiation());
   2932     DeclGroupRef DG(Var);
   2933     Consumer.HandleTopLevelDecl(DG);
   2934   }
   2935   Local.Exit();
   2936 
   2937   if (Recursive) {
   2938     // Define any newly required vtables.
   2939     DefineUsedVTables();
   2940 
   2941     // Instantiate any pending implicit instantiations found during the
   2942     // instantiation of this template.
   2943     PerformPendingInstantiations();
   2944 
   2945     // Restore the set of pending vtables.
   2946     assert(VTableUses.empty() &&
   2947            "VTableUses should be empty before it is discarded, "
   2948            "while instantiating static data member.");
   2949     VTableUses.swap(SavedVTableUses);
   2950 
   2951     // Restore the set of pending implicit instantiations.
   2952     assert(PendingInstantiations.empty() &&
   2953            "PendingInstantiations should be empty before it is discarded, "
   2954            "while instantiating static data member.");
   2955     PendingInstantiations.swap(SavedPendingInstantiations);
   2956   }
   2957 }
   2958 
   2959 void
   2960 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
   2961                                  const CXXConstructorDecl *Tmpl,
   2962                            const MultiLevelTemplateArgumentList &TemplateArgs) {
   2963 
   2964   SmallVector<CXXCtorInitializer*, 4> NewInits;
   2965   bool AnyErrors = false;
   2966 
   2967   // Instantiate all the initializers.
   2968   for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
   2969                                             InitsEnd = Tmpl->init_end();
   2970        Inits != InitsEnd; ++Inits) {
   2971     CXXCtorInitializer *Init = *Inits;
   2972 
   2973     // Only instantiate written initializers, let Sema re-construct implicit
   2974     // ones.
   2975     if (!Init->isWritten())
   2976       continue;
   2977 
   2978     SourceLocation EllipsisLoc;
   2979 
   2980     if (Init->isPackExpansion()) {
   2981       // This is a pack expansion. We should expand it now.
   2982       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
   2983       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   2984       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
   2985       bool ShouldExpand = false;
   2986       bool RetainExpansion = false;
   2987       llvm::Optional<unsigned> NumExpansions;
   2988       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
   2989                                           BaseTL.getSourceRange(),
   2990                                           Unexpanded,
   2991                                           TemplateArgs, ShouldExpand,
   2992                                           RetainExpansion,
   2993                                           NumExpansions)) {
   2994         AnyErrors = true;
   2995         New->setInvalidDecl();
   2996         continue;
   2997       }
   2998       assert(ShouldExpand && "Partial instantiation of base initializer?");
   2999 
   3000       // Loop over all of the arguments in the argument pack(s),
   3001       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3002         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
   3003 
   3004         // Instantiate the initializer.
   3005         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
   3006                                                /*CXXDirectInit=*/true);
   3007         if (TempInit.isInvalid()) {
   3008           AnyErrors = true;
   3009           break;
   3010         }
   3011 
   3012         // Instantiate the base type.
   3013         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
   3014                                               TemplateArgs,
   3015                                               Init->getSourceLocation(),
   3016                                               New->getDeclName());
   3017         if (!BaseTInfo) {
   3018           AnyErrors = true;
   3019           break;
   3020         }
   3021 
   3022         // Build the initializer.
   3023         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
   3024                                                      BaseTInfo, TempInit.take(),
   3025                                                      New->getParent(),
   3026                                                      SourceLocation());
   3027         if (NewInit.isInvalid()) {
   3028           AnyErrors = true;
   3029           break;
   3030         }
   3031 
   3032         NewInits.push_back(NewInit.get());
   3033       }
   3034 
   3035       continue;
   3036     }
   3037 
   3038     // Instantiate the initializer.
   3039     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
   3040                                            /*CXXDirectInit=*/true);
   3041     if (TempInit.isInvalid()) {
   3042       AnyErrors = true;
   3043       continue;
   3044     }
   3045 
   3046     MemInitResult NewInit;
   3047     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
   3048       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
   3049                                         TemplateArgs,
   3050                                         Init->getSourceLocation(),
   3051                                         New->getDeclName());
   3052       if (!TInfo) {
   3053         AnyErrors = true;
   3054         New->setInvalidDecl();
   3055         continue;
   3056       }
   3057 
   3058       if (Init->isBaseInitializer())
   3059         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
   3060                                        New->getParent(), EllipsisLoc);
   3061       else
   3062         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
   3063                                   cast<CXXRecordDecl>(CurContext->getParent()));
   3064     } else if (Init->isMemberInitializer()) {
   3065       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
   3066                                                      Init->getMemberLocation(),
   3067                                                      Init->getMember(),
   3068                                                      TemplateArgs));
   3069       if (!Member) {
   3070         AnyErrors = true;
   3071         New->setInvalidDecl();
   3072         continue;
   3073       }
   3074 
   3075       NewInit = BuildMemberInitializer(Member, TempInit.take(),
   3076                                        Init->getSourceLocation());
   3077     } else if (Init->isIndirectMemberInitializer()) {
   3078       IndirectFieldDecl *IndirectMember =
   3079          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
   3080                                  Init->getMemberLocation(),
   3081                                  Init->getIndirectMember(), TemplateArgs));
   3082 
   3083       if (!IndirectMember) {
   3084         AnyErrors = true;
   3085         New->setInvalidDecl();
   3086         continue;
   3087       }
   3088 
   3089       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
   3090                                        Init->getSourceLocation());
   3091     }
   3092 
   3093     if (NewInit.isInvalid()) {
   3094       AnyErrors = true;
   3095       New->setInvalidDecl();
   3096     } else {
   3097       NewInits.push_back(NewInit.get());
   3098     }
   3099   }
   3100 
   3101   // Assign all the initializers to the new constructor.
   3102   ActOnMemInitializers(New,
   3103                        /*FIXME: ColonLoc */
   3104                        SourceLocation(),
   3105                        NewInits.data(), NewInits.size(),
   3106                        AnyErrors);
   3107 }
   3108 
   3109 ExprResult Sema::SubstInitializer(Expr *Init,
   3110                           const MultiLevelTemplateArgumentList &TemplateArgs,
   3111                           bool CXXDirectInit) {
   3112   // Initializers are instantiated like expressions, except that various outer
   3113   // layers are stripped.
   3114   if (!Init)
   3115     return Owned(Init);
   3116 
   3117   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
   3118     Init = ExprTemp->getSubExpr();
   3119 
   3120   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
   3121     Init = Binder->getSubExpr();
   3122 
   3123   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
   3124     Init = ICE->getSubExprAsWritten();
   3125 
   3126   // If this is a direct-initializer, we take apart CXXConstructExprs.
   3127   // Everything else is passed through.
   3128   CXXConstructExpr *Construct;
   3129   if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
   3130       isa<CXXTemporaryObjectExpr>(Construct))
   3131     return SubstExpr(Init, TemplateArgs);
   3132 
   3133   SmallVector<Expr*, 8> NewArgs;
   3134   if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
   3135                  TemplateArgs, NewArgs))
   3136     return ExprError();
   3137 
   3138   // Treat an empty initializer like none.
   3139   if (NewArgs.empty())
   3140     return Owned((Expr*)0);
   3141 
   3142   // Build a ParenListExpr to represent anything else.
   3143   // FIXME: Fake locations!
   3144   SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
   3145   return ActOnParenListExpr(Loc, Loc, NewArgs);
   3146 }
   3147 
   3148 // TODO: this could be templated if the various decl types used the
   3149 // same method name.
   3150 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
   3151                               ClassTemplateDecl *Instance) {
   3152   Pattern = Pattern->getCanonicalDecl();
   3153 
   3154   do {
   3155     Instance = Instance->getCanonicalDecl();
   3156     if (Pattern == Instance) return true;
   3157     Instance = Instance->getInstantiatedFromMemberTemplate();
   3158   } while (Instance);
   3159 
   3160   return false;
   3161 }
   3162 
   3163 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
   3164                               FunctionTemplateDecl *Instance) {
   3165   Pattern = Pattern->getCanonicalDecl();
   3166 
   3167   do {
   3168     Instance = Instance->getCanonicalDecl();
   3169     if (Pattern == Instance) return true;
   3170     Instance = Instance->getInstantiatedFromMemberTemplate();
   3171   } while (Instance);
   3172 
   3173   return false;
   3174 }
   3175 
   3176 static bool
   3177 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
   3178                   ClassTemplatePartialSpecializationDecl *Instance) {
   3179   Pattern
   3180     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
   3181   do {
   3182     Instance = cast<ClassTemplatePartialSpecializationDecl>(
   3183                                                 Instance->getCanonicalDecl());
   3184     if (Pattern == Instance)
   3185       return true;
   3186     Instance = Instance->getInstantiatedFromMember();
   3187   } while (Instance);
   3188 
   3189   return false;
   3190 }
   3191 
   3192 static bool isInstantiationOf(CXXRecordDecl *Pattern,
   3193                               CXXRecordDecl *Instance) {
   3194   Pattern = Pattern->getCanonicalDecl();
   3195 
   3196   do {
   3197     Instance = Instance->getCanonicalDecl();
   3198     if (Pattern == Instance) return true;
   3199     Instance = Instance->getInstantiatedFromMemberClass();
   3200   } while (Instance);
   3201 
   3202   return false;
   3203 }
   3204 
   3205 static bool isInstantiationOf(FunctionDecl *Pattern,
   3206                               FunctionDecl *Instance) {
   3207   Pattern = Pattern->getCanonicalDecl();
   3208 
   3209   do {
   3210     Instance = Instance->getCanonicalDecl();
   3211     if (Pattern == Instance) return true;
   3212     Instance = Instance->getInstantiatedFromMemberFunction();
   3213   } while (Instance);
   3214 
   3215   return false;
   3216 }
   3217 
   3218 static bool isInstantiationOf(EnumDecl *Pattern,
   3219                               EnumDecl *Instance) {
   3220   Pattern = Pattern->getCanonicalDecl();
   3221 
   3222   do {
   3223     Instance = Instance->getCanonicalDecl();
   3224     if (Pattern == Instance) return true;
   3225     Instance = Instance->getInstantiatedFromMemberEnum();
   3226   } while (Instance);
   3227 
   3228   return false;
   3229 }
   3230 
   3231 static bool isInstantiationOf(UsingShadowDecl *Pattern,
   3232                               UsingShadowDecl *Instance,
   3233                               ASTContext &C) {
   3234   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
   3235 }
   3236 
   3237 static bool isInstantiationOf(UsingDecl *Pattern,
   3238                               UsingDecl *Instance,
   3239                               ASTContext &C) {
   3240   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
   3241 }
   3242 
   3243 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
   3244                               UsingDecl *Instance,
   3245                               ASTContext &C) {
   3246   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
   3247 }
   3248 
   3249 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
   3250                               UsingDecl *Instance,
   3251                               ASTContext &C) {
   3252   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
   3253 }
   3254 
   3255 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
   3256                                               VarDecl *Instance) {
   3257   assert(Instance->isStaticDataMember());
   3258 
   3259   Pattern = Pattern->getCanonicalDecl();
   3260 
   3261   do {
   3262     Instance = Instance->getCanonicalDecl();
   3263     if (Pattern == Instance) return true;
   3264     Instance = Instance->getInstantiatedFromStaticDataMember();
   3265   } while (Instance);
   3266 
   3267   return false;
   3268 }
   3269 
   3270 // Other is the prospective instantiation
   3271 // D is the prospective pattern
   3272 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
   3273   if (D->getKind() != Other->getKind()) {
   3274     if (UnresolvedUsingTypenameDecl *UUD
   3275           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
   3276       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
   3277         return isInstantiationOf(UUD, UD, Ctx);
   3278       }
   3279     }
   3280 
   3281     if (UnresolvedUsingValueDecl *UUD
   3282           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
   3283       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
   3284         return isInstantiationOf(UUD, UD, Ctx);
   3285       }
   3286     }
   3287 
   3288     return false;
   3289   }
   3290 
   3291   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
   3292     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
   3293 
   3294   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
   3295     return isInstantiationOf(cast<FunctionDecl>(D), Function);
   3296 
   3297   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
   3298     return isInstantiationOf(cast<EnumDecl>(D), Enum);
   3299 
   3300   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
   3301     if (Var->isStaticDataMember())
   3302       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
   3303 
   3304   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
   3305     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
   3306 
   3307   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
   3308     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
   3309 
   3310   if (ClassTemplatePartialSpecializationDecl *PartialSpec
   3311         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
   3312     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
   3313                              PartialSpec);
   3314 
   3315   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
   3316     if (!Field->getDeclName()) {
   3317       // This is an unnamed field.
   3318       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
   3319         cast<FieldDecl>(D);
   3320     }
   3321   }
   3322 
   3323   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
   3324     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
   3325 
   3326   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
   3327     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
   3328 
   3329   return D->getDeclName() && isa<NamedDecl>(Other) &&
   3330     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
   3331 }
   3332 
   3333 template<typename ForwardIterator>
   3334 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
   3335                                       NamedDecl *D,
   3336                                       ForwardIterator first,
   3337                                       ForwardIterator last) {
   3338   for (; first != last; ++first)
   3339     if (isInstantiationOf(Ctx, D, *first))
   3340       return cast<NamedDecl>(*first);
   3341 
   3342   return 0;
   3343 }
   3344 
   3345 /// \brief Finds the instantiation of the given declaration context
   3346 /// within the current instantiation.
   3347 ///
   3348 /// \returns NULL if there was an error
   3349 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
   3350                           const MultiLevelTemplateArgumentList &TemplateArgs) {
   3351   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
   3352     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
   3353     return cast_or_null<DeclContext>(ID);
   3354   } else return DC;
   3355 }
   3356 
   3357 /// \brief Find the instantiation of the given declaration within the
   3358 /// current instantiation.
   3359 ///
   3360 /// This routine is intended to be used when \p D is a declaration
   3361 /// referenced from within a template, that needs to mapped into the
   3362 /// corresponding declaration within an instantiation. For example,
   3363 /// given:
   3364 ///
   3365 /// \code
   3366 /// template<typename T>
   3367 /// struct X {
   3368 ///   enum Kind {
   3369 ///     KnownValue = sizeof(T)
   3370 ///   };
   3371 ///
   3372 ///   bool getKind() const { return KnownValue; }
   3373 /// };
   3374 ///
   3375 /// template struct X<int>;
   3376 /// \endcode
   3377 ///
   3378 /// In the instantiation of X<int>::getKind(), we need to map the
   3379 /// EnumConstantDecl for KnownValue (which refers to
   3380 /// X<T>::\<Kind>\::KnownValue) to its instantiation
   3381 /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
   3382 /// this mapping from within the instantiation of X<int>.
   3383 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
   3384                           const MultiLevelTemplateArgumentList &TemplateArgs) {
   3385   DeclContext *ParentDC = D->getDeclContext();
   3386   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
   3387       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
   3388       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
   3389       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
   3390     // D is a local of some kind. Look into the map of local
   3391     // declarations to their instantiations.
   3392     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
   3393     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
   3394       = CurrentInstantiationScope->findInstantiationOf(D);
   3395 
   3396     if (Found) {
   3397       if (Decl *FD = Found->dyn_cast<Decl *>())
   3398         return cast<NamedDecl>(FD);
   3399 
   3400       unsigned PackIdx = ArgumentPackSubstitutionIndex;
   3401       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
   3402     }
   3403 
   3404     // If we didn't find the decl, then we must have a label decl that hasn't
   3405     // been found yet.  Lazily instantiate it and return it now.
   3406     assert(isa<LabelDecl>(D));
   3407 
   3408     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
   3409     assert(Inst && "Failed to instantiate label??");
   3410 
   3411     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
   3412     return cast<LabelDecl>(Inst);
   3413   }
   3414 
   3415   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
   3416     if (!Record->isDependentContext())
   3417       return D;
   3418 
   3419     // Determine whether this record is the "templated" declaration describing
   3420     // a class template or class template partial specialization.
   3421     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
   3422     if (ClassTemplate)
   3423       ClassTemplate = ClassTemplate->getCanonicalDecl();
   3424     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
   3425                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
   3426       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
   3427 
   3428     // Walk the current context to find either the record or an instantiation of
   3429     // it.
   3430     DeclContext *DC = CurContext;
   3431     while (!DC->isFileContext()) {
   3432       // If we're performing substitution while we're inside the template
   3433       // definition, we'll find our own context. We're done.
   3434       if (DC->Equals(Record))
   3435         return Record;
   3436 
   3437       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
   3438         // Check whether we're in the process of instantiating a class template
   3439         // specialization of the template we're mapping.
   3440         if (ClassTemplateSpecializationDecl *InstSpec
   3441                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
   3442           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
   3443           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
   3444             return InstRecord;
   3445         }
   3446 
   3447         // Check whether we're in the process of instantiating a member class.
   3448         if (isInstantiationOf(Record, InstRecord))
   3449           return InstRecord;
   3450       }
   3451 
   3452 
   3453       // Move to the outer template scope.
   3454       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
   3455         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
   3456           DC = FD->getLexicalDeclContext();
   3457           continue;
   3458         }
   3459       }
   3460 
   3461       DC = DC->getParent();
   3462     }
   3463 
   3464     // Fall through to deal with other dependent record types (e.g.,
   3465     // anonymous unions in class templates).
   3466   }
   3467 
   3468   if (!ParentDC->isDependentContext())
   3469     return D;
   3470 
   3471   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
   3472   if (!ParentDC)
   3473     return 0;
   3474 
   3475   if (ParentDC != D->getDeclContext()) {
   3476     // We performed some kind of instantiation in the parent context,
   3477     // so now we need to look into the instantiated parent context to
   3478     // find the instantiation of the declaration D.
   3479 
   3480     // If our context used to be dependent, we may need to instantiate
   3481     // it before performing lookup into that context.
   3482     bool IsBeingInstantiated = false;
   3483     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
   3484       if (!Spec->isDependentContext()) {
   3485         QualType T = Context.getTypeDeclType(Spec);
   3486         const RecordType *Tag = T->getAs<RecordType>();
   3487         assert(Tag && "type of non-dependent record is not a RecordType");
   3488         if (Tag->isBeingDefined())
   3489           IsBeingInstantiated = true;
   3490         if (!Tag->isBeingDefined() &&
   3491             RequireCompleteType(Loc, T, diag::err_incomplete_type))
   3492           return 0;
   3493 
   3494         ParentDC = Tag->getDecl();
   3495       }
   3496     }
   3497 
   3498     NamedDecl *Result = 0;
   3499     if (D->getDeclName()) {
   3500       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
   3501       Result = findInstantiationOf(Context, D, Found.first, Found.second);
   3502     } else {
   3503       // Since we don't have a name for the entity we're looking for,
   3504       // our only option is to walk through all of the declarations to
   3505       // find that name. This will occur in a few cases:
   3506       //
   3507       //   - anonymous struct/union within a template
   3508       //   - unnamed class/struct/union/enum within a template
   3509       //
   3510       // FIXME: Find a better way to find these instantiations!
   3511       Result = findInstantiationOf(Context, D,
   3512                                    ParentDC->decls_begin(),
   3513                                    ParentDC->decls_end());
   3514     }
   3515 
   3516     if (!Result) {
   3517       if (isa<UsingShadowDecl>(D)) {
   3518         // UsingShadowDecls can instantiate to nothing because of using hiding.
   3519       } else if (Diags.hasErrorOccurred()) {
   3520         // We've already complained about something, so most likely this
   3521         // declaration failed to instantiate. There's no point in complaining
   3522         // further, since this is normal in invalid code.
   3523       } else if (IsBeingInstantiated) {
   3524         // The class in which this member exists is currently being
   3525         // instantiated, and we haven't gotten around to instantiating this
   3526         // member yet. This can happen when the code uses forward declarations
   3527         // of member classes, and introduces ordering dependencies via
   3528         // template instantiation.
   3529         Diag(Loc, diag::err_member_not_yet_instantiated)
   3530           << D->getDeclName()
   3531           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
   3532         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
   3533       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
   3534         // This enumeration constant was found when the template was defined,
   3535         // but can't be found in the instantiation. This can happen if an
   3536         // unscoped enumeration member is explicitly specialized.
   3537         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
   3538         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
   3539                                                              TemplateArgs));
   3540         assert(Spec->getTemplateSpecializationKind() ==
   3541                  TSK_ExplicitSpecialization);
   3542         Diag(Loc, diag::err_enumerator_does_not_exist)
   3543           << D->getDeclName()
   3544           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
   3545         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
   3546           << Context.getTypeDeclType(Spec);
   3547       } else {
   3548         // We should have found something, but didn't.
   3549         llvm_unreachable("Unable to find instantiation of declaration!");
   3550       }
   3551     }
   3552 
   3553     D = Result;
   3554   }
   3555 
   3556   return D;
   3557 }
   3558 
   3559 /// \brief Performs template instantiation for all implicit template
   3560 /// instantiations we have seen until this point.
   3561 void Sema::PerformPendingInstantiations(bool LocalOnly) {
   3562   // Load pending instantiations from the external source.
   3563   if (!LocalOnly && ExternalSource) {
   3564     SmallVector<PendingImplicitInstantiation, 4> Pending;
   3565     ExternalSource->ReadPendingInstantiations(Pending);
   3566     PendingInstantiations.insert(PendingInstantiations.begin(),
   3567                                  Pending.begin(), Pending.end());
   3568   }
   3569 
   3570   while (!PendingLocalImplicitInstantiations.empty() ||
   3571          (!LocalOnly && !PendingInstantiations.empty())) {
   3572     PendingImplicitInstantiation Inst;
   3573 
   3574     if (PendingLocalImplicitInstantiations.empty()) {
   3575       Inst = PendingInstantiations.front();
   3576       PendingInstantiations.pop_front();
   3577     } else {
   3578       Inst = PendingLocalImplicitInstantiations.front();
   3579       PendingLocalImplicitInstantiations.pop_front();
   3580     }
   3581 
   3582     // Instantiate function definitions
   3583     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
   3584       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
   3585                                           "instantiating function definition");
   3586       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
   3587                                 TSK_ExplicitInstantiationDefinition;
   3588       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
   3589                                     DefinitionRequired);
   3590       continue;
   3591     }
   3592 
   3593     // Instantiate static data member definitions.
   3594     VarDecl *Var = cast<VarDecl>(Inst.first);
   3595     assert(Var->isStaticDataMember() && "Not a static data member?");
   3596 
   3597     // Don't try to instantiate declarations if the most recent redeclaration
   3598     // is invalid.
   3599     if (Var->getMostRecentDecl()->isInvalidDecl())
   3600       continue;
   3601 
   3602     // Check if the most recent declaration has changed the specialization kind
   3603     // and removed the need for implicit instantiation.
   3604     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
   3605     case TSK_Undeclared:
   3606       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
   3607     case TSK_ExplicitInstantiationDeclaration:
   3608     case TSK_ExplicitSpecialization:
   3609       continue;  // No longer need to instantiate this type.
   3610     case TSK_ExplicitInstantiationDefinition:
   3611       // We only need an instantiation if the pending instantiation *is* the
   3612       // explicit instantiation.
   3613       if (Var != Var->getMostRecentDecl()) continue;
   3614     case TSK_ImplicitInstantiation:
   3615       break;
   3616     }
   3617 
   3618     PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
   3619                                         "instantiating static data member "
   3620                                         "definition");
   3621 
   3622     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
   3623                               TSK_ExplicitInstantiationDefinition;
   3624     InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
   3625                                           DefinitionRequired);
   3626   }
   3627 }
   3628 
   3629 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
   3630                        const MultiLevelTemplateArgumentList &TemplateArgs) {
   3631   for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
   3632          E = Pattern->ddiag_end(); I != E; ++I) {
   3633     DependentDiagnostic *DD = *I;
   3634 
   3635     switch (DD->getKind()) {
   3636     case DependentDiagnostic::Access:
   3637       HandleDependentAccessCheck(*DD, TemplateArgs);
   3638       break;
   3639     }
   3640   }
   3641 }
   3642