SemaTemplateInstantiate.cpp revision 15a928580f936a76dc09f5f57c055122d32d763d
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/ASTContext.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/Parse/DeclSpec.h"
18#include "clang/Basic/LangOptions.h"
19#include "llvm/Support/Compiler.h"
20
21using namespace clang;
22
23//===----------------------------------------------------------------------===/
24// Template Instantiation Support
25//===----------------------------------------------------------------------===/
26
27Sema::InstantiatingTemplate::
28InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
29                      CXXRecordDecl *Entity,
30                      SourceRange InstantiationRange)
31  :  SemaRef(SemaRef) {
32
33  Invalid = CheckInstantiationDepth(PointOfInstantiation,
34                                    InstantiationRange);
35  if (!Invalid) {
36    ActiveTemplateInstantiation Inst;
37    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
38    Inst.PointOfInstantiation = PointOfInstantiation;
39    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
40    Inst.TemplateArgs = 0;
41    Inst.NumTemplateArgs = 0;
42    Inst.InstantiationRange = InstantiationRange;
43    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
44    Invalid = false;
45  }
46}
47
48Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
49                                         SourceLocation PointOfInstantiation,
50                                         TemplateDecl *Template,
51                                         const TemplateArgument *TemplateArgs,
52                                         unsigned NumTemplateArgs,
53                                         SourceRange InstantiationRange)
54  : SemaRef(SemaRef) {
55
56  Invalid = CheckInstantiationDepth(PointOfInstantiation,
57                                    InstantiationRange);
58  if (!Invalid) {
59    ActiveTemplateInstantiation Inst;
60    Inst.Kind
61      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
62    Inst.PointOfInstantiation = PointOfInstantiation;
63    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
64    Inst.TemplateArgs = TemplateArgs;
65    Inst.NumTemplateArgs = NumTemplateArgs;
66    Inst.InstantiationRange = InstantiationRange;
67    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
68    Invalid = false;
69  }
70}
71
72Sema::InstantiatingTemplate::~InstantiatingTemplate() {
73  if (!Invalid)
74    SemaRef.ActiveTemplateInstantiations.pop_back();
75}
76
77bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
78                                        SourceLocation PointOfInstantiation,
79                                           SourceRange InstantiationRange) {
80  if (SemaRef.ActiveTemplateInstantiations.size()
81       <= SemaRef.getLangOptions().InstantiationDepth)
82    return false;
83
84  SemaRef.Diag(PointOfInstantiation,
85               diag::err_template_recursion_depth_exceeded)
86    << SemaRef.getLangOptions().InstantiationDepth
87    << InstantiationRange;
88  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
89    << SemaRef.getLangOptions().InstantiationDepth;
90  return true;
91}
92
93/// \brief Prints the current instantiation stack through a series of
94/// notes.
95void Sema::PrintInstantiationStack() {
96  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
97         Active = ActiveTemplateInstantiations.rbegin(),
98         ActiveEnd = ActiveTemplateInstantiations.rend();
99       Active != ActiveEnd;
100       ++Active) {
101    switch (Active->Kind) {
102    case ActiveTemplateInstantiation::TemplateInstantiation: {
103      unsigned DiagID = diag::note_template_member_class_here;
104      CXXRecordDecl *Record = (CXXRecordDecl *)Active->Entity;
105      if (isa<ClassTemplateSpecializationDecl>(Record))
106        DiagID = diag::note_template_class_instantiation_here;
107      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
108                   DiagID)
109        << Context.getTypeDeclType(Record)
110        << Active->InstantiationRange;
111      break;
112    }
113
114    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
115      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
116      std::string TemplateArgsStr
117        = TemplateSpecializationType::PrintTemplateArgumentList(
118                                                      Active->TemplateArgs,
119                                                      Active->NumTemplateArgs);
120      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
121                   diag::note_default_arg_instantiation_here)
122        << (Template->getNameAsString() + TemplateArgsStr)
123        << Active->InstantiationRange;
124      break;
125    }
126    }
127  }
128}
129
130//===----------------------------------------------------------------------===/
131// Template Instantiation for Types
132//===----------------------------------------------------------------------===/
133namespace {
134  class VISIBILITY_HIDDEN TemplateTypeInstantiator {
135    Sema &SemaRef;
136    const TemplateArgument *TemplateArgs;
137    unsigned NumTemplateArgs;
138    SourceLocation Loc;
139    DeclarationName Entity;
140
141  public:
142    TemplateTypeInstantiator(Sema &SemaRef,
143                             const TemplateArgument *TemplateArgs,
144                             unsigned NumTemplateArgs,
145                             SourceLocation Loc,
146                             DeclarationName Entity)
147      : SemaRef(SemaRef), TemplateArgs(TemplateArgs),
148        NumTemplateArgs(NumTemplateArgs), Loc(Loc), Entity(Entity) { }
149
150    QualType operator()(QualType T) const { return Instantiate(T); }
151
152    QualType Instantiate(QualType T) const;
153
154    // Declare instantiate functions for each type.
155#define TYPE(Class, Base)                                       \
156    QualType Instantiate##Class##Type(const Class##Type *T,     \
157                                      unsigned Quals) const;
158#define ABSTRACT_TYPE(Class, Base)
159#include "clang/AST/TypeNodes.def"
160  };
161}
162
163QualType
164TemplateTypeInstantiator::InstantiateExtQualType(const ExtQualType *T,
165                                                 unsigned Quals) const {
166  // FIXME: Implement this
167  assert(false && "Cannot instantiate ExtQualType yet");
168  return QualType();
169}
170
171QualType
172TemplateTypeInstantiator::InstantiateBuiltinType(const BuiltinType *T,
173                                                 unsigned Quals) const {
174  assert(false && "Builtin types are not dependent and cannot be instantiated");
175  return QualType(T, Quals);
176}
177
178QualType
179TemplateTypeInstantiator::
180InstantiateFixedWidthIntType(const FixedWidthIntType *T, unsigned Quals) const {
181  // FIXME: Implement this
182  assert(false && "Cannot instantiate FixedWidthIntType yet");
183  return QualType();
184}
185
186QualType
187TemplateTypeInstantiator::InstantiateComplexType(const ComplexType *T,
188                                                 unsigned Quals) const {
189  // FIXME: Implement this
190  assert(false && "Cannot instantiate ComplexType yet");
191  return QualType();
192}
193
194QualType
195TemplateTypeInstantiator::InstantiatePointerType(const PointerType *T,
196                                                 unsigned Quals) const {
197  QualType PointeeType = Instantiate(T->getPointeeType());
198  if (PointeeType.isNull())
199    return QualType();
200
201  return SemaRef.BuildPointerType(PointeeType, Quals, Loc, Entity);
202}
203
204QualType
205TemplateTypeInstantiator::InstantiateBlockPointerType(const BlockPointerType *T,
206                                                      unsigned Quals) const {
207  // FIXME: Implement this
208  assert(false && "Cannot instantiate BlockPointerType yet");
209  return QualType();
210}
211
212QualType
213TemplateTypeInstantiator::InstantiateLValueReferenceType(
214    const LValueReferenceType *T, unsigned Quals) const {
215  QualType ReferentType = Instantiate(T->getPointeeType());
216  if (ReferentType.isNull())
217    return QualType();
218
219  return SemaRef.BuildReferenceType(ReferentType, true, Quals, Loc, Entity);
220}
221
222QualType
223TemplateTypeInstantiator::InstantiateRValueReferenceType(
224    const RValueReferenceType *T, unsigned Quals) const {
225  QualType ReferentType = Instantiate(T->getPointeeType());
226  if (ReferentType.isNull())
227    return QualType();
228
229  return SemaRef.BuildReferenceType(ReferentType, false, Quals, Loc, Entity);
230}
231
232QualType
233TemplateTypeInstantiator::
234InstantiateMemberPointerType(const MemberPointerType *T,
235                             unsigned Quals) const {
236  // FIXME: Implement this
237  assert(false && "Cannot instantiate MemberPointerType yet");
238  return QualType();
239}
240
241QualType
242TemplateTypeInstantiator::
243InstantiateConstantArrayType(const ConstantArrayType *T,
244                             unsigned Quals) const {
245  QualType ElementType = Instantiate(T->getElementType());
246  if (ElementType.isNull())
247    return ElementType;
248
249  // Build a temporary integer literal to specify the size for
250  // BuildArrayType. Since we have already checked the size as part of
251  // creating the dependent array type in the first place, we know
252  // there aren't any errors.
253  // FIXME: Is IntTy big enough? Maybe not, but LongLongTy causes
254  // problems that I have yet to investigate.
255  IntegerLiteral ArraySize(T->getSize(), SemaRef.Context.IntTy, Loc);
256  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
257                                &ArraySize, T->getIndexTypeQualifier(),
258                                Loc, Entity);
259}
260
261QualType
262TemplateTypeInstantiator::
263InstantiateIncompleteArrayType(const IncompleteArrayType *T,
264                               unsigned Quals) const {
265  QualType ElementType = Instantiate(T->getElementType());
266  if (ElementType.isNull())
267    return ElementType;
268
269  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
270                                0, T->getIndexTypeQualifier(),
271                                Loc, Entity);
272}
273
274QualType
275TemplateTypeInstantiator::
276InstantiateVariableArrayType(const VariableArrayType *T,
277                             unsigned Quals) const {
278  // FIXME: Implement this
279  assert(false && "Cannot instantiate VariableArrayType yet");
280  return QualType();
281}
282
283QualType
284TemplateTypeInstantiator::
285InstantiateDependentSizedArrayType(const DependentSizedArrayType *T,
286                                   unsigned Quals) const {
287  Expr *ArraySize = T->getSizeExpr();
288  assert(ArraySize->isValueDependent() &&
289         "dependent sized array types must have value dependent size expr");
290
291  // Instantiate the element type if needed
292  QualType ElementType = T->getElementType();
293  if (ElementType->isDependentType()) {
294    ElementType = Instantiate(ElementType);
295    if (ElementType.isNull())
296      return QualType();
297  }
298
299  // Instantiate the size expression
300  Sema::OwningExprResult InstantiatedArraySize =
301    SemaRef.InstantiateExpr(ArraySize, TemplateArgs, NumTemplateArgs);
302  if (InstantiatedArraySize.isInvalid())
303    return QualType();
304
305  return SemaRef.BuildArrayType(ElementType, T->getSizeModifier(),
306                                (Expr *)InstantiatedArraySize.release(),
307                                T->getIndexTypeQualifier(), Loc, Entity);
308}
309
310QualType
311TemplateTypeInstantiator::InstantiateVectorType(const VectorType *T,
312                                             unsigned Quals) const {
313  // FIXME: Implement this
314  assert(false && "Cannot instantiate VectorType yet");
315  return QualType();
316}
317
318QualType
319TemplateTypeInstantiator::InstantiateExtVectorType(const ExtVectorType *T,
320                                                   unsigned Quals) const {
321  // FIXME: Implement this
322  assert(false && "Cannot instantiate ExtVectorType yet");
323  return QualType();
324}
325
326QualType
327TemplateTypeInstantiator::
328InstantiateFunctionProtoType(const FunctionProtoType *T,
329                             unsigned Quals) const {
330  QualType ResultType = Instantiate(T->getResultType());
331  if (ResultType.isNull())
332    return ResultType;
333
334  llvm::SmallVector<QualType, 16> ParamTypes;
335  for (FunctionProtoType::arg_type_iterator Param = T->arg_type_begin(),
336                                         ParamEnd = T->arg_type_end();
337       Param != ParamEnd; ++Param) {
338    QualType P = Instantiate(*Param);
339    if (P.isNull())
340      return P;
341
342    ParamTypes.push_back(P);
343  }
344
345  return SemaRef.BuildFunctionType(ResultType, &ParamTypes[0],
346                                   ParamTypes.size(),
347                                   T->isVariadic(), T->getTypeQuals(),
348                                   Loc, Entity);
349}
350
351QualType
352TemplateTypeInstantiator::
353InstantiateFunctionNoProtoType(const FunctionNoProtoType *T,
354                               unsigned Quals) const {
355  assert(false && "Functions without prototypes cannot be dependent.");
356  return QualType();
357}
358
359QualType
360TemplateTypeInstantiator::InstantiateTypedefType(const TypedefType *T,
361                                                 unsigned Quals) const {
362  // FIXME: Implement this
363  assert(false && "Cannot instantiate TypedefType yet");
364  return QualType();
365}
366
367QualType
368TemplateTypeInstantiator::InstantiateTypeOfExprType(const TypeOfExprType *T,
369                                                    unsigned Quals) const {
370  // FIXME: Implement this
371  assert(false && "Cannot instantiate TypeOfExprType yet");
372  return QualType();
373}
374
375QualType
376TemplateTypeInstantiator::InstantiateTypeOfType(const TypeOfType *T,
377                                                unsigned Quals) const {
378  // FIXME: Implement this
379  assert(false && "Cannot instantiate TypeOfType yet");
380  return QualType();
381}
382
383QualType
384TemplateTypeInstantiator::InstantiateRecordType(const RecordType *T,
385                                                unsigned Quals) const {
386  // FIXME: Implement this
387  assert(false && "Cannot instantiate RecordType yet");
388  return QualType();
389}
390
391QualType
392TemplateTypeInstantiator::InstantiateEnumType(const EnumType *T,
393                                              unsigned Quals) const {
394  // FIXME: Implement this
395  assert(false && "Cannot instantiate EnumType yet");
396  return QualType();
397}
398
399QualType
400TemplateTypeInstantiator::
401InstantiateTemplateTypeParmType(const TemplateTypeParmType *T,
402                                unsigned Quals) const {
403  if (T->getDepth() == 0) {
404    // Replace the template type parameter with its corresponding
405    // template argument.
406    assert(T->getIndex() < NumTemplateArgs && "Wrong # of template args");
407    assert(TemplateArgs[T->getIndex()].getKind() == TemplateArgument::Type &&
408           "Template argument kind mismatch");
409    QualType Result = TemplateArgs[T->getIndex()].getAsType();
410    if (Result.isNull() || !Quals)
411      return Result;
412
413    // C++ [dcl.ref]p1:
414    //   [...] Cv-qualified references are ill-formed except when
415    //   the cv-qualifiers are introduced through the use of a
416    //   typedef (7.1.3) or of a template type argument (14.3), in
417    //   which case the cv-qualifiers are ignored.
418    if (Quals && Result->isReferenceType())
419      Quals = 0;
420
421    return QualType(Result.getTypePtr(), Quals | Result.getCVRQualifiers());
422  }
423
424  // The template type parameter comes from an inner template (e.g.,
425  // the template parameter list of a member template inside the
426  // template we are instantiating). Create a new template type
427  // parameter with the template "level" reduced by one.
428  return SemaRef.Context.getTemplateTypeParmType(T->getDepth() - 1,
429                                                 T->getIndex(),
430                                                 T->getName())
431    .getQualifiedType(Quals);
432}
433
434QualType
435TemplateTypeInstantiator::
436InstantiateTemplateSpecializationType(
437                                  const TemplateSpecializationType *T,
438                                  unsigned Quals) const {
439  llvm::SmallVector<TemplateArgument, 16> InstantiatedTemplateArgs;
440  InstantiatedTemplateArgs.reserve(T->getNumArgs());
441  for (TemplateSpecializationType::iterator Arg = T->begin(), ArgEnd = T->end();
442       Arg != ArgEnd; ++Arg) {
443    switch (Arg->getKind()) {
444    case TemplateArgument::Type: {
445      QualType T = SemaRef.InstantiateType(Arg->getAsType(),
446                                           TemplateArgs, NumTemplateArgs,
447                                           Arg->getLocation(),
448                                           DeclarationName());
449      if (T.isNull())
450        return QualType();
451
452      InstantiatedTemplateArgs.push_back(
453                                TemplateArgument(Arg->getLocation(), T));
454      break;
455    }
456
457    case TemplateArgument::Declaration:
458    case TemplateArgument::Integral:
459      InstantiatedTemplateArgs.push_back(*Arg);
460      break;
461
462    case TemplateArgument::Expression:
463      Sema::OwningExprResult E
464        = SemaRef.InstantiateExpr(Arg->getAsExpr(), TemplateArgs,
465                                  NumTemplateArgs);
466      if (E.isInvalid())
467        return QualType();
468      InstantiatedTemplateArgs.push_back((Expr *)E.release());
469      break;
470    }
471  }
472
473  // FIXME: We're missing the locations of the template name, '<', and
474  // '>'.
475
476  TemplateName Name = SemaRef.InstantiateTemplateName(T->getTemplateName(),
477                                                      Loc,
478                                                      TemplateArgs,
479                                                      NumTemplateArgs);
480
481  return SemaRef.CheckTemplateIdType(Name, Loc, SourceLocation(),
482                                     &InstantiatedTemplateArgs[0],
483                                     InstantiatedTemplateArgs.size(),
484                                     SourceLocation());
485}
486
487QualType
488TemplateTypeInstantiator::
489InstantiateQualifiedNameType(const QualifiedNameType *T,
490                             unsigned Quals) const {
491  // When we instantiated a qualified name type, there's no point in
492  // keeping the qualification around in the instantiated result. So,
493  // just instantiate the named type.
494  return (*this)(T->getNamedType());
495}
496
497QualType
498TemplateTypeInstantiator::
499InstantiateTypenameType(const TypenameType *T, unsigned Quals) const {
500  NestedNameSpecifier *NNS
501    = SemaRef.InstantiateNestedNameSpecifier(T->getQualifier(),
502                                             SourceRange(Loc),
503                                             TemplateArgs, NumTemplateArgs);
504  if (!NNS)
505    return QualType();
506
507  return SemaRef.CheckTypenameType(NNS, *T->getName(), SourceRange(Loc));
508}
509
510QualType
511TemplateTypeInstantiator::
512InstantiateObjCInterfaceType(const ObjCInterfaceType *T,
513                             unsigned Quals) const {
514  assert(false && "Objective-C types cannot be dependent");
515  return QualType();
516}
517
518QualType
519TemplateTypeInstantiator::
520InstantiateObjCQualifiedInterfaceType(const ObjCQualifiedInterfaceType *T,
521                                      unsigned Quals) const {
522  assert(false && "Objective-C types cannot be dependent");
523  return QualType();
524}
525
526QualType
527TemplateTypeInstantiator::
528InstantiateObjCQualifiedIdType(const ObjCQualifiedIdType *T,
529                               unsigned Quals) const {
530  assert(false && "Objective-C types cannot be dependent");
531  return QualType();
532}
533
534QualType
535TemplateTypeInstantiator::
536InstantiateObjCQualifiedClassType(const ObjCQualifiedClassType *T,
537                                  unsigned Quals) const {
538  assert(false && "Objective-C types cannot be dependent");
539  return QualType();
540}
541
542/// \brief The actual implementation of Sema::InstantiateType().
543QualType TemplateTypeInstantiator::Instantiate(QualType T) const {
544  // If T is not a dependent type, there is nothing to do.
545  if (!T->isDependentType())
546    return T;
547
548  switch (T->getTypeClass()) {
549#define TYPE(Class, Base)                                               \
550  case Type::Class:                                                     \
551    return Instantiate##Class##Type(cast<Class##Type>(T.getTypePtr()),  \
552                                    T.getCVRQualifiers());
553#define ABSTRACT_TYPE(Class, Base)
554#include "clang/AST/TypeNodes.def"
555  }
556
557  assert(false && "Not all types have been decoded for instantiation");
558  return QualType();
559}
560
561/// \brief Instantiate the type T with a given set of template arguments.
562///
563/// This routine substitutes the given template arguments into the
564/// type T and produces the instantiated type.
565///
566/// \param T the type into which the template arguments will be
567/// substituted. If this type is not dependent, it will be returned
568/// immediately.
569///
570/// \param TemplateArgs the template arguments that will be
571/// substituted for the top-level template parameters within T.
572///
573/// \param NumTemplateArgs the number of template arguments provided
574/// by TemplateArgs.
575///
576/// \param Loc the location in the source code where this substitution
577/// is being performed. It will typically be the location of the
578/// declarator (if we're instantiating the type of some declaration)
579/// or the location of the type in the source code (if, e.g., we're
580/// instantiating the type of a cast expression).
581///
582/// \param Entity the name of the entity associated with a declaration
583/// being instantiated (if any). May be empty to indicate that there
584/// is no such entity (if, e.g., this is a type that occurs as part of
585/// a cast expression) or that the entity has no name (e.g., an
586/// unnamed function parameter).
587///
588/// \returns If the instantiation succeeds, the instantiated
589/// type. Otherwise, produces diagnostics and returns a NULL type.
590QualType Sema::InstantiateType(QualType T,
591                               const TemplateArgument *TemplateArgs,
592                               unsigned NumTemplateArgs,
593                               SourceLocation Loc, DeclarationName Entity) {
594  assert(!ActiveTemplateInstantiations.empty() &&
595         "Cannot perform an instantiation without some context on the "
596         "instantiation stack");
597
598  // If T is not a dependent type, there is nothing to do.
599  if (!T->isDependentType())
600    return T;
601
602  TemplateTypeInstantiator Instantiator(*this, TemplateArgs, NumTemplateArgs,
603                                        Loc, Entity);
604  return Instantiator(T);
605}
606
607/// \brief Instantiate the base class specifiers of the given class
608/// template specialization.
609///
610/// Produces a diagnostic and returns true on error, returns false and
611/// attaches the instantiated base classes to the class template
612/// specialization if successful.
613bool
614Sema::InstantiateBaseSpecifiers(CXXRecordDecl *Instantiation,
615                                CXXRecordDecl *Pattern,
616                                const TemplateArgument *TemplateArgs,
617                                unsigned NumTemplateArgs) {
618  bool Invalid = false;
619  llvm::SmallVector<CXXBaseSpecifier*, 8> InstantiatedBases;
620  for (ClassTemplateSpecializationDecl::base_class_iterator
621         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
622       Base != BaseEnd; ++Base) {
623    if (!Base->getType()->isDependentType()) {
624      // FIXME: Allocate via ASTContext
625      InstantiatedBases.push_back(new CXXBaseSpecifier(*Base));
626      continue;
627    }
628
629    QualType BaseType = InstantiateType(Base->getType(),
630                                        TemplateArgs, NumTemplateArgs,
631                                        Base->getSourceRange().getBegin(),
632                                        DeclarationName());
633    if (BaseType.isNull()) {
634      Invalid = true;
635      continue;
636    }
637
638    if (CXXBaseSpecifier *InstantiatedBase
639          = CheckBaseSpecifier(Instantiation,
640                               Base->getSourceRange(),
641                               Base->isVirtual(),
642                               Base->getAccessSpecifierAsWritten(),
643                               BaseType,
644                               /*FIXME: Not totally accurate */
645                               Base->getSourceRange().getBegin()))
646      InstantiatedBases.push_back(InstantiatedBase);
647    else
648      Invalid = true;
649  }
650
651  if (!Invalid &&
652      AttachBaseSpecifiers(Instantiation, &InstantiatedBases[0],
653                           InstantiatedBases.size()))
654    Invalid = true;
655
656  return Invalid;
657}
658
659/// \brief Instantiate the definition of a class from a given pattern.
660///
661/// \param PointOfInstantiation The point of instantiation within the
662/// source code.
663///
664/// \param Instantiation is the declaration whose definition is being
665/// instantiated. This will be either a class template specialization
666/// or a member class of a class template specialization.
667///
668/// \param Pattern is the pattern from which the instantiation
669/// occurs. This will be either the declaration of a class template or
670/// the declaration of a member class of a class template.
671///
672/// \param TemplateArgs The template arguments to be substituted into
673/// the pattern.
674///
675/// \param NumTemplateArgs The number of templates arguments in
676/// TemplateArgs.
677///
678/// \returns true if an error occurred, false otherwise.
679bool
680Sema::InstantiateClass(SourceLocation PointOfInstantiation,
681                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
682                       const TemplateArgument *TemplateArgs,
683                       unsigned NumTemplateArgs) {
684  bool Invalid = false;
685
686  CXXRecordDecl *PatternDef
687    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
688  if (!PatternDef) {
689    if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
690      Diag(PointOfInstantiation,
691           diag::err_implicit_instantiate_member_undefined)
692        << Context.getTypeDeclType(Instantiation);
693      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
694    } else {
695      Diag(PointOfInstantiation,
696           diag::err_template_implicit_instantiate_undefined)
697        << Context.getTypeDeclType(Instantiation);
698      Diag(Pattern->getLocation(), diag::note_template_decl_here);
699    }
700    return true;
701  }
702  Pattern = PatternDef;
703
704  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
705  if (Inst)
706    return true;
707
708  // Enter the scope of this instantiation. We don't use
709  // PushDeclContext because we don't have a scope.
710  DeclContext *PreviousContext = CurContext;
711  CurContext = Instantiation;
712
713  // Start the definition of this instantiation.
714  Instantiation->startDefinition();
715
716  // Instantiate the base class specifiers.
717  if (InstantiateBaseSpecifiers(Instantiation, Pattern, TemplateArgs,
718                                NumTemplateArgs))
719    Invalid = true;
720
721  llvm::SmallVector<DeclPtrTy, 32> Fields;
722  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
723       MemberEnd = Pattern->decls_end(); Member != MemberEnd; ++Member) {
724    Decl *NewMember = InstantiateDecl(*Member, Instantiation,
725                                      TemplateArgs, NumTemplateArgs);
726    if (NewMember) {
727      if (NewMember->isInvalidDecl())
728        Invalid = true;
729      else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember))
730        Fields.push_back(DeclPtrTy::make(Field));
731    } else {
732      // FIXME: Eventually, a NULL return will mean that one of the
733      // instantiations was a semantic disaster, and we'll want to set
734      // Invalid = true. For now, we expect to skip some members that
735      // we can't yet handle.
736    }
737  }
738
739  // Finish checking fields.
740  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
741              &Fields[0], Fields.size(), SourceLocation(), SourceLocation(),
742              0);
743
744  // Add any implicitly-declared members that we might need.
745  AddImplicitlyDeclaredMembersToClass(Instantiation);
746
747  // Exit the scope of this instantiation.
748  CurContext = PreviousContext;
749
750  return Invalid;
751}
752
753bool
754Sema::InstantiateClassTemplateSpecialization(
755                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
756                           bool ExplicitInstantiation) {
757  // Perform the actual instantiation on the canonical declaration.
758  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
759                               Context.getCanonicalDecl(ClassTemplateSpec));
760
761  // We can only instantiate something that hasn't already been
762  // instantiated or specialized. Fail without any diagnostics: our
763  // caller will provide an error message.
764  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared)
765    return true;
766
767  // FIXME: Push this class template instantiation onto the
768  // instantiation stack, checking for recursion that exceeds a
769  // certain depth.
770
771  // FIXME: Perform class template partial specialization to select
772  // the best template.
773  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
774
775  CXXRecordDecl *Pattern = Template->getTemplatedDecl();
776
777  // Note that this is an instantiation.
778  ClassTemplateSpec->setSpecializationKind(
779                        ExplicitInstantiation? TSK_ExplicitInstantiation
780                                             : TSK_ImplicitInstantiation);
781
782  return InstantiateClass(ClassTemplateSpec->getLocation(),
783                          ClassTemplateSpec, Pattern,
784                          ClassTemplateSpec->getTemplateArgs(),
785                          ClassTemplateSpec->getNumTemplateArgs());
786}
787
788/// \brief Instantiate a nested-name-specifier.
789NestedNameSpecifier *
790Sema::InstantiateNestedNameSpecifier(NestedNameSpecifier *NNS,
791                                     SourceRange Range,
792                                     const TemplateArgument *TemplateArgs,
793                                     unsigned NumTemplateArgs) {
794  // Instantiate the prefix of this nested name specifier.
795  NestedNameSpecifier *Prefix = NNS->getPrefix();
796  if (Prefix) {
797    Prefix = InstantiateNestedNameSpecifier(Prefix, Range, TemplateArgs,
798                                            NumTemplateArgs);
799    if (!Prefix)
800      return 0;
801  }
802
803  switch (NNS->getKind()) {
804  case NestedNameSpecifier::Identifier:
805    // FIXME: Implement this lookup!
806    assert(false && "Cannot instantiate this nested-name-specifier");
807    break;
808
809  case NestedNameSpecifier::Namespace:
810  case NestedNameSpecifier::Global:
811    return NNS;
812
813  case NestedNameSpecifier::TypeSpecWithTemplate:
814  case NestedNameSpecifier::TypeSpec: {
815    QualType T = QualType(NNS->getAsType(), 0);
816    if (!T->isDependentType())
817      return NNS;
818
819    // FIXME: We won't be able to perform the instantiation here when
820    // the template-name is dependent, e.g., we have something like
821    // "T::template apply<U>::type".
822    T = InstantiateType(T, TemplateArgs, NumTemplateArgs, Range.getBegin(),
823                        DeclarationName());
824    if (T.isNull())
825      return 0;
826
827    if (T->isRecordType() ||
828        (getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
829      // Note that T.getTypePtr(), below, strips cv-qualifiers. This is
830      // perfectly reasonable, since cv-qualified types in
831      // nested-name-specifiers don't matter.
832      return NestedNameSpecifier::Create(Context, Prefix,
833                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
834                                         T.getTypePtr());
835    }
836
837    Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
838    return 0;
839  }
840  }
841
842  // Required to silence a GCC warning
843  return 0;
844}
845
846TemplateName
847Sema::InstantiateTemplateName(TemplateName Name, SourceLocation Loc,
848                              const TemplateArgument *TemplateArgs,
849                              unsigned NumTemplateArgs) {
850  if (TemplateTemplateParmDecl *TTP
851        = dyn_cast_or_null<TemplateTemplateParmDecl>(
852                                                 Name.getAsTemplateDecl())) {
853    assert(TTP->getDepth() == 0 &&
854           "Cannot reduce depth of a template template parameter");
855    assert(TTP->getPosition() < NumTemplateArgs && "Wrong # of template args");
856    assert(dyn_cast_or_null<ClassTemplateDecl>(
857                          TemplateArgs[TTP->getPosition()].getAsDecl()) &&
858           "Wrong kind of template template argument");
859    ClassTemplateDecl *ClassTemplate
860      = dyn_cast<ClassTemplateDecl>(
861                               TemplateArgs[TTP->getPosition()].getAsDecl());
862
863    if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
864      NestedNameSpecifier *NNS
865        = InstantiateNestedNameSpecifier(QTN->getQualifier(),
866                                         /*FIXME=*/SourceRange(Loc),
867                                         TemplateArgs, NumTemplateArgs);
868      if (NNS)
869        return Context.getQualifiedTemplateName(NNS,
870                                                QTN->hasTemplateKeyword(),
871                                                ClassTemplate);
872    }
873
874    return TemplateName(ClassTemplate);
875  } else if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
876    NestedNameSpecifier *NNS
877      = InstantiateNestedNameSpecifier(DTN->getQualifier(),
878                                       /*FIXME=*/SourceRange(Loc),
879                                       TemplateArgs, NumTemplateArgs);
880
881    if (!NNS) // FIXME: Not the best recovery strategy.
882      return Name;
883
884    if (NNS->isDependent())
885      return Context.getDependentTemplateName(NNS, DTN->getName());
886
887    // Somewhat redundant with ActOnDependentTemplateName.
888    CXXScopeSpec SS;
889    SS.setRange(SourceRange(Loc));
890    SS.setScopeRep(NNS);
891    TemplateTy Template;
892    TemplateNameKind TNK = isTemplateName(*DTN->getName(), 0, Template, &SS);
893    if (TNK == TNK_Non_template) {
894      Diag(Loc, diag::err_template_kw_refers_to_non_template)
895        << DTN->getName();
896      return Name;
897    } else if (TNK == TNK_Function_template) {
898      Diag(Loc, diag::err_template_kw_refers_to_non_template)
899        << DTN->getName();
900      return Name;
901    }
902
903    return Template.getAsVal<TemplateName>();
904  }
905
906
907
908  // FIXME: Even if we're referring to a Decl that isn't a template
909  // template parameter, we may need to instantiate the outer contexts
910  // of that Decl. However, this won't be needed until we implement
911  // member templates.
912  return Name;
913}
914