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 "Sema.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/Expr.h"
18 #include "llvm/Support/Compiler.h"
19 
20 using namespace clang;
21 
22 namespace {
23   class VISIBILITY_HIDDEN TemplateDeclInstantiator
24     : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
25     Sema &SemaRef;
26     DeclContext *Owner;
27     const TemplateArgumentList &TemplateArgs;
28 
29   public:
30     typedef Sema::OwningExprResult OwningExprResult;
31 
32     TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
33                              const TemplateArgumentList &TemplateArgs)
34       : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
35 
36     // FIXME: Once we get closer to completion, replace these manually-written
37     // declarations with automatically-generated ones from
38     // clang/AST/DeclNodes.def.
39     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
40     Decl *VisitNamespaceDecl(NamespaceDecl *D);
41     Decl *VisitTypedefDecl(TypedefDecl *D);
42     Decl *VisitVarDecl(VarDecl *D);
43     Decl *VisitFieldDecl(FieldDecl *D);
44     Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
45     Decl *VisitEnumDecl(EnumDecl *D);
46     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
47     Decl *VisitFunctionDecl(FunctionDecl *D);
48     Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
49     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
50     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
51     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
52     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
53     ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
54     Decl *VisitOriginalParmVarDecl(OriginalParmVarDecl *D);
55 
56     // Base case. FIXME: Remove once we can instantiate everything.
57     Decl *VisitDecl(Decl *) {
58       assert(false && "Template instantiation of unknown declaration kind!");
59       return 0;
60     }
61 
62     // Helper functions for instantiating methods.
63     QualType InstantiateFunctionType(FunctionDecl *D,
64                              llvm::SmallVectorImpl<ParmVarDecl *> &Params);
65     bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
66     bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
67   };
68 }
69 
70 Decl *
71 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
72   assert(false && "Translation units cannot be instantiated");
73   return D;
74 }
75 
76 Decl *
77 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
78   assert(false && "Namespaces cannot be instantiated");
79   return D;
80 }
81 
82 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
83   bool Invalid = false;
84   QualType T = D->getUnderlyingType();
85   if (T->isDependentType()) {
86     T = SemaRef.InstantiateType(T, TemplateArgs,
87                                 D->getLocation(), D->getDeclName());
88     if (T.isNull()) {
89       Invalid = true;
90       T = SemaRef.Context.IntTy;
91     }
92   }
93 
94   // Create the new typedef
95   TypedefDecl *Typedef
96     = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
97                           D->getIdentifier(), T);
98   if (Invalid)
99     Typedef->setInvalidDecl();
100 
101   Owner->addDecl(Typedef);
102 
103   return Typedef;
104 }
105 
106 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
107   // Instantiate the type of the declaration
108   QualType T = SemaRef.InstantiateType(D->getType(), TemplateArgs,
109                                        D->getTypeSpecStartLoc(),
110                                        D->getDeclName());
111   if (T.isNull())
112     return 0;
113 
114   // Build the instantiated declaration
115   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
116                                  D->getLocation(), D->getIdentifier(),
117                                  T, D->getStorageClass(),
118                                  D->getTypeSpecStartLoc());
119   Var->setThreadSpecified(D->isThreadSpecified());
120   Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
121   Var->setDeclaredInCondition(D->isDeclaredInCondition());
122 
123   // If we are instantiating a static data member defined
124   // out-of-line, the instantiation will have the same lexical
125   // context (which will be a namespace scope) as the template.
126   if (D->isOutOfLine())
127     Var->setLexicalDeclContext(D->getLexicalDeclContext());
128 
129   // FIXME: In theory, we could have a previous declaration for variables that
130   // are not static data members.
131   bool Redeclaration = false;
132   SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration);
133 
134   if (D->isOutOfLine()) {
135     D->getLexicalDeclContext()->addDecl(Var);
136     Owner->makeDeclVisibleInContext(Var);
137   } else {
138     Owner->addDecl(Var);
139   }
140 
141   if (D->getInit()) {
142     OwningExprResult Init
143       = SemaRef.InstantiateExpr(D->getInit(), TemplateArgs);
144     if (Init.isInvalid())
145       Var->setInvalidDecl();
146     else
147       SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init),
148                                    D->hasCXXDirectInitializer());
149   } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
150     SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
151 
152   // Link instantiations of static data members back to the template from
153   // which they were instantiated.
154   if (Var->isStaticDataMember())
155     SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D);
156 
157   return Var;
158 }
159 
160 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
161   bool Invalid = false;
162   QualType T = D->getType();
163   if (T->isDependentType())  {
164     T = SemaRef.InstantiateType(T, TemplateArgs,
165                                 D->getLocation(), D->getDeclName());
166     if (!T.isNull() && T->isFunctionType()) {
167       // C++ [temp.arg.type]p3:
168       //   If a declaration acquires a function type through a type
169       //   dependent on a template-parameter and this causes a
170       //   declaration that does not use the syntactic form of a
171       //   function declarator to have function type, the program is
172       //   ill-formed.
173       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
174         << T;
175       T = QualType();
176       Invalid = true;
177     }
178   }
179 
180   Expr *BitWidth = D->getBitWidth();
181   if (Invalid)
182     BitWidth = 0;
183   else if (BitWidth) {
184     // The bit-width expression is not potentially evaluated.
185     EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
186 
187     OwningExprResult InstantiatedBitWidth
188       = SemaRef.InstantiateExpr(BitWidth, TemplateArgs);
189     if (InstantiatedBitWidth.isInvalid()) {
190       Invalid = true;
191       BitWidth = 0;
192     } else
193       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
194   }
195 
196   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), T,
197                                             cast<RecordDecl>(Owner),
198                                             D->getLocation(),
199                                             D->isMutable(),
200                                             BitWidth,
201                                             D->getTypeSpecStartLoc(),
202                                             D->getAccess(),
203                                             0);
204   if (Field) {
205     if (Invalid)
206       Field->setInvalidDecl();
207 
208     Owner->addDecl(Field);
209   }
210 
211   return Field;
212 }
213 
214 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
215   Expr *AssertExpr = D->getAssertExpr();
216 
217   // The expression in a static assertion is not potentially evaluated.
218   EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
219 
220   OwningExprResult InstantiatedAssertExpr
221     = SemaRef.InstantiateExpr(AssertExpr, TemplateArgs);
222   if (InstantiatedAssertExpr.isInvalid())
223     return 0;
224 
225   OwningExprResult Message = SemaRef.Clone(D->getMessage());
226   Decl *StaticAssert
227     = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
228                                            move(InstantiatedAssertExpr),
229                                            move(Message)).getAs<Decl>();
230   return StaticAssert;
231 }
232 
233 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
234   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
235                                     D->getLocation(), D->getIdentifier(),
236                                     D->getTagKeywordLoc(),
237                                     /*PrevDecl=*/0);
238   Enum->setInstantiationOfMemberEnum(D);
239   Enum->setAccess(D->getAccess());
240   Owner->addDecl(Enum);
241   Enum->startDefinition();
242 
243   llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
244 
245   EnumConstantDecl *LastEnumConst = 0;
246   for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
247          ECEnd = D->enumerator_end();
248        EC != ECEnd; ++EC) {
249     // The specified value for the enumerator.
250     OwningExprResult Value = SemaRef.Owned((Expr *)0);
251     if (Expr *UninstValue = EC->getInitExpr()) {
252       // The enumerator's value expression is not potentially evaluated.
253       EnterExpressionEvaluationContext Unevaluated(SemaRef,
254                                                    Action::Unevaluated);
255 
256       Value = SemaRef.InstantiateExpr(UninstValue, TemplateArgs);
257     }
258 
259     // Drop the initial value and continue.
260     bool isInvalid = false;
261     if (Value.isInvalid()) {
262       Value = SemaRef.Owned((Expr *)0);
263       isInvalid = true;
264     }
265 
266     EnumConstantDecl *EnumConst
267       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
268                                   EC->getLocation(), EC->getIdentifier(),
269                                   move(Value));
270 
271     if (isInvalid) {
272       if (EnumConst)
273         EnumConst->setInvalidDecl();
274       Enum->setInvalidDecl();
275     }
276 
277     if (EnumConst) {
278       Enum->addDecl(EnumConst);
279       Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
280       LastEnumConst = EnumConst;
281     }
282   }
283 
284   // FIXME: Fixup LBraceLoc and RBraceLoc
285   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
286                         Sema::DeclPtrTy::make(Enum),
287                         &Enumerators[0], Enumerators.size());
288 
289   return Enum;
290 }
291 
292 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
293   assert(false && "EnumConstantDecls can only occur within EnumDecls.");
294   return 0;
295 }
296 
297 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
298   CXXRecordDecl *PrevDecl = 0;
299   if (D->isInjectedClassName())
300     PrevDecl = cast<CXXRecordDecl>(Owner);
301 
302   CXXRecordDecl *Record
303     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
304                             D->getLocation(), D->getIdentifier(),
305                             D->getTagKeywordLoc(), PrevDecl);
306   Record->setImplicit(D->isImplicit());
307   Record->setAccess(D->getAccess());
308   if (!D->isInjectedClassName())
309     Record->setInstantiationOfMemberClass(D);
310 
311   Owner->addDecl(Record);
312   return Record;
313 }
314 
315 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
316   // Check whether there is already a function template specialization for
317   // this declaration.
318   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
319   void *InsertPos = 0;
320   if (FunctionTemplate) {
321     llvm::FoldingSetNodeID ID;
322     FunctionTemplateSpecializationInfo::Profile(ID,
323                                           TemplateArgs.getFlatArgumentList(),
324                                                 TemplateArgs.flat_size(),
325                                                 SemaRef.Context);
326 
327     FunctionTemplateSpecializationInfo *Info
328       = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
329                                                                    InsertPos);
330 
331     // If we already have a function template specialization, return it.
332     if (Info)
333       return Info->Function;
334   }
335 
336   Sema::LocalInstantiationScope Scope(SemaRef);
337 
338   llvm::SmallVector<ParmVarDecl *, 4> Params;
339   QualType T = InstantiateFunctionType(D, Params);
340   if (T.isNull())
341     return 0;
342 
343   // Build the instantiated method declaration.
344   FunctionDecl *Function
345     = FunctionDecl::Create(SemaRef.Context, Owner, D->getLocation(),
346                            D->getDeclName(), T, D->getStorageClass(),
347                            D->isInline(), D->hasWrittenPrototype(),
348                            D->getTypeSpecStartLoc());
349 
350   // FIXME: friend functions
351 
352   // Attach the parameters
353   for (unsigned P = 0; P < Params.size(); ++P)
354     Params[P]->setOwningFunction(Function);
355   Function->setParams(SemaRef.Context, Params.data(), Params.size());
356 
357   if (InitFunctionInstantiation(Function, D))
358     Function->setInvalidDecl();
359 
360   bool Redeclaration = false;
361   bool OverloadableAttrRequired = false;
362   NamedDecl *PrevDecl = 0;
363   SemaRef.CheckFunctionDeclaration(Function, PrevDecl, Redeclaration,
364                                    /*FIXME:*/OverloadableAttrRequired);
365 
366   if (FunctionTemplate) {
367     // Record this function template specialization.
368     Function->setFunctionTemplateSpecialization(SemaRef.Context,
369                                                 FunctionTemplate,
370                                                 &TemplateArgs,
371                                                 InsertPos);
372    }
373 
374   return Function;
375 }
376 
377 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
378   // FIXME: Look for existing, explicit specializations.
379   Sema::LocalInstantiationScope Scope(SemaRef);
380 
381   llvm::SmallVector<ParmVarDecl *, 4> Params;
382   QualType T = InstantiateFunctionType(D, Params);
383   if (T.isNull())
384     return 0;
385 
386   // Build the instantiated method declaration.
387   CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
388   CXXMethodDecl *Method
389     = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
390                             D->getDeclName(), T, D->isStatic(),
391                             D->isInline());
392   Method->setInstantiationOfMemberFunction(D);
393 
394   // If we are instantiating a member function defined
395   // out-of-line, the instantiation will have the same lexical
396   // context (which will be a namespace scope) as the template.
397   if (D->isOutOfLine())
398     Method->setLexicalDeclContext(D->getLexicalDeclContext());
399 
400   // Attach the parameters
401   for (unsigned P = 0; P < Params.size(); ++P)
402     Params[P]->setOwningFunction(Method);
403   Method->setParams(SemaRef.Context, Params.data(), Params.size());
404 
405   if (InitMethodInstantiation(Method, D))
406     Method->setInvalidDecl();
407 
408   NamedDecl *PrevDecl
409     = SemaRef.LookupQualifiedName(Owner, Method->getDeclName(),
410                                   Sema::LookupOrdinaryName, true);
411   // In C++, the previous declaration we find might be a tag type
412   // (class or enum). In this case, the new declaration will hide the
413   // tag type. Note that this does does not apply if we're declaring a
414   // typedef (C++ [dcl.typedef]p4).
415   if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
416     PrevDecl = 0;
417   bool Redeclaration = false;
418   bool OverloadableAttrRequired = false;
419   SemaRef.CheckFunctionDeclaration(Method, PrevDecl, Redeclaration,
420                                    /*FIXME:*/OverloadableAttrRequired);
421 
422   if (!Method->isInvalidDecl() || !PrevDecl)
423     Owner->addDecl(Method);
424   return Method;
425 }
426 
427 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
428   // FIXME: Look for existing, explicit specializations.
429   Sema::LocalInstantiationScope Scope(SemaRef);
430 
431   llvm::SmallVector<ParmVarDecl *, 4> Params;
432   QualType T = InstantiateFunctionType(D, Params);
433   if (T.isNull())
434     return 0;
435 
436   // Build the instantiated method declaration.
437   CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
438   QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
439   DeclarationName Name
440     = SemaRef.Context.DeclarationNames.getCXXConstructorName(
441                                  SemaRef.Context.getCanonicalType(ClassTy));
442   CXXConstructorDecl *Constructor
443     = CXXConstructorDecl::Create(SemaRef.Context, Record, D->getLocation(),
444                                  Name, T, D->isExplicit(), D->isInline(),
445                                  false);
446   Constructor->setInstantiationOfMemberFunction(D);
447 
448   // Attach the parameters
449   for (unsigned P = 0; P < Params.size(); ++P)
450     Params[P]->setOwningFunction(Constructor);
451   Constructor->setParams(SemaRef.Context, Params.data(), Params.size());
452 
453   if (InitMethodInstantiation(Constructor, D))
454     Constructor->setInvalidDecl();
455 
456   NamedDecl *PrevDecl
457     = SemaRef.LookupQualifiedName(Owner, Name, Sema::LookupOrdinaryName, true);
458 
459   // In C++, the previous declaration we find might be a tag type
460   // (class or enum). In this case, the new declaration will hide the
461   // tag type. Note that this does does not apply if we're declaring a
462   // typedef (C++ [dcl.typedef]p4).
463   if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
464     PrevDecl = 0;
465   bool Redeclaration = false;
466   bool OverloadableAttrRequired = false;
467   SemaRef.CheckFunctionDeclaration(Constructor, PrevDecl, Redeclaration,
468                                    /*FIXME:*/OverloadableAttrRequired);
469 
470   Record->addedConstructor(SemaRef.Context, Constructor);
471   Owner->addDecl(Constructor);
472   return Constructor;
473 }
474 
475 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
476   // FIXME: Look for existing, explicit specializations.
477   Sema::LocalInstantiationScope Scope(SemaRef);
478 
479   llvm::SmallVector<ParmVarDecl *, 4> Params;
480   QualType T = InstantiateFunctionType(D, Params);
481   if (T.isNull())
482     return 0;
483   assert(Params.size() == 0 && "Destructor with parameters?");
484 
485   // Build the instantiated destructor declaration.
486   CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
487   QualType ClassTy =
488     SemaRef.Context.getCanonicalType(SemaRef.Context.getTypeDeclType(Record));
489   CXXDestructorDecl *Destructor
490     = CXXDestructorDecl::Create(SemaRef.Context, Record,
491                                 D->getLocation(),
492              SemaRef.Context.DeclarationNames.getCXXDestructorName(ClassTy),
493                                 T, D->isInline(), false);
494   Destructor->setInstantiationOfMemberFunction(D);
495   if (InitMethodInstantiation(Destructor, D))
496     Destructor->setInvalidDecl();
497 
498   bool Redeclaration = false;
499   bool OverloadableAttrRequired = false;
500   NamedDecl *PrevDecl = 0;
501   SemaRef.CheckFunctionDeclaration(Destructor, PrevDecl, Redeclaration,
502                                    /*FIXME:*/OverloadableAttrRequired);
503   Owner->addDecl(Destructor);
504   return Destructor;
505 }
506 
507 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
508   // FIXME: Look for existing, explicit specializations.
509   Sema::LocalInstantiationScope Scope(SemaRef);
510 
511   llvm::SmallVector<ParmVarDecl *, 4> Params;
512   QualType T = InstantiateFunctionType(D, Params);
513   if (T.isNull())
514     return 0;
515   assert(Params.size() == 0 && "Destructor with parameters?");
516 
517   // Build the instantiated conversion declaration.
518   CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
519   QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
520   QualType ConvTy
521     = SemaRef.Context.getCanonicalType(T->getAsFunctionType()->getResultType());
522   CXXConversionDecl *Conversion
523     = CXXConversionDecl::Create(SemaRef.Context, Record,
524                                 D->getLocation(),
525          SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(ConvTy),
526                                 T, D->isInline(), D->isExplicit());
527   Conversion->setInstantiationOfMemberFunction(D);
528   if (InitMethodInstantiation(Conversion, D))
529     Conversion->setInvalidDecl();
530 
531   bool Redeclaration = false;
532   bool OverloadableAttrRequired = false;
533   NamedDecl *PrevDecl = 0;
534   SemaRef.CheckFunctionDeclaration(Conversion, PrevDecl, Redeclaration,
535                                    /*FIXME:*/OverloadableAttrRequired);
536   Owner->addDecl(Conversion);
537   return Conversion;
538 }
539 
540 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
541   QualType OrigT = SemaRef.InstantiateType(D->getOriginalType(), TemplateArgs,
542                                            D->getLocation(), D->getDeclName());
543   if (OrigT.isNull())
544     return 0;
545 
546   QualType T = SemaRef.adjustParameterType(OrigT);
547 
548   if (D->getDefaultArg()) {
549     // FIXME: Leave a marker for "uninstantiated" default
550     // arguments. They only get instantiated on demand at the call
551     // site.
552     unsigned DiagID = SemaRef.Diags.getCustomDiagID(Diagnostic::Warning,
553         "sorry, dropping default argument during template instantiation");
554     SemaRef.Diag(D->getDefaultArg()->getSourceRange().getBegin(), DiagID)
555       << D->getDefaultArg()->getSourceRange();
556   }
557 
558   // Allocate the parameter
559   ParmVarDecl *Param = 0;
560   if (T == OrigT)
561     Param = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(),
562                                 D->getIdentifier(), T, D->getStorageClass(),
563                                 0);
564   else
565     Param = OriginalParmVarDecl::Create(SemaRef.Context, Owner,
566                                         D->getLocation(), D->getIdentifier(),
567                                         T, OrigT, D->getStorageClass(), 0);
568 
569   // Note: we don't try to instantiate function parameters until after
570   // we've instantiated the function's type. Therefore, we don't have
571   // to check for 'void' parameter types here.
572   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
573   return Param;
574 }
575 
576 Decl *
577 TemplateDeclInstantiator::VisitOriginalParmVarDecl(OriginalParmVarDecl *D) {
578   // Since parameter types can decay either before or after
579   // instantiation, we simply treat OriginalParmVarDecls as
580   // ParmVarDecls the same way, and create one or the other depending
581   // on what happens after template instantiation.
582   return VisitParmVarDecl(D);
583 }
584 
585 Decl *Sema::InstantiateDecl(Decl *D, DeclContext *Owner,
586                             const TemplateArgumentList &TemplateArgs) {
587   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
588   return Instantiator.Visit(D);
589 }
590 
591 /// \brief Instantiates the type of the given function, including
592 /// instantiating all of the function parameters.
593 ///
594 /// \param D The function that we will be instantiated
595 ///
596 /// \param Params the instantiated parameter declarations
597 
598 /// \returns the instantiated function's type if successfull, a NULL
599 /// type if there was an error.
600 QualType
601 TemplateDeclInstantiator::InstantiateFunctionType(FunctionDecl *D,
602                               llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
603   bool InvalidDecl = false;
604 
605   // Instantiate the function parameters
606   TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs);
607   llvm::SmallVector<QualType, 4> ParamTys;
608   for (FunctionDecl::param_iterator P = D->param_begin(),
609                                  PEnd = D->param_end();
610        P != PEnd; ++P) {
611     if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) {
612       if (PInst->getType()->isVoidType()) {
613         SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type);
614         PInst->setInvalidDecl();
615       }
616       else if (SemaRef.RequireNonAbstractType(PInst->getLocation(),
617                                               PInst->getType(),
618                                               diag::err_abstract_type_in_decl,
619                                               Sema::AbstractParamType))
620         PInst->setInvalidDecl();
621 
622       Params.push_back(PInst);
623       ParamTys.push_back(PInst->getType());
624 
625       if (PInst->isInvalidDecl())
626         InvalidDecl = true;
627     } else
628       InvalidDecl = true;
629   }
630 
631   // FIXME: Deallocate dead declarations.
632   if (InvalidDecl)
633     return QualType();
634 
635   const FunctionProtoType *Proto = D->getType()->getAsFunctionProtoType();
636   assert(Proto && "Missing prototype?");
637   QualType ResultType
638     = SemaRef.InstantiateType(Proto->getResultType(), TemplateArgs,
639                               D->getLocation(), D->getDeclName());
640   if (ResultType.isNull())
641     return QualType();
642 
643   return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(),
644                                    Proto->isVariadic(), Proto->getTypeQuals(),
645                                    D->getLocation(), D->getDeclName());
646 }
647 
648 /// \brief Initializes the common fields of an instantiation function
649 /// declaration (New) from the corresponding fields of its template (Tmpl).
650 ///
651 /// \returns true if there was an error
652 bool
653 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
654                                                     FunctionDecl *Tmpl) {
655   if (Tmpl->isDeleted())
656     New->setDeleted();
657 
658   // If we are performing substituting explicitly-specified template arguments
659   // or deduced template arguments into a function template and we reach this
660   // point, we are now past the point where SFINAE applies and have committed
661   // to keeping the new function template specialization. We therefore
662   // convert the active template instantiation for the function template
663   // into a template instantiation for this specific function template
664   // specialization, which is not a SFINAE context, so that we diagnose any
665   // further errors in the declaration itself.
666   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
667   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
668   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
669       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
670     if (FunctionTemplateDecl *FunTmpl
671           = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
672       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
673              "Deduction from the wrong function template?");
674       (void) FunTmpl;
675       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
676       ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
677     }
678   }
679 
680   return false;
681 }
682 
683 /// \brief Initializes common fields of an instantiated method
684 /// declaration (New) from the corresponding fields of its template
685 /// (Tmpl).
686 ///
687 /// \returns true if there was an error
688 bool
689 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
690                                                   CXXMethodDecl *Tmpl) {
691   if (InitFunctionInstantiation(New, Tmpl))
692     return true;
693 
694   CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
695   New->setAccess(Tmpl->getAccess());
696   if (Tmpl->isVirtualAsWritten()) {
697     New->setVirtualAsWritten(true);
698     Record->setAggregate(false);
699     Record->setPOD(false);
700     Record->setPolymorphic(true);
701   }
702   if (Tmpl->isPure()) {
703     New->setPure();
704     Record->setAbstract(true);
705   }
706 
707   // FIXME: attributes
708   // FIXME: New needs a pointer to Tmpl
709   return false;
710 }
711 
712 /// \brief Instantiate the definition of the given function from its
713 /// template.
714 ///
715 /// \param PointOfInstantiation the point at which the instantiation was
716 /// required. Note that this is not precisely a "point of instantiation"
717 /// for the function, but it's close.
718 ///
719 /// \param Function the already-instantiated declaration of a
720 /// function template specialization or member function of a class template
721 /// specialization.
722 ///
723 /// \param Recursive if true, recursively instantiates any functions that
724 /// are required by this instantiation.
725 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
726                                          FunctionDecl *Function,
727                                          bool Recursive) {
728   if (Function->isInvalidDecl())
729     return;
730 
731   assert(!Function->getBody() && "Already instantiated!");
732 
733   // Find the function body that we'll be substituting.
734   const FunctionDecl *PatternDecl = 0;
735   if (FunctionTemplateDecl *Primary = Function->getPrimaryTemplate())
736     PatternDecl = Primary->getTemplatedDecl();
737   else
738     PatternDecl = Function->getInstantiatedFromMemberFunction();
739   Stmt *Pattern = 0;
740   if (PatternDecl)
741     Pattern = PatternDecl->getBody(PatternDecl);
742 
743   if (!Pattern)
744     return;
745 
746   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
747   if (Inst)
748     return;
749 
750   // If we're performing recursive template instantiation, create our own
751   // queue of pending implicit instantiations that we will instantiate later,
752   // while we're still within our own instantiation context.
753   std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
754   if (Recursive)
755     PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
756 
757   ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
758 
759   // Introduce a new scope where local variable instantiations will be
760   // recorded.
761   LocalInstantiationScope Scope(*this);
762 
763   // Introduce the instantiated function parameters into the local
764   // instantiation scope.
765   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
766     Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
767                             Function->getParamDecl(I));
768 
769   // Enter the scope of this instantiation. We don't use
770   // PushDeclContext because we don't have a scope.
771   DeclContext *PreviousContext = CurContext;
772   CurContext = Function;
773 
774   // Instantiate the function body.
775   OwningStmtResult Body
776     = InstantiateStmt(Pattern, getTemplateInstantiationArgs(Function));
777 
778   ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
779                           /*IsInstantiation=*/true);
780 
781   CurContext = PreviousContext;
782 
783   DeclGroupRef DG(Function);
784   Consumer.HandleTopLevelDecl(DG);
785 
786   if (Recursive) {
787     // Instantiate any pending implicit instantiations found during the
788     // instantiation of this template.
789     PerformPendingImplicitInstantiations();
790 
791     // Restore the set of pending implicit instantiations.
792     PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
793   }
794 }
795 
796 /// \brief Instantiate the definition of the given variable from its
797 /// template.
798 ///
799 /// \param PointOfInstantiation the point at which the instantiation was
800 /// required. Note that this is not precisely a "point of instantiation"
801 /// for the function, but it's close.
802 ///
803 /// \param Var the already-instantiated declaration of a static member
804 /// variable of a class template specialization.
805 ///
806 /// \param Recursive if true, recursively instantiates any functions that
807 /// are required by this instantiation.
808 void Sema::InstantiateStaticDataMemberDefinition(
809                                           SourceLocation PointOfInstantiation,
810                                                  VarDecl *Var,
811                                                  bool Recursive) {
812   if (Var->isInvalidDecl())
813     return;
814 
815   // Find the out-of-line definition of this static data member.
816   // FIXME: Do we have to look for specializations separately?
817   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
818   bool FoundOutOfLineDef = false;
819   assert(Def && "This data member was not instantiated from a template?");
820   assert(Def->isStaticDataMember() && "Not a static data member?");
821   for (VarDecl::redecl_iterator RD = Def->redecls_begin(),
822                              RDEnd = Def->redecls_end();
823        RD != RDEnd; ++RD) {
824     if (RD->getLexicalDeclContext()->isFileContext()) {
825       Def = *RD;
826       FoundOutOfLineDef = true;
827     }
828   }
829 
830   if (!FoundOutOfLineDef) {
831     // We did not find an out-of-line definition of this static data member,
832     // so we won't perform any instantiation. Rather, we rely on the user to
833     // instantiate this definition (or provide a specialization for it) in
834     // another translation unit.
835     return;
836   }
837 
838   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
839   if (Inst)
840     return;
841 
842   // If we're performing recursive template instantiation, create our own
843   // queue of pending implicit instantiations that we will instantiate later,
844   // while we're still within our own instantiation context.
845   std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
846   if (Recursive)
847     PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
848 
849   // Enter the scope of this instantiation. We don't use
850   // PushDeclContext because we don't have a scope.
851   DeclContext *PreviousContext = CurContext;
852   CurContext = Var->getDeclContext();
853 
854 #if 0
855   // Instantiate the initializer of this static data member.
856   OwningExprResult Init
857     = InstantiateExpr(Def->getInit(), getTemplateInstantiationArgs(Var));
858   if (Init.isInvalid()) {
859     // If instantiation of the initializer failed, mark the declaration invalid
860     // and don't instantiate anything else that was triggered by this
861     // instantiation.
862     Var->setInvalidDecl();
863 
864     // Restore the set of pending implicit instantiations.
865     PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
866 
867     return;
868   }
869 
870   // Type-check the initializer.
871   if (Init.get())
872     AddInitializerToDecl(DeclPtrTy::make(Var), move(Init),
873                          Def->hasCXXDirectInitializer());
874   else
875     ActOnUninitializedDecl(DeclPtrTy::make(Var), false);
876 #else
877   Var = cast_or_null<VarDecl>(InstantiateDecl(Def, Var->getDeclContext(),
878                                           getTemplateInstantiationArgs(Var)));
879 #endif
880 
881   CurContext = PreviousContext;
882 
883   if (Var) {
884     DeclGroupRef DG(Var);
885     Consumer.HandleTopLevelDecl(DG);
886   }
887 
888   if (Recursive) {
889     // Instantiate any pending implicit instantiations found during the
890     // instantiation of this template.
891     PerformPendingImplicitInstantiations();
892 
893     // Restore the set of pending implicit instantiations.
894     PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
895   }
896 }
897 
898 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
899   if (D->getKind() != Other->getKind())
900     return false;
901 
902   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
903     return Record->getInstantiatedFromMemberClass()->getCanonicalDecl()
904              == D->getCanonicalDecl();
905 
906   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
907     return Function->getInstantiatedFromMemberFunction()->getCanonicalDecl()
908              == D->getCanonicalDecl();
909 
910   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
911     return Enum->getInstantiatedFromMemberEnum()->getCanonicalDecl()
912              == D->getCanonicalDecl();
913 
914   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
915     if (Var->isStaticDataMember())
916       return Var->getInstantiatedFromStaticDataMember()->getCanonicalDecl()
917                == D->getCanonicalDecl();
918 
919   // FIXME: How can we find instantiations of anonymous unions?
920 
921   return D->getDeclName() && isa<NamedDecl>(Other) &&
922     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
923 }
924 
925 template<typename ForwardIterator>
926 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
927                                       NamedDecl *D,
928                                       ForwardIterator first,
929                                       ForwardIterator last) {
930   for (; first != last; ++first)
931     if (isInstantiationOf(Ctx, D, *first))
932       return cast<NamedDecl>(*first);
933 
934   return 0;
935 }
936 
937 /// \brief Find the instantiation of the given declaration within the
938 /// current instantiation.
939 ///
940 /// This routine is intended to be used when \p D is a declaration
941 /// referenced from within a template, that needs to mapped into the
942 /// corresponding declaration within an instantiation. For example,
943 /// given:
944 ///
945 /// \code
946 /// template<typename T>
947 /// struct X {
948 ///   enum Kind {
949 ///     KnownValue = sizeof(T)
950 ///   };
951 ///
952 ///   bool getKind() const { return KnownValue; }
953 /// };
954 ///
955 /// template struct X<int>;
956 /// \endcode
957 ///
958 /// In the instantiation of X<int>::getKind(), we need to map the
959 /// EnumConstantDecl for KnownValue (which refers to
960 /// X<T>::<Kind>::KnownValue) to its instantiation
961 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
962 /// this mapping from within the instantiation of X<int>.
963 NamedDecl * Sema::InstantiateCurrentDeclRef(NamedDecl *D) {
964   DeclContext *ParentDC = D->getDeclContext();
965   if (isa<ParmVarDecl>(D) || ParentDC->isFunctionOrMethod()) {
966     // D is a local of some kind. Look into the map of local
967     // declarations to their instantiations.
968     return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
969   }
970 
971   if (NamedDecl *ParentDecl = dyn_cast<NamedDecl>(ParentDC)) {
972     ParentDecl = InstantiateCurrentDeclRef(ParentDecl);
973     if (!ParentDecl)
974       return 0;
975 
976     ParentDC = cast<DeclContext>(ParentDecl);
977   }
978 
979   if (ParentDC != D->getDeclContext()) {
980     // We performed some kind of instantiation in the parent context,
981     // so now we need to look into the instantiated parent context to
982     // find the instantiation of the declaration D.
983     NamedDecl *Result = 0;
984     if (D->getDeclName()) {
985       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
986       Result = findInstantiationOf(Context, D, Found.first, Found.second);
987     } else {
988       // Since we don't have a name for the entity we're looking for,
989       // our only option is to walk through all of the declarations to
990       // find that name. This will occur in a few cases:
991       //
992       //   - anonymous struct/union within a template
993       //   - unnamed class/struct/union/enum within a template
994       //
995       // FIXME: Find a better way to find these instantiations!
996       Result = findInstantiationOf(Context, D,
997                                    ParentDC->decls_begin(),
998                                    ParentDC->decls_end());
999     }
1000     assert(Result && "Unable to find instantiation of declaration!");
1001     D = Result;
1002   }
1003 
1004   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
1005     if (ClassTemplateDecl *ClassTemplate
1006           = Record->getDescribedClassTemplate()) {
1007       // When the declaration D was parsed, it referred to the current
1008       // instantiation. Therefore, look through the current context,
1009       // which contains actual instantiations, to find the
1010       // instantiation of the "current instantiation" that D refers
1011       // to. Alternatively, we could just instantiate the
1012       // injected-class-name with the current template arguments, but
1013       // such an instantiation is far more expensive.
1014       for (DeclContext *DC = CurContext; !DC->isFileContext();
1015            DC = DC->getParent()) {
1016         if (ClassTemplateSpecializationDecl *Spec
1017               = dyn_cast<ClassTemplateSpecializationDecl>(DC))
1018           if (Spec->getSpecializedTemplate()->getCanonicalDecl()
1019               == ClassTemplate->getCanonicalDecl())
1020             return Spec;
1021       }
1022 
1023       assert(false &&
1024              "Unable to find declaration for the current instantiation");
1025     }
1026 
1027   return D;
1028 }
1029 
1030 /// \brief Performs template instantiation for all implicit template
1031 /// instantiations we have seen until this point.
1032 void Sema::PerformPendingImplicitInstantiations() {
1033   while (!PendingImplicitInstantiations.empty()) {
1034     PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front();
1035     PendingImplicitInstantiations.pop_front();
1036 
1037     // Instantiate function definitions
1038     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
1039       if (!Function->getBody())
1040         InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
1041       continue;
1042     }
1043 
1044     // Instantiate static data member definitions.
1045     VarDecl *Var = cast<VarDecl>(Inst.first);
1046     assert(Var->isStaticDataMember() && "Not a static data member?");
1047     InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
1048   }
1049 }
1050