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