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