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