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