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