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