SemaTemplateInstantiate.cpp revision 194711
1//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
10//
11//===----------------------------------------------------------------------===/
12
13#include "Sema.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20#include "llvm/Support/Compiler.h"
21
22using namespace clang;
23
24//===----------------------------------------------------------------------===/
25// Template Instantiation Support
26//===----------------------------------------------------------------------===/
27
28/// \brief Retrieve the template argument list that should be used to
29/// instantiate the given declaration.
30const TemplateArgumentList &
31Sema::getTemplateInstantiationArgs(NamedDecl *D) {
32  if (ClassTemplateSpecializationDecl *Spec
33        = dyn_cast<ClassTemplateSpecializationDecl>(D))
34    return Spec->getTemplateArgs();
35
36  DeclContext *EnclosingTemplateCtx = D->getDeclContext();
37  while (!isa<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx)) {
38    assert(!EnclosingTemplateCtx->isFileContext() &&
39           "Tried to get the instantiation arguments of a non-template");
40    EnclosingTemplateCtx = EnclosingTemplateCtx->getParent();
41  }
42
43  ClassTemplateSpecializationDecl *EnclosingTemplate
44    = cast<ClassTemplateSpecializationDecl>(EnclosingTemplateCtx);
45  return EnclosingTemplate->getTemplateArgs();
46}
47
48Sema::InstantiatingTemplate::
49InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
50                      Decl *Entity,
51                      SourceRange InstantiationRange)
52  :  SemaRef(SemaRef) {
53
54  Invalid = CheckInstantiationDepth(PointOfInstantiation,
55                                    InstantiationRange);
56  if (!Invalid) {
57    ActiveTemplateInstantiation Inst;
58    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
59    Inst.PointOfInstantiation = PointOfInstantiation;
60    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
61    Inst.TemplateArgs = 0;
62    Inst.NumTemplateArgs = 0;
63    Inst.InstantiationRange = InstantiationRange;
64    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
65    Invalid = false;
66  }
67}
68
69Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
70                                         SourceLocation PointOfInstantiation,
71                                         TemplateDecl *Template,
72                                         const TemplateArgument *TemplateArgs,
73                                         unsigned NumTemplateArgs,
74                                         SourceRange InstantiationRange)
75  : SemaRef(SemaRef) {
76
77  Invalid = CheckInstantiationDepth(PointOfInstantiation,
78                                    InstantiationRange);
79  if (!Invalid) {
80    ActiveTemplateInstantiation Inst;
81    Inst.Kind
82      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
83    Inst.PointOfInstantiation = PointOfInstantiation;
84    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
85    Inst.TemplateArgs = TemplateArgs;
86    Inst.NumTemplateArgs = NumTemplateArgs;
87    Inst.InstantiationRange = InstantiationRange;
88    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
89    Invalid = false;
90  }
91}
92
93Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
94                                         SourceLocation PointOfInstantiation,
95                          ClassTemplatePartialSpecializationDecl *PartialSpec,
96                                         const TemplateArgument *TemplateArgs,
97                                         unsigned NumTemplateArgs,
98                                         SourceRange InstantiationRange)
99  : SemaRef(SemaRef) {
100
101  Invalid = CheckInstantiationDepth(PointOfInstantiation,
102                                    InstantiationRange);
103  if (!Invalid) {
104    ActiveTemplateInstantiation Inst;
105    Inst.Kind
106      = ActiveTemplateInstantiation::PartialSpecDeductionInstantiation;
107    Inst.PointOfInstantiation = PointOfInstantiation;
108    Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
109    Inst.TemplateArgs = TemplateArgs;
110    Inst.NumTemplateArgs = NumTemplateArgs;
111    Inst.InstantiationRange = InstantiationRange;
112    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
113    Invalid = false;
114  }
115}
116
117void Sema::InstantiatingTemplate::Clear() {
118  if (!Invalid) {
119    SemaRef.ActiveTemplateInstantiations.pop_back();
120    Invalid = true;
121  }
122}
123
124bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
125                                        SourceLocation PointOfInstantiation,
126                                           SourceRange InstantiationRange) {
127  if (SemaRef.ActiveTemplateInstantiations.size()
128       <= SemaRef.getLangOptions().InstantiationDepth)
129    return false;
130
131  SemaRef.Diag(PointOfInstantiation,
132               diag::err_template_recursion_depth_exceeded)
133    << SemaRef.getLangOptions().InstantiationDepth
134    << InstantiationRange;
135  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
136    << SemaRef.getLangOptions().InstantiationDepth;
137  return true;
138}
139
140/// \brief Prints the current instantiation stack through a series of
141/// notes.
142void Sema::PrintInstantiationStack() {
143  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
144         Active = ActiveTemplateInstantiations.rbegin(),
145         ActiveEnd = ActiveTemplateInstantiations.rend();
146       Active != ActiveEnd;
147       ++Active) {
148    switch (Active->Kind) {
149    case ActiveTemplateInstantiation::TemplateInstantiation: {
150      Decl *D = reinterpret_cast<Decl *>(Active->Entity);
151      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
152        unsigned DiagID = diag::note_template_member_class_here;
153        if (isa<ClassTemplateSpecializationDecl>(Record))
154          DiagID = diag::note_template_class_instantiation_here;
155        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
156                     DiagID)
157          << Context.getTypeDeclType(Record)
158          << Active->InstantiationRange;
159      } else {
160        FunctionDecl *Function = cast<FunctionDecl>(D);
161        unsigned DiagID = diag::note_template_member_function_here;
162        // FIXME: check for a function template
163        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
164                     DiagID)
165          << Function
166          << Active->InstantiationRange;
167      }
168      break;
169    }
170
171    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
172      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
173      std::string TemplateArgsStr
174        = TemplateSpecializationType::PrintTemplateArgumentList(
175                                                      Active->TemplateArgs,
176                                                      Active->NumTemplateArgs,
177                                                      Context.PrintingPolicy);
178      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
179                   diag::note_default_arg_instantiation_here)
180        << (Template->getNameAsString() + TemplateArgsStr)
181        << Active->InstantiationRange;
182      break;
183    }
184
185    case ActiveTemplateInstantiation::PartialSpecDeductionInstantiation: {
186      ClassTemplatePartialSpecializationDecl *PartialSpec
187        = cast<ClassTemplatePartialSpecializationDecl>((Decl *)Active->Entity);
188      // FIXME: The active template instantiation's template arguments
189      // are interesting, too. We should add something like [with T =
190      // foo, U = bar, etc.] to the string.
191      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
192                   diag::note_partial_spec_deduct_instantiation_here)
193        << Context.getTypeDeclType(PartialSpec)
194        << Active->InstantiationRange;
195      break;
196    }
197
198    }
199  }
200}
201
202bool Sema::isSFINAEContext() const {
203  using llvm::SmallVector;
204  for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
205         Active = ActiveTemplateInstantiations.rbegin(),
206         ActiveEnd = ActiveTemplateInstantiations.rend();
207       Active != ActiveEnd;
208       ++Active) {
209
210    switch(Active->Kind) {
211    case ActiveTemplateInstantiation::PartialSpecDeductionInstantiation:
212      // We're in a template argument deduction context, so SFINAE
213      // applies.
214      return true;
215
216    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
217      // A default template argument instantiation may or may not be a
218      // SFINAE context; look further up the stack.
219      break;
220
221    case ActiveTemplateInstantiation::TemplateInstantiation:
222      // This is a template instantiation, so there is no SFINAE.
223      return false;
224    }
225  }
226
227  return false;
228}
229
230//===----------------------------------------------------------------------===/
231// Template Instantiation for Types
232//===----------------------------------------------------------------------===/
233namespace {
234  class VISIBILITY_HIDDEN TemplateTypeInstantiator {
235    Sema &SemaRef;
236    const TemplateArgumentList &TemplateArgs;
237    SourceLocation Loc;
238    DeclarationName Entity;
239
240  public:
241    TemplateTypeInstantiator(Sema &SemaRef,
242                             const TemplateArgumentList &TemplateArgs,
243                             SourceLocation Loc,
244                             DeclarationName Entity)
245      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
246        Loc(Loc), Entity(Entity) { }
247
248    QualType operator()(QualType T) const { return Instantiate(T); }
249
250    QualType Instantiate(QualType T) const;
251
252    // Declare instantiate functions for each type.
253#define TYPE(Class, Base)                                       \
254    QualType Instantiate##Class##Type(const Class##Type *T,     \
255                                      unsigned Quals) const;
256#define ABSTRACT_TYPE(Class, Base)
257#include "clang/AST/TypeNodes.def"
258  };
259}
260
261QualType
262TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
263                                                 unsigned Quals) const {
264  // FIXME: Implement this
265  assert(false && "Cannot instantiate ExtQualType yet");
266  return QualType();
267}
268
269QualType
270TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
271                                                 unsigned Quals) const {
272  assert(false && "Builtin types are not dependent and cannot be instantiated");
273  return QualType(T, Quals);
274}
275
276QualType
277TemplateTypeInstantiator::
278InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
279  // FIXME: Implement this
280  assert(false && "Cannot instantiate FixedWidthIntType yet");
281  return QualType();
282}
283
284QualType
285TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
286                                                 unsigned Quals) const {
287  // FIXME: Implement this
288  assert(false && "Cannot instantiate ComplexType yet");
289  return QualType();
290}
291
292QualType
293TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
294                                                 unsigned Quals) const {
295  QualType PointeeType = Instantiate(T->getPointeeType());
296  if (PointeeType.isNull())
297    return QualType();
298
299  return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
300}
301
302QualType
303TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
304                                                      unsigned Quals) const {
305  QualType PointeeType = Instantiate(T->getPointeeType());
306  if (PointeeType.isNull())
307    return QualType();
308
309  return SemaRef.BuildBlockPointerType(PointeeType, Quals, Loc, Entity);
310}
311
312QualType
313TemplateTypeInstantiator::InstantiateLValueReferenceType(
314    const LValueReferenceType *T, unsigned Quals) const {
315  QualType ReferentType = Instantiate(T->getPointeeType());
316  if (ReferentType.isNull())
317    return QualType();
318
319  return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity);
320}
321
322QualType
323TemplateTypeInstantiator::InstantiateRValueReferenceType(
324    const RValueReferenceType *T, unsigned Quals) const {
325  QualType ReferentType = Instantiate(T->getPointeeType());
326  if (ReferentType.isNull())
327    return QualType();
328
329  return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity);
330}
331
332QualType
333TemplateTypeInstantiator::
334InstantiateMemberPointerType(const MemberPointerType *T,
335                             unsigned Quals) const {
336  QualType PointeeType = Instantiate(T->getPointeeType());
337  if (PointeeType.isNull())
338    return QualType();
339
340  QualType ClassType = Instantiate(QualType(T->getClass(), 0));
341  if (ClassType.isNull())
342    return QualType();
343
344  return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Quals, Loc,
345                                        Entity);
346}
347
348QualType
349TemplateTypeInstantiator::
350InstantiateConstantArrayType(const ConstantArrayType *T,
351                             unsigned Quals) const {
352  QualType ElementType = Instantiate(T->getElementType());
353  if (ElementType.isNull())
354    return ElementType;
355
356  // Build a temporary integer literal to specify the size for
357  // BuildArrayType. Since we have already checked the size as part of
358  // creating the dependent array type in the first place, we know
359  // there aren't any errors. However, we do need to determine what
360  // C++ type to give the size expression.
361  llvm::APInt Size = T->getSize();
362  QualType Types[] = {
363    SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
364    SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
365    SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
366  };
367  const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
368  QualType SizeType;
369  for (unsigned I = 0; I != NumTypes; ++I)
370    if (Size.getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
371      SizeType = Types[I];
372      break;
373    }
374
375  if (SizeType.isNull())
376    SizeType = SemaRef.Context.getFixedWidthIntType(Size.getBitWidth(), false);
377
378  IntegerLiteral ArraySize(Size, SizeType, Loc);
379  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
380                                &ArraySize, T->getIndexTypeQualifier(),
381                                Loc, Entity);
382}
383
384QualType
385TemplateTypeInstantiator::
386InstantiateIncompleteArrayType(const IncompleteArrayType *T,
387                               unsigned Quals) const {
388  QualType ElementType = Instantiate(T->getElementType());
389  if (ElementType.isNull())
390    return ElementType;
391
392  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
393                                0, T->getIndexTypeQualifier(),
394                                Loc, Entity);
395}
396
397QualType
398TemplateTypeInstantiator::
399InstantiateVariableArrayType(const VariableArrayType *T,
400                             unsigned Quals) const {
401  // FIXME: Implement this
402  assert(false && "Cannot instantiate VariableArrayType yet");
403  return QualType();
404}
405
406QualType
407TemplateTypeInstantiator::
408InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
409                                   unsigned Quals) const {
410  Expr *ArraySize = T->getSizeExpr();
411  assert(ArraySize->isValueDependent() &&
412         "dependent sized array types must have value dependent size expr");
413
414  // Instantiate the element type if needed
415  QualType ElementType = T->getElementType();
416  if (ElementType->isDependentType()) {
417    ElementType = Instantiate(ElementType);
418    if (ElementType.isNull())
419      return QualType();
420  }
421
422  // Instantiate the size expression
423  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
424  Sema::OwningExprResult InstantiatedArraySize =
425    SemaRef.InstantiateExpr(ArraySize, TemplateArgs);
426  if (InstantiatedArraySize.isInvalid())
427    return QualType();
428
429  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
430                                InstantiatedArraySize.takeAs<Expr>(),
431                                T->getIndexTypeQualifier(), Loc, Entity);
432}
433
434QualType
435TemplateTypeInstantiator::
436InstantiateDependentSizedExtVectorType(const DependentSizedExtVectorType *T,
437                                   unsigned Quals) const {
438
439  // Instantiate the element type if needed.
440  QualType ElementType = T->getElementType();
441  if (ElementType->isDependentType()) {
442    ElementType = Instantiate(ElementType);
443    if (ElementType.isNull())
444      return QualType();
445  }
446
447  // The expression in a dependent-sized extended vector type is not
448  // potentially evaluated.
449  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
450
451  // Instantiate the size expression.
452  const Expr *SizeExpr = T->getSizeExpr();
453  Sema::OwningExprResult InstantiatedArraySize =
454    SemaRef.InstantiateExpr(const_cast<Expr *>(SizeExpr), TemplateArgs);
455  if (InstantiatedArraySize.isInvalid())
456    return QualType();
457
458  return SemaRef.BuildExtVectorType(ElementType,
459                                    SemaRef.Owned(
460                                      InstantiatedArraySize.takeAs<Expr>()),
461                                    T->getAttributeLoc());
462}
463
464QualType
465TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
466                                             unsigned Quals) const {
467  // FIXME: Implement this
468  assert(false && "Cannot instantiate VectorType yet");
469  return QualType();
470}
471
472QualType
473TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
474                                                   unsigned Quals) const {
475  // FIXME: Implement this
476  assert(false && "Cannot instantiate ExtVectorType yet");
477  return QualType();
478}
479
480QualType
481TemplateTypeInstantiator::
482InstantiateFunctionProtoType(const FunctionProtoType *T,
483                             unsigned Quals) const {
484  QualType ResultType = Instantiate(T->getResultType());
485  if (ResultType.isNull())
486    return ResultType;
487
488  llvm::SmallVector<QualType, 4> ParamTypes;
489  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
490                                         ParamEnd = T->arg_type_end();
491       Param != ParamEnd; ++Param) {
492    QualType P = Instantiate(*Param);
493    if (P.isNull())
494      return P;
495
496    ParamTypes.push_back(P);
497  }
498
499  return SemaRef.BuildFunctionType(ResultType, ParamTypes.data(),
500                                   ParamTypes.size(),
501                                   T->isVariadic(), T->getTypeQuals(),
502                                   Loc, Entity);
503}
504
505QualType
506TemplateTypeInstantiator::
507InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
508                               unsigned Quals) const {
509  assert(false && "Functions without prototypes cannot be dependent.");
510  return QualType();
511}
512
513QualType
514TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
515                                                 unsigned Quals) const {
516  TypedefDecl *Typedef
517    = cast_or_null<TypedefDecl>(
518                           SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
519  if (!Typedef)
520    return QualType();
521
522  return SemaRef.Context.getTypeDeclType(Typedef);
523}
524
525QualType
526TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
527                                                    unsigned Quals) const {
528  // The expression in a typeof is not potentially evaluated.
529  EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
530
531  Sema::OwningExprResult E
532    = SemaRef.InstantiateExpr(T->getUnderlyingExpr(), TemplateArgs);
533  if (E.isInvalid())
534    return QualType();
535
536  return SemaRef.Context.getTypeOfExprType(E.takeAs<Expr>());
537}
538
539QualType
540TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
541                                                unsigned Quals) const {
542  QualType Underlying = Instantiate(T->getUnderlyingType());
543  if (Underlying.isNull())
544    return QualType();
545
546  return SemaRef.Context.getTypeOfType(Underlying);
547}
548
549QualType
550TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
551                                                unsigned Quals) const {
552  RecordDecl *Record
553    = cast_or_null<RecordDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
554  if (!Record)
555    return QualType();
556
557  return SemaRef.Context.getTypeDeclType(Record);
558}
559
560QualType
561TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
562                                              unsigned Quals) const {
563  EnumDecl *Enum
564    = cast_or_null<EnumDecl>(SemaRef.InstantiateCurrentDeclRef(T->getDecl()));
565  if (!Enum)
566    return QualType();
567
568  return SemaRef.Context.getTypeDeclType(Enum);
569}
570
571QualType
572TemplateTypeInstantiator::
573InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
574                                unsigned Quals) const {
575  if (T->getDepth() == 0) {
576    // Replace the template type parameter with its corresponding
577    // template argument.
578    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
579           "Template argument kind mismatch");
580    QualType Result = TemplateArgs[T->getIndex()].getAsType();
581    if (Result.isNull() || !Quals)
582      return Result;
583
584    // C++ [dcl.ref]p1:
585    //   [...] Cv-qualified references are ill-formed except when
586    //   the cv-qualifiers are introduced through the use of a
587    //   typedef (7.1.3) or of a template type argument (14.3), in
588    //   which case the cv-qualifiers are ignored.
589    if (Quals && Result->isReferenceType())
590      Quals = 0;
591
592    return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
593  }
594
595  // The template type parameter comes from an inner template (e.g.,
596  // the template parameter list of a member template inside the
597  // template we are instantiating). Create a new template type
598  // parameter with the template "level" reduced by one.
599  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
600                                                 T->getIndex(),
601                                                 T->isParameterPack(),
602                                                 T->getName())
603    .getQualifiedType(Quals);
604}
605
606QualType
607TemplateTypeInstantiator::
608InstantiateTemplateSpecializationType(
609                                  const TemplateSpecializationType *T,
610                                  unsigned Quals) const {
611  llvm::SmallVector<TemplateArgument, 4> InstantiatedTemplateArgs;
612  InstantiatedTemplateArgs.reserve(T->getNumArgs());
613  for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
614       Arg != ArgEnd; ++Arg) {
615    TemplateArgument InstArg = SemaRef.Instantiate(*Arg, TemplateArgs);
616    if (InstArg.isNull())
617      return QualType();
618
619    InstantiatedTemplateArgs.push_back(InstArg);
620  }
621
622  // FIXME: We're missing the locations of the template name, '<', and '>'.
623
624  TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
625                                                      Loc,
626                                                      TemplateArgs);
627
628  return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
629                                     InstantiatedTemplateArgs.data(),
630                                     InstantiatedTemplateArgs.size(),
631                                     SourceLocation());
632}
633
634QualType
635TemplateTypeInstantiator::
636InstantiateQualifiedNameType(const QualifiedNameType *T,
637                             unsigned Quals) const {
638  // When we instantiated a qualified name type, there's no point in
639  // keeping the qualification around in the instantiated result. So,
640  // just instantiate the named type.
641  return (*this)(T->getNamedType());
642}
643
644QualType
645TemplateTypeInstantiator::
646InstantiateTypenameType(const TypenameType *T, unsigned Quals) const {
647  if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
648    // When the typename type refers to a template-id, the template-id
649    // is dependent and has enough information to instantiate the
650    // result of the typename type. Since we don't care about keeping
651    // the spelling of the typename type in template instantiations,
652    // we just instantiate the template-id.
653    return InstantiateTemplateSpecializationType(TemplateId, Quals);
654  }
655
656  NestedNameSpecifier *NNS
657    = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
658                                             SourceRange(Loc),
659                                             TemplateArgs);
660  if (!NNS)
661    return QualType();
662
663  return SemaRef.CheckTypenameType(NNS, *T->getIdentifier(), SourceRange(Loc));
664}
665
666QualType
667TemplateTypeInstantiator::
668InstantiateObjCObjectPointerType(const ObjCObjectPointerType *T,
669                                 unsigned Quals) const {
670  assert(false && "Objective-C types cannot be dependent");
671  return QualType();
672}
673
674QualType
675TemplateTypeInstantiator::
676InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
677                             unsigned Quals) const {
678  assert(false && "Objective-C types cannot be dependent");
679  return QualType();
680}
681
682QualType
683TemplateTypeInstantiator::
684InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
685                                      unsigned Quals) const {
686  assert(false && "Objective-C types cannot be dependent");
687  return QualType();
688}
689
690/// \brief The actual implementation of Sema::InstantiateType().
691QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
692  // If T is not a dependent type, there is nothing to do.
693  if (!T->isDependentType())
694    return T;
695
696  switch (T->getTypeClass()) {
697#define TYPE(Class, Base)                                               \
698  case Type::Class:                                                     \
699    return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()),  \
700                                    T.getCVRQualifiers());
701#define ABSTRACT_TYPE(Class, Base)
702#include "clang/AST/TypeNodes.def"
703  }
704
705  assert(false && "Not all types have been decoded for instantiation");
706  return QualType();
707}
708
709/// \brief Instantiate the type T with a given set of template arguments.
710///
711/// This routine substitutes the given template arguments into the
712/// type T and produces the instantiated type.
713///
714/// \param T the type into which the template arguments will be
715/// substituted. If this type is not dependent, it will be returned
716/// immediately.
717///
718/// \param TemplateArgs the template arguments that will be
719/// substituted for the top-level template parameters within T.
720///
721/// \param Loc the location in the source code where this substitution
722/// is being performed. It will typically be the location of the
723/// declarator (if we're instantiating the type of some declaration)
724/// or the location of the type in the source code (if, e.g., we're
725/// instantiating the type of a cast expression).
726///
727/// \param Entity the name of the entity associated with a declaration
728/// being instantiated (if any). May be empty to indicate that there
729/// is no such entity (if, e.g., this is a type that occurs as part of
730/// a cast expression) or that the entity has no name (e.g., an
731/// unnamed function parameter).
732///
733/// \returns If the instantiation succeeds, the instantiated
734/// type. Otherwise, produces diagnostics and returns a NULL type.
735QualType Sema::InstantiateType(QualType T,
736                               const TemplateArgumentList &TemplateArgs,
737                               SourceLocation Loc, DeclarationName Entity) {
738  assert(!ActiveTemplateInstantiations.empty() &&
739         "Cannot perform an instantiation without some context on the "
740         "instantiation stack");
741
742  // If T is not a dependent type, there is nothing to do.
743  if (!T->isDependentType())
744    return T;
745
746  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
747  return Instantiator(T);
748}
749
750/// \brief Instantiate the base class specifiers of the given class
751/// template specialization.
752///
753/// Produces a diagnostic and returns true on error, returns false and
754/// attaches the instantiated base classes to the class template
755/// specialization if successful.
756bool
757Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
758                                CXXRecordDecl *Pattern,
759                                const TemplateArgumentList &TemplateArgs) {
760  bool Invalid = false;
761  llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
762  for (ClassTemplateSpecializationDecl::base_class_iterator
763         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
764       Base != BaseEnd; ++Base) {
765    if (!Base->getType()->isDependentType()) {
766      // FIXME: Allocate via ASTContext
767      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
768      continue;
769    }
770
771    QualType BaseType = InstantiateType(Base->getType(),
772                                        TemplateArgs,
773                                        Base->getSourceRange().getBegin(),
774                                        DeclarationName());
775    if (BaseType.isNull()) {
776      Invalid = true;
777      continue;
778    }
779
780    if (CXXBaseSpecifier *InstantiatedBase
781          = CheckBaseSpecifier(Instantiation,
782                               Base->getSourceRange(),
783                               Base->isVirtual(),
784                               Base->getAccessSpecifierAsWritten(),
785                               BaseType,
786                               /*FIXME: Not totally accurate */
787                               Base->getSourceRange().getBegin()))
788      InstantiatedBases.push_back(InstantiatedBase);
789    else
790      Invalid = true;
791  }
792
793  if (!Invalid &&
794      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
795                           InstantiatedBases.size()))
796    Invalid = true;
797
798  return Invalid;
799}
800
801/// \brief Instantiate the definition of a class from a given pattern.
802///
803/// \param PointOfInstantiation The point of instantiation within the
804/// source code.
805///
806/// \param Instantiation is the declaration whose definition is being
807/// instantiated. This will be either a class template specialization
808/// or a member class of a class template specialization.
809///
810/// \param Pattern is the pattern from which the instantiation
811/// occurs. This will be either the declaration of a class template or
812/// the declaration of a member class of a class template.
813///
814/// \param TemplateArgs The template arguments to be substituted into
815/// the pattern.
816///
817/// \returns true if an error occurred, false otherwise.
818bool
819Sema::InstantiateClass(SourceLocation PointOfInstantiation,
820                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
821                       const TemplateArgumentList &TemplateArgs,
822                       bool ExplicitInstantiation) {
823  bool Invalid = false;
824
825  CXXRecordDecl *PatternDef
826    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
827  if (!PatternDef) {
828    if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
829      Diag(PointOfInstantiation,
830           diag::err_implicit_instantiate_member_undefined)
831        << Context.getTypeDeclType(Instantiation);
832      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
833    } else {
834      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
835        << ExplicitInstantiation
836        << Context.getTypeDeclType(Instantiation);
837      Diag(Pattern->getLocation(), diag::note_template_decl_here);
838    }
839    return true;
840  }
841  Pattern = PatternDef;
842
843  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
844  if (Inst)
845    return true;
846
847  // Enter the scope of this instantiation. We don't use
848  // PushDeclContext because we don't have a scope.
849  DeclContext *PreviousContext = CurContext;
850  CurContext = Instantiation;
851
852  // Start the definition of this instantiation.
853  Instantiation->startDefinition();
854
855  // Instantiate the base class specifiers.
856  if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
857    Invalid = true;
858
859  llvm::SmallVector<DeclPtrTy, 4> Fields;
860  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(Context),
861         MemberEnd = Pattern->decls_end(Context);
862       Member != MemberEnd; ++Member) {
863    Decl *NewMember = InstantiateDecl(*Member, Instantiation, TemplateArgs);
864    if (NewMember) {
865      if (NewMember->isInvalidDecl())
866        Invalid = true;
867      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
868        Fields.push_back(DeclPtrTy::make(Field));
869    } else {
870      // FIXME: Eventually, a NULL return will mean that one of the
871      // instantiations was a semantic disaster, and we'll want to set Invalid =
872      // true. For now, we expect to skip some members that we can't yet handle.
873    }
874  }
875
876  // Finish checking fields.
877  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
878              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
879              0);
880
881  // Add any implicitly-declared members that we might need.
882  AddImplicitlyDeclaredMembersToClass(Instantiation);
883
884  // Exit the scope of this instantiation.
885  CurContext = PreviousContext;
886
887  if (!Invalid)
888    Consumer.HandleTagDeclDefinition(Instantiation);
889
890  // If this is an explicit instantiation, instantiate our members, too.
891  if (!Invalid && ExplicitInstantiation) {
892    Inst.Clear();
893    InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs);
894  }
895
896  return Invalid;
897}
898
899bool
900Sema::InstantiateClassTemplateSpecialization(
901                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
902                           bool ExplicitInstantiation) {
903  // Perform the actual instantiation on the canonical declaration.
904  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
905                               Context.getCanonicalDecl(ClassTemplateSpec));
906
907  // We can only instantiate something that hasn't already been
908  // instantiated or specialized. Fail without any diagnostics: our
909  // caller will provide an error message.
910  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
911    return true;
912
913  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
914  CXXRecordDecl *Pattern = Template->getTemplatedDecl();
915  const TemplateArgumentList *TemplateArgs
916    = &ClassTemplateSpec->getTemplateArgs();
917
918  // C++ [temp.class.spec.match]p1:
919  //   When a class template is used in a context that requires an
920  //   instantiation of the class, it is necessary to determine
921  //   whether the instantiation is to be generated using the primary
922  //   template or one of the partial specializations. This is done by
923  //   matching the template arguments of the class template
924  //   specialization with the template argument lists of the partial
925  //   specializations.
926  typedef std::pair<ClassTemplatePartialSpecializationDecl *,
927                    TemplateArgumentList *> MatchResult;
928  llvm::SmallVector<MatchResult, 4> Matched;
929  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
930         Partial = Template->getPartialSpecializations().begin(),
931         PartialEnd = Template->getPartialSpecializations().end();
932       Partial != PartialEnd;
933       ++Partial) {
934    TemplateDeductionInfo Info(Context);
935    if (TemplateDeductionResult Result
936          = DeduceTemplateArguments(&*Partial,
937                                    ClassTemplateSpec->getTemplateArgs(),
938                                    Info)) {
939      // FIXME: Store the failed-deduction information for use in
940      // diagnostics, later.
941      (void)Result;
942    } else {
943      Matched.push_back(std::make_pair(&*Partial, Info.take()));
944    }
945  }
946
947  if (Matched.size() == 1) {
948    //   -- If exactly one matching specialization is found, the
949    //      instantiation is generated from that specialization.
950    Pattern = Matched[0].first;
951    TemplateArgs = Matched[0].second;
952  } else if (Matched.size() > 1) {
953    //   -- If more than one matching specialization is found, the
954    //      partial order rules (14.5.4.2) are used to determine
955    //      whether one of the specializations is more specialized
956    //      than the others. If none of the specializations is more
957    //      specialized than all of the other matching
958    //      specializations, then the use of the class template is
959    //      ambiguous and the program is ill-formed.
960    // FIXME: Implement partial ordering of class template partial
961    // specializations.
962    Diag(ClassTemplateSpec->getLocation(),
963         diag::unsup_template_partial_spec_ordering);
964  } else {
965    //   -- If no matches are found, the instantiation is generated
966    //      from the primary template.
967
968    // Since we initialized the pattern and template arguments from
969    // the primary template, there is nothing more we need to do here.
970  }
971
972  // Note that this is an instantiation.
973  ClassTemplateSpec->setSpecializationKind(
974                        ExplicitInstantiation? TSK_ExplicitInstantiation
975                                             : TSK_ImplicitInstantiation);
976
977  bool Result = InstantiateClass(ClassTemplateSpec->getLocation(),
978                                 ClassTemplateSpec, Pattern, *TemplateArgs,
979                                 ExplicitInstantiation);
980
981  for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
982    // FIXME: Implement TemplateArgumentList::Destroy!
983    //    if (Matched[I].first != Pattern)
984    //      Matched[I].second->Destroy(Context);
985  }
986
987  return Result;
988}
989
990/// \brief Instantiate the definitions of all of the member of the
991/// given class, which is an instantiation of a class template or a
992/// member class of a template.
993void
994Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
995                              CXXRecordDecl *Instantiation,
996                              const TemplateArgumentList &TemplateArgs) {
997  for (DeclContext::decl_iterator D = Instantiation->decls_begin(Context),
998                               DEnd = Instantiation->decls_end(Context);
999       D != DEnd; ++D) {
1000    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1001      if (!Function->getBody(Context))
1002        InstantiateFunctionDefinition(PointOfInstantiation, Function);
1003    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1004      const VarDecl *Def = 0;
1005      if (!Var->getDefinition(Def))
1006        InstantiateVariableDefinition(Var);
1007    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1008      if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) {
1009        assert(Record->getInstantiatedFromMemberClass() &&
1010               "Missing instantiated-from-template information");
1011        InstantiateClass(PointOfInstantiation, Record,
1012                         Record->getInstantiatedFromMemberClass(),
1013                         TemplateArgs, true);
1014      }
1015    }
1016  }
1017}
1018
1019/// \brief Instantiate the definitions of all of the members of the
1020/// given class template specialization, which was named as part of an
1021/// explicit instantiation.
1022void Sema::InstantiateClassTemplateSpecializationMembers(
1023                                           SourceLocation PointOfInstantiation,
1024                          ClassTemplateSpecializationDecl *ClassTemplateSpec) {
1025  // C++0x [temp.explicit]p7:
1026  //   An explicit instantiation that names a class template
1027  //   specialization is an explicit instantion of the same kind
1028  //   (declaration or definition) of each of its members (not
1029  //   including members inherited from base classes) that has not
1030  //   been previously explicitly specialized in the translation unit
1031  //   containing the explicit instantiation, except as described
1032  //   below.
1033  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1034                          ClassTemplateSpec->getTemplateArgs());
1035}
1036
1037/// \brief Instantiate a nested-name-specifier.
1038NestedNameSpecifier *
1039Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
1040                                     SourceRange Range,
1041                                     const TemplateArgumentList &TemplateArgs) {
1042  // Instantiate the prefix of this nested name specifier.
1043  NestedNameSpecifier *Prefix = NNS->getPrefix();
1044  if (Prefix) {
1045    Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs);
1046    if (!Prefix)
1047      return 0;
1048  }
1049
1050  switch (NNS->getKind()) {
1051  case NestedNameSpecifier::Identifier: {
1052    assert(Prefix &&
1053           "Can't have an identifier nested-name-specifier with no prefix");
1054    CXXScopeSpec SS;
1055    // FIXME: The source location information is all wrong.
1056    SS.setRange(Range);
1057    SS.setScopeRep(Prefix);
1058    return static_cast<NestedNameSpecifier *>(
1059                                 ActOnCXXNestedNameSpecifier(0, SS,
1060                                                             Range.getEnd(),
1061                                                             Range.getEnd(),
1062                                                    *NNS->getAsIdentifier()));
1063    break;
1064  }
1065
1066  case NestedNameSpecifier::Namespace:
1067  case NestedNameSpecifier::Global:
1068    return NNS;
1069
1070  case NestedNameSpecifier::TypeSpecWithTemplate:
1071  case NestedNameSpecifier::TypeSpec: {
1072    QualType T = QualType(NNS->getAsType(), 0);
1073    if (!T->isDependentType())
1074      return NNS;
1075
1076    T = InstantiateType(T, TemplateArgs, Range.getBegin(), DeclarationName());
1077    if (T.isNull())
1078      return 0;
1079
1080    if (T->isDependentType() || T->isRecordType() ||
1081        (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
1082      assert(T.getCVRQualifiers() == 0 && "Can't get cv-qualifiers here");
1083      return NestedNameSpecifier::Create(Context, Prefix,
1084                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1085                                         T.getTypePtr());
1086    }
1087
1088    Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
1089    return 0;
1090  }
1091  }
1092
1093  // Required to silence a GCC warning
1094  return 0;
1095}
1096
1097TemplateName
1098Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
1099                              const TemplateArgumentList &TemplateArgs) {
1100  if (TemplateTemplateParmDecl *TTP
1101        = dyn_cast_or_null<TemplateTemplateParmDecl>(
1102                                                 Name.getAsTemplateDecl())) {
1103    assert(TTP->getDepth() == 0 &&
1104           "Cannot reduce depth of a template template parameter");
1105    assert(TemplateArgs[TTP->getPosition()].getAsDecl() &&
1106           "Wrong kind of template template argument");
1107    ClassTemplateDecl *ClassTemplate
1108      = dyn_cast<ClassTemplateDecl>(
1109                               TemplateArgs[TTP->getPosition()].getAsDecl());
1110    assert(ClassTemplate && "Expected a class template");
1111    if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
1112      NestedNameSpecifier *NNS
1113        = InstantiateNestedNameSpecifier(QTN->getQualifier(),
1114                                         /*FIXME=*/SourceRange(Loc),
1115                                         TemplateArgs);
1116      if (NNS)
1117        return Context.getQualifiedTemplateName(NNS,
1118                                                QTN->hasTemplateKeyword(),
1119                                                ClassTemplate);
1120    }
1121
1122    return TemplateName(ClassTemplate);
1123  } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
1124    NestedNameSpecifier *NNS
1125      = InstantiateNestedNameSpecifier(DTN->getQualifier(),
1126                                       /*FIXME=*/SourceRange(Loc),
1127                                       TemplateArgs);
1128
1129    if (!NNS) // FIXME: Not the best recovery strategy.
1130      return Name;
1131
1132    if (NNS->isDependent())
1133      return Context.getDependentTemplateName(NNS, DTN->getName());
1134
1135    // Somewhat redundant with ActOnDependentTemplateName.
1136    CXXScopeSpec SS;
1137    SS.setRange(SourceRange(Loc));
1138    SS.setScopeRep(NNS);
1139    TemplateTy Template;
1140    TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
1141    if (TNK == TNK_Non_template) {
1142      Diag(Loc, diag::err_template_kw_refers_to_non_template)
1143        << DTN->getName();
1144      return Name;
1145    } else if (TNK == TNK_Function_template) {
1146      Diag(Loc, diag::err_template_kw_refers_to_non_template)
1147        << DTN->getName();
1148      return Name;
1149    }
1150
1151    return Template.getAsVal<TemplateName>();
1152  }
1153
1154
1155
1156  // FIXME: Even if we're referring to a Decl that isn't a template template
1157  // parameter, we may need to instantiate the outer contexts of that
1158  // Decl. However, this won't be needed until we implement member templates.
1159  return Name;
1160}
1161
1162TemplateArgument Sema::Instantiate(TemplateArgument Arg,
1163                                   const TemplateArgumentList &TemplateArgs) {
1164  switch (Arg.getKind()) {
1165  case TemplateArgument::Null:
1166    assert(false && "Should never have a NULL template argument");
1167    break;
1168
1169  case TemplateArgument::Type: {
1170    QualType T = InstantiateType(Arg.getAsType(), TemplateArgs,
1171                                 Arg.getLocation(), DeclarationName());
1172    if (T.isNull())
1173      return TemplateArgument();
1174
1175    return TemplateArgument(Arg.getLocation(), T);
1176  }
1177
1178  case TemplateArgument::Declaration:
1179    // FIXME: Template instantiation for template template parameters.
1180    return Arg;
1181
1182  case TemplateArgument::Integral:
1183    return Arg;
1184
1185  case TemplateArgument::Expression: {
1186    // Template argument expressions are not potentially evaluated.
1187    EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
1188
1189    Sema::OwningExprResult E = InstantiateExpr(Arg.getAsExpr(), TemplateArgs);
1190    if (E.isInvalid())
1191      return TemplateArgument();
1192    return TemplateArgument(E.takeAs<Expr>());
1193  }
1194
1195  case TemplateArgument::Pack:
1196    assert(0 && "FIXME: Implement!");
1197    break;
1198  }
1199
1200  assert(false && "Unhandled template argument kind");
1201  return TemplateArgument();
1202}
1203