SemaTemplateInstantiate.cpp revision dd41da9a2b74de24ef09f56cc5bb92be99787415
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 "TreeTransform.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/DeclSpec.h"
20#include "clang/Basic/LangOptions.h"
21#include "llvm/Support/Compiler.h"
22
23using namespace clang;
24
25//===----------------------------------------------------------------------===/
26// Template Instantiation Support
27//===----------------------------------------------------------------------===/
28
29/// \brief Retrieve the template argument list(s) that should be used to
30/// instantiate the definition of the given declaration.
31MultiLevelTemplateArgumentList
32Sema::getTemplateInstantiationArgs(NamedDecl *D) {
33  // Accumulate the set of template argument lists in this structure.
34  MultiLevelTemplateArgumentList Result;
35
36  DeclContext *Ctx = dyn_cast<DeclContext>(D);
37  if (!Ctx)
38    Ctx = D->getDeclContext();
39
40  while (!Ctx->isFileContext()) {
41    // Add template arguments from a class template instantiation.
42    if (ClassTemplateSpecializationDecl *Spec
43          = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
44      // We're done when we hit an explicit specialization.
45      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization)
46        break;
47
48      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
49
50      // If this class template specialization was instantiated from a
51      // specialized member that is a class template, we're done.
52      assert(Spec->getSpecializedTemplate() && "No class template?");
53      if (Spec->getSpecializedTemplate()->isMemberSpecialization())
54        break;
55    }
56    // Add template arguments from a function template specialization.
57    else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
58      if (Function->getTemplateSpecializationKind()
59            == TSK_ExplicitSpecialization)
60        break;
61
62      if (const TemplateArgumentList *TemplateArgs
63            = Function->getTemplateSpecializationArgs()) {
64        // Add the template arguments for this specialization.
65        Result.addOuterTemplateArguments(TemplateArgs);
66
67        // If this function was instantiated from a specialized member that is
68        // a function template, we're done.
69        assert(Function->getPrimaryTemplate() && "No function template?");
70        if (Function->getPrimaryTemplate()->isMemberSpecialization())
71          break;
72      }
73
74      // If this is a friend declaration and it declares an entity at
75      // namespace scope, take arguments from its lexical parent
76      // instead of its semantic parent.
77      if (Function->getFriendObjectKind() &&
78          Function->getDeclContext()->isFileContext()) {
79        Ctx = Function->getLexicalDeclContext();
80        continue;
81      }
82    }
83
84    Ctx = Ctx->getParent();
85  }
86
87  return Result;
88}
89
90Sema::InstantiatingTemplate::
91InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
92                      Decl *Entity,
93                      SourceRange InstantiationRange)
94  :  SemaRef(SemaRef) {
95
96  Invalid = CheckInstantiationDepth(PointOfInstantiation,
97                                    InstantiationRange);
98  if (!Invalid) {
99    ActiveTemplateInstantiation Inst;
100    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
101    Inst.PointOfInstantiation = PointOfInstantiation;
102    Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
103    Inst.TemplateArgs = 0;
104    Inst.NumTemplateArgs = 0;
105    Inst.InstantiationRange = InstantiationRange;
106    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
107    Invalid = false;
108  }
109}
110
111Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
112                                         SourceLocation PointOfInstantiation,
113                                         TemplateDecl *Template,
114                                         const TemplateArgument *TemplateArgs,
115                                         unsigned NumTemplateArgs,
116                                         SourceRange InstantiationRange)
117  : SemaRef(SemaRef) {
118
119  Invalid = CheckInstantiationDepth(PointOfInstantiation,
120                                    InstantiationRange);
121  if (!Invalid) {
122    ActiveTemplateInstantiation Inst;
123    Inst.Kind
124      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
125    Inst.PointOfInstantiation = PointOfInstantiation;
126    Inst.Entity = reinterpret_cast<uintptr_t>(Template);
127    Inst.TemplateArgs = TemplateArgs;
128    Inst.NumTemplateArgs = NumTemplateArgs;
129    Inst.InstantiationRange = InstantiationRange;
130    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
131    Invalid = false;
132  }
133}
134
135Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
136                                         SourceLocation PointOfInstantiation,
137                                      FunctionTemplateDecl *FunctionTemplate,
138                                        const TemplateArgument *TemplateArgs,
139                                                   unsigned NumTemplateArgs,
140                         ActiveTemplateInstantiation::InstantiationKind Kind,
141                                              SourceRange InstantiationRange)
142: SemaRef(SemaRef) {
143
144  Invalid = CheckInstantiationDepth(PointOfInstantiation,
145                                    InstantiationRange);
146  if (!Invalid) {
147    ActiveTemplateInstantiation Inst;
148    Inst.Kind = Kind;
149    Inst.PointOfInstantiation = PointOfInstantiation;
150    Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
151    Inst.TemplateArgs = TemplateArgs;
152    Inst.NumTemplateArgs = NumTemplateArgs;
153    Inst.InstantiationRange = InstantiationRange;
154    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
155    Invalid = false;
156  }
157}
158
159Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
160                                         SourceLocation PointOfInstantiation,
161                          ClassTemplatePartialSpecializationDecl *PartialSpec,
162                                         const TemplateArgument *TemplateArgs,
163                                         unsigned NumTemplateArgs,
164                                         SourceRange InstantiationRange)
165  : SemaRef(SemaRef) {
166
167  Invalid = CheckInstantiationDepth(PointOfInstantiation,
168                                    InstantiationRange);
169  if (!Invalid) {
170    ActiveTemplateInstantiation Inst;
171    Inst.Kind
172      = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
173    Inst.PointOfInstantiation = PointOfInstantiation;
174    Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
175    Inst.TemplateArgs = TemplateArgs;
176    Inst.NumTemplateArgs = NumTemplateArgs;
177    Inst.InstantiationRange = InstantiationRange;
178    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
179    Invalid = false;
180  }
181}
182
183Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
184                                          SourceLocation PointOfInstantation,
185                                          ParmVarDecl *Param,
186                                          const TemplateArgument *TemplateArgs,
187                                          unsigned NumTemplateArgs,
188                                          SourceRange InstantiationRange)
189  : SemaRef(SemaRef) {
190
191  Invalid = CheckInstantiationDepth(PointOfInstantation, InstantiationRange);
192
193  if (!Invalid) {
194    ActiveTemplateInstantiation Inst;
195    Inst.Kind
196      = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
197    Inst.PointOfInstantiation = PointOfInstantation;
198    Inst.Entity = reinterpret_cast<uintptr_t>(Param);
199    Inst.TemplateArgs = TemplateArgs;
200    Inst.NumTemplateArgs = NumTemplateArgs;
201    Inst.InstantiationRange = InstantiationRange;
202    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
203    Invalid = false;
204  }
205}
206
207void Sema::InstantiatingTemplate::Clear() {
208  if (!Invalid) {
209    SemaRef.ActiveTemplateInstantiations.pop_back();
210    Invalid = true;
211  }
212}
213
214bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
215                                        SourceLocation PointOfInstantiation,
216                                           SourceRange InstantiationRange) {
217  if (SemaRef.ActiveTemplateInstantiations.size()
218       <= SemaRef.getLangOptions().InstantiationDepth)
219    return false;
220
221  SemaRef.Diag(PointOfInstantiation,
222               diag::err_template_recursion_depth_exceeded)
223    << SemaRef.getLangOptions().InstantiationDepth
224    << InstantiationRange;
225  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
226    << SemaRef.getLangOptions().InstantiationDepth;
227  return true;
228}
229
230/// \brief Prints the current instantiation stack through a series of
231/// notes.
232void Sema::PrintInstantiationStack() {
233  // FIXME: In all of these cases, we need to show the template arguments
234  for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
235         Active = ActiveTemplateInstantiations.rbegin(),
236         ActiveEnd = ActiveTemplateInstantiations.rend();
237       Active != ActiveEnd;
238       ++Active) {
239    switch (Active->Kind) {
240    case ActiveTemplateInstantiation::TemplateInstantiation: {
241      Decl *D = reinterpret_cast<Decl *>(Active->Entity);
242      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
243        unsigned DiagID = diag::note_template_member_class_here;
244        if (isa<ClassTemplateSpecializationDecl>(Record))
245          DiagID = diag::note_template_class_instantiation_here;
246        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
247                     DiagID)
248          << Context.getTypeDeclType(Record)
249          << Active->InstantiationRange;
250      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
251        unsigned DiagID;
252        if (Function->getPrimaryTemplate())
253          DiagID = diag::note_function_template_spec_here;
254        else
255          DiagID = diag::note_template_member_function_here;
256        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
257                     DiagID)
258          << Function
259          << Active->InstantiationRange;
260      } else {
261        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
262                     diag::note_template_static_data_member_def_here)
263          << cast<VarDecl>(D)
264          << Active->InstantiationRange;
265      }
266      break;
267    }
268
269    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
270      TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
271      std::string TemplateArgsStr
272        = TemplateSpecializationType::PrintTemplateArgumentList(
273                                                         Active->TemplateArgs,
274                                                      Active->NumTemplateArgs,
275                                                      Context.PrintingPolicy);
276      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
277                   diag::note_default_arg_instantiation_here)
278        << (Template->getNameAsString() + TemplateArgsStr)
279        << Active->InstantiationRange;
280      break;
281    }
282
283    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
284      FunctionTemplateDecl *FnTmpl
285        = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
286      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
287                   diag::note_explicit_template_arg_substitution_here)
288        << FnTmpl << Active->InstantiationRange;
289      break;
290    }
291
292    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
293      if (ClassTemplatePartialSpecializationDecl *PartialSpec
294            = dyn_cast<ClassTemplatePartialSpecializationDecl>(
295                                                    (Decl *)Active->Entity)) {
296        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
297                     diag::note_partial_spec_deduct_instantiation_here)
298          << Context.getTypeDeclType(PartialSpec)
299          << Active->InstantiationRange;
300      } else {
301        FunctionTemplateDecl *FnTmpl
302          = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
303        Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
304                     diag::note_function_template_deduction_instantiation_here)
305          << FnTmpl << Active->InstantiationRange;
306      }
307      break;
308
309    case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
310      ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
311      FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
312
313      std::string TemplateArgsStr
314        = TemplateSpecializationType::PrintTemplateArgumentList(
315                                                         Active->TemplateArgs,
316                                                      Active->NumTemplateArgs,
317                                                      Context.PrintingPolicy);
318      Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr),
319                   diag::note_default_function_arg_instantiation_here)
320        << (FD->getNameAsString() + TemplateArgsStr)
321        << Active->InstantiationRange;
322      break;
323    }
324
325    }
326  }
327}
328
329bool Sema::isSFINAEContext() const {
330  using llvm::SmallVector;
331  for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
332         Active = ActiveTemplateInstantiations.rbegin(),
333         ActiveEnd = ActiveTemplateInstantiations.rend();
334       Active != ActiveEnd;
335       ++Active) {
336
337    switch(Active->Kind) {
338    case ActiveTemplateInstantiation::TemplateInstantiation:
339    case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
340
341      // This is a template instantiation, so there is no SFINAE.
342      return false;
343
344    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
345      // A default template argument instantiation may or may not be a
346      // SFINAE context; look further up the stack.
347      break;
348
349    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
350    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
351      // We're either substitution explicitly-specified template arguments
352      // or deduced template arguments, so SFINAE applies.
353      return true;
354    }
355  }
356
357  return false;
358}
359
360//===----------------------------------------------------------------------===/
361// Template Instantiation for Types
362//===----------------------------------------------------------------------===/
363namespace {
364  class VISIBILITY_HIDDEN TemplateInstantiator
365    : public TreeTransform<TemplateInstantiator> {
366    const MultiLevelTemplateArgumentList &TemplateArgs;
367    SourceLocation Loc;
368    DeclarationName Entity;
369
370  public:
371    typedef TreeTransform<TemplateInstantiator> inherited;
372
373    TemplateInstantiator(Sema &SemaRef,
374                         const MultiLevelTemplateArgumentList &TemplateArgs,
375                         SourceLocation Loc,
376                         DeclarationName Entity)
377      : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
378        Entity(Entity) { }
379
380    /// \brief Determine whether the given type \p T has already been
381    /// transformed.
382    ///
383    /// For the purposes of template instantiation, a type has already been
384    /// transformed if it is NULL or if it is not dependent.
385    bool AlreadyTransformed(QualType T) {
386      return T.isNull() || !T->isDependentType();
387    }
388
389    /// \brief Returns the location of the entity being instantiated, if known.
390    SourceLocation getBaseLocation() { return Loc; }
391
392    /// \brief Returns the name of the entity being instantiated, if any.
393    DeclarationName getBaseEntity() { return Entity; }
394
395    /// \brief Transform the given declaration by instantiating a reference to
396    /// this declaration.
397    Decl *TransformDecl(Decl *D);
398
399    /// \brief Transform the definition of the given declaration by
400    /// instantiating it.
401    Decl *TransformDefinition(Decl *D);
402
403    /// \bried Transform the first qualifier within a scope by instantiating the
404    /// declaration.
405    NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
406
407    /// \brief Rebuild the exception declaration and register the declaration
408    /// as an instantiated local.
409    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T,
410                                  DeclaratorInfo *Declarator,
411                                  IdentifierInfo *Name,
412                                  SourceLocation Loc, SourceRange TypeRange);
413
414    /// \brief Check for tag mismatches when instantiating an
415    /// elaborated type.
416    QualType RebuildElaboratedType(QualType T, ElaboratedType::TagKind Tag);
417
418    Sema::OwningExprResult TransformPredefinedExpr(PredefinedExpr *E);
419    Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E);
420
421    /// \brief Transforms a template type parameter type by performing
422    /// substitution of the corresponding template type argument.
423    QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
424                                           TemplateTypeParmTypeLoc TL);
425  };
426}
427
428Decl *TemplateInstantiator::TransformDecl(Decl *D) {
429  if (!D)
430    return 0;
431
432  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
433    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
434      assert(TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsDecl() &&
435             "Wrong kind of template template argument");
436      return cast<TemplateDecl>(TemplateArgs(TTP->getDepth(),
437                                             TTP->getPosition()).getAsDecl());
438    }
439
440    // If the corresponding template argument is NULL or non-existent, it's
441    // because we are performing instantiation from explicitly-specified
442    // template arguments in a function template, but there were some
443    // arguments left unspecified.
444    if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
445                                          TTP->getPosition()))
446      return D;
447
448    // FIXME: Implement depth reduction of template template parameters
449    assert(false &&
450      "Reducing depth of template template parameters is not yet implemented");
451  }
452
453  return SemaRef.FindInstantiatedDecl(cast<NamedDecl>(D), TemplateArgs);
454}
455
456Decl *TemplateInstantiator::TransformDefinition(Decl *D) {
457  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
458  if (!Inst)
459    return 0;
460
461  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
462  return Inst;
463}
464
465NamedDecl *
466TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
467                                                     SourceLocation Loc) {
468  // If the first part of the nested-name-specifier was a template type
469  // parameter, instantiate that type parameter down to a tag type.
470  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
471    const TemplateTypeParmType *TTP
472      = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
473    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
474      QualType T = TemplateArgs(TTP->getDepth(), TTP->getIndex()).getAsType();
475      if (T.isNull())
476        return cast_or_null<NamedDecl>(TransformDecl(D));
477
478      if (const TagType *Tag = T->getAs<TagType>())
479        return Tag->getDecl();
480
481      // The resulting type is not a tag; complain.
482      getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
483      return 0;
484    }
485  }
486
487  return cast_or_null<NamedDecl>(TransformDecl(D));
488}
489
490VarDecl *
491TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
492                                           QualType T,
493                                           DeclaratorInfo *Declarator,
494                                           IdentifierInfo *Name,
495                                           SourceLocation Loc,
496                                           SourceRange TypeRange) {
497  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator,
498                                                 Name, Loc, TypeRange);
499  if (Var && !Var->isInvalidDecl())
500    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
501  return Var;
502}
503
504QualType
505TemplateInstantiator::RebuildElaboratedType(QualType T,
506                                            ElaboratedType::TagKind Tag) {
507  if (const TagType *TT = T->getAs<TagType>()) {
508    TagDecl* TD = TT->getDecl();
509
510    // FIXME: this location is very wrong;  we really need typelocs.
511    SourceLocation TagLocation = TD->getTagKeywordLoc();
512
513    // FIXME: type might be anonymous.
514    IdentifierInfo *Id = TD->getIdentifier();
515
516    // TODO: should we even warn on struct/class mismatches for this?  Seems
517    // like it's likely to produce a lot of spurious errors.
518    if (!SemaRef.isAcceptableTagRedeclaration(TD, Tag, TagLocation, *Id)) {
519      SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
520        << Id
521        << CodeModificationHint::CreateReplacement(SourceRange(TagLocation),
522                                                   TD->getKindName());
523      SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
524    }
525  }
526
527  return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(T, Tag);
528}
529
530Sema::OwningExprResult
531TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
532  if (!E->isTypeDependent())
533    return SemaRef.Owned(E->Retain());
534
535  FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
536  assert(currentDecl && "Must have current function declaration when "
537                        "instantiating.");
538
539  PredefinedExpr::IdentType IT = E->getIdentType();
540
541  unsigned Length =
542    PredefinedExpr::ComputeName(getSema().Context, IT, currentDecl).length();
543
544  llvm::APInt LengthI(32, Length + 1);
545  QualType ResTy = getSema().Context.CharTy.withConst();
546  ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
547                                                 ArrayType::Normal, 0);
548  PredefinedExpr *PE =
549    new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
550  return getSema().Owned(PE);
551}
552
553Sema::OwningExprResult
554TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
555  // FIXME: Clean this up a bit
556  NamedDecl *D = E->getDecl();
557  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
558    if (NTTP->getDepth() >= TemplateArgs.getNumLevels()) {
559      assert(false && "Cannot reduce non-type template parameter depth yet");
560      return getSema().ExprError();
561    }
562
563    // If the corresponding template argument is NULL or non-existent, it's
564    // because we are performing instantiation from explicitly-specified
565    // template arguments in a function template, but there were some
566    // arguments left unspecified.
567    if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
568                                          NTTP->getPosition()))
569      return SemaRef.Owned(E->Retain());
570
571    const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(),
572                                               NTTP->getPosition());
573
574    // The template argument itself might be an expression, in which
575    // case we just return that expression.
576    if (Arg.getKind() == TemplateArgument::Expression)
577      return SemaRef.Owned(Arg.getAsExpr()->Retain());
578
579    if (Arg.getKind() == TemplateArgument::Declaration) {
580      ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
581
582      VD = cast_or_null<ValueDecl>(
583                              getSema().FindInstantiatedDecl(VD, TemplateArgs));
584      if (!VD)
585        return SemaRef.ExprError();
586
587      return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(),
588                                      /*FIXME:*/false, /*FIXME:*/false);
589    }
590
591    assert(Arg.getKind() == TemplateArgument::Integral);
592    QualType T = Arg.getIntegralType();
593    if (T->isCharType() || T->isWideCharType())
594      return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral(
595                                            Arg.getAsIntegral()->getZExtValue(),
596                                            T->isWideCharType(),
597                                            T,
598                                            E->getSourceRange().getBegin()));
599    if (T->isBooleanType())
600      return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr(
601                                          Arg.getAsIntegral()->getBoolValue(),
602                                          T,
603                                          E->getSourceRange().getBegin()));
604
605    assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T));
606    return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral(
607                                              *Arg.getAsIntegral(),
608                                              T,
609                                              E->getSourceRange().getBegin()));
610  }
611
612  NamedDecl *InstD = SemaRef.FindInstantiatedDecl(D, TemplateArgs);
613  if (!InstD)
614    return SemaRef.ExprError();
615
616  // If we instantiated an UnresolvedUsingDecl and got back an UsingDecl,
617  // we need to get the underlying decl.
618  // FIXME: Is this correct? Maybe FindInstantiatedDecl should do this?
619  InstD = InstD->getUnderlyingDecl();
620
621  // FIXME: nested-name-specifier for QualifiedDeclRefExpr
622  return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD,
623                                          /*FIXME:*/false,
624                                          /*FIXME:*/0,
625                                          /*FIXME:*/false);
626}
627
628QualType
629TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
630                                                TemplateTypeParmTypeLoc TL) {
631  TemplateTypeParmType *T = TL.getTypePtr();
632  if (T->getDepth() < TemplateArgs.getNumLevels()) {
633    // Replace the template type parameter with its corresponding
634    // template argument.
635
636    // If the corresponding template argument is NULL or doesn't exist, it's
637    // because we are performing instantiation from explicitly-specified
638    // template arguments in a function template class, but there were some
639    // arguments left unspecified.
640    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
641      TemplateTypeParmTypeLoc NewTL
642        = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
643      NewTL.setNameLoc(TL.getNameLoc());
644      return TL.getType();
645    }
646
647    assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind()
648             == TemplateArgument::Type &&
649           "Template argument kind mismatch");
650
651    QualType Replacement
652      = TemplateArgs(T->getDepth(), T->getIndex()).getAsType();
653
654    // TODO: only do this uniquing once, at the start of instantiation.
655    QualType Result
656      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
657    SubstTemplateTypeParmTypeLoc NewTL
658      = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
659    NewTL.setNameLoc(TL.getNameLoc());
660    return Result;
661  }
662
663  // The template type parameter comes from an inner template (e.g.,
664  // the template parameter list of a member template inside the
665  // template we are instantiating). Create a new template type
666  // parameter with the template "level" reduced by one.
667  QualType Result
668    = getSema().Context.getTemplateTypeParmType(T->getDepth()
669                                                 - TemplateArgs.getNumLevels(),
670                                                T->getIndex(),
671                                                T->isParameterPack(),
672                                                T->getName());
673  TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
674  NewTL.setNameLoc(TL.getNameLoc());
675  return Result;
676}
677
678/// \brief Perform substitution on the type T with a given set of template
679/// arguments.
680///
681/// This routine substitutes the given template arguments into the
682/// type T and produces the instantiated type.
683///
684/// \param T the type into which the template arguments will be
685/// substituted. If this type is not dependent, it will be returned
686/// immediately.
687///
688/// \param TemplateArgs the template arguments that will be
689/// substituted for the top-level template parameters within T.
690///
691/// \param Loc the location in the source code where this substitution
692/// is being performed. It will typically be the location of the
693/// declarator (if we're instantiating the type of some declaration)
694/// or the location of the type in the source code (if, e.g., we're
695/// instantiating the type of a cast expression).
696///
697/// \param Entity the name of the entity associated with a declaration
698/// being instantiated (if any). May be empty to indicate that there
699/// is no such entity (if, e.g., this is a type that occurs as part of
700/// a cast expression) or that the entity has no name (e.g., an
701/// unnamed function parameter).
702///
703/// \returns If the instantiation succeeds, the instantiated
704/// type. Otherwise, produces diagnostics and returns a NULL type.
705DeclaratorInfo *Sema::SubstType(DeclaratorInfo *T,
706                                const MultiLevelTemplateArgumentList &Args,
707                                SourceLocation Loc,
708                                DeclarationName Entity) {
709  assert(!ActiveTemplateInstantiations.empty() &&
710         "Cannot perform an instantiation without some context on the "
711         "instantiation stack");
712
713  if (!T->getType()->isDependentType())
714    return T;
715
716  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
717  return Instantiator.TransformType(T);
718}
719
720/// Deprecated form of the above.
721QualType Sema::SubstType(QualType T,
722                         const MultiLevelTemplateArgumentList &TemplateArgs,
723                         SourceLocation Loc, DeclarationName Entity) {
724  assert(!ActiveTemplateInstantiations.empty() &&
725         "Cannot perform an instantiation without some context on the "
726         "instantiation stack");
727
728  // If T is not a dependent type, there is nothing to do.
729  if (!T->isDependentType())
730    return T;
731
732  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
733  return Instantiator.TransformType(T);
734}
735
736/// \brief Perform substitution on the base class specifiers of the
737/// given class template specialization.
738///
739/// Produces a diagnostic and returns true on error, returns false and
740/// attaches the instantiated base classes to the class template
741/// specialization if successful.
742bool
743Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
744                          CXXRecordDecl *Pattern,
745                          const MultiLevelTemplateArgumentList &TemplateArgs) {
746  bool Invalid = false;
747  llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
748  for (ClassTemplateSpecializationDecl::base_class_iterator
749         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
750       Base != BaseEnd; ++Base) {
751    if (!Base->getType()->isDependentType()) {
752      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
753      continue;
754    }
755
756    QualType BaseType = SubstType(Base->getType(),
757                                  TemplateArgs,
758                                  Base->getSourceRange().getBegin(),
759                                  DeclarationName());
760    if (BaseType.isNull()) {
761      Invalid = true;
762      continue;
763    }
764
765    if (CXXBaseSpecifier *InstantiatedBase
766          = CheckBaseSpecifier(Instantiation,
767                               Base->getSourceRange(),
768                               Base->isVirtual(),
769                               Base->getAccessSpecifierAsWritten(),
770                               BaseType,
771                               /*FIXME: Not totally accurate */
772                               Base->getSourceRange().getBegin()))
773      InstantiatedBases.push_back(InstantiatedBase);
774    else
775      Invalid = true;
776  }
777
778  if (!Invalid &&
779      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
780                           InstantiatedBases.size()))
781    Invalid = true;
782
783  return Invalid;
784}
785
786/// \brief Instantiate the definition of a class from a given pattern.
787///
788/// \param PointOfInstantiation The point of instantiation within the
789/// source code.
790///
791/// \param Instantiation is the declaration whose definition is being
792/// instantiated. This will be either a class template specialization
793/// or a member class of a class template specialization.
794///
795/// \param Pattern is the pattern from which the instantiation
796/// occurs. This will be either the declaration of a class template or
797/// the declaration of a member class of a class template.
798///
799/// \param TemplateArgs The template arguments to be substituted into
800/// the pattern.
801///
802/// \param TSK the kind of implicit or explicit instantiation to perform.
803///
804/// \param Complain whether to complain if the class cannot be instantiated due
805/// to the lack of a definition.
806///
807/// \returns true if an error occurred, false otherwise.
808bool
809Sema::InstantiateClass(SourceLocation PointOfInstantiation,
810                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
811                       const MultiLevelTemplateArgumentList &TemplateArgs,
812                       TemplateSpecializationKind TSK,
813                       bool Complain) {
814  bool Invalid = false;
815
816  CXXRecordDecl *PatternDef
817    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
818  if (!PatternDef) {
819    if (!Complain) {
820      // Say nothing
821    } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
822      Diag(PointOfInstantiation,
823           diag::err_implicit_instantiate_member_undefined)
824        << Context.getTypeDeclType(Instantiation);
825      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
826    } else {
827      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
828        << (TSK != TSK_ImplicitInstantiation)
829        << Context.getTypeDeclType(Instantiation);
830      Diag(Pattern->getLocation(), diag::note_template_decl_here);
831    }
832    return true;
833  }
834  Pattern = PatternDef;
835
836  // \brief Record the point of instantiation.
837  if (MemberSpecializationInfo *MSInfo
838        = Instantiation->getMemberSpecializationInfo()) {
839    MSInfo->setTemplateSpecializationKind(TSK);
840    MSInfo->setPointOfInstantiation(PointOfInstantiation);
841  }
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  // Do substitution on the base class specifiers.
856  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
857    Invalid = true;
858
859  llvm::SmallVector<DeclPtrTy, 4> Fields;
860  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
861         MemberEnd = Pattern->decls_end();
862       Member != MemberEnd; ++Member) {
863    Decl *NewMember = SubstDecl(*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 if (UsingDecl *UD = dyn_cast<UsingDecl>(NewMember))
870        Instantiation->addDecl(UD);
871    } else {
872      // FIXME: Eventually, a NULL return will mean that one of the
873      // instantiations was a semantic disaster, and we'll want to set Invalid =
874      // true. For now, we expect to skip some members that we can't yet handle.
875    }
876  }
877
878  // Finish checking fields.
879  ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation),
880              Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
881              0);
882  if (Instantiation->isInvalidDecl())
883    Invalid = true;
884
885  // Add any implicitly-declared members that we might need.
886  if (!Invalid)
887    AddImplicitlyDeclaredMembersToClass(Instantiation);
888
889  // Exit the scope of this instantiation.
890  CurContext = PreviousContext;
891
892  if (!Invalid)
893    Consumer.HandleTagDeclDefinition(Instantiation);
894
895  // If this is an explicit instantiation, instantiate our members, too.
896  if (!Invalid && TSK != TSK_ImplicitInstantiation) {
897    Inst.Clear();
898    InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs,
899                            TSK);
900  }
901
902  return Invalid;
903}
904
905bool
906Sema::InstantiateClassTemplateSpecialization(
907                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
908                           TemplateSpecializationKind TSK,
909                           bool Complain) {
910  // Perform the actual instantiation on the canonical declaration.
911  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
912                                         ClassTemplateSpec->getCanonicalDecl());
913
914  // Check whether we have already instantiated or specialized this class
915  // template specialization.
916  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
917    if (ClassTemplateSpec->getSpecializationKind() ==
918          TSK_ExplicitInstantiationDeclaration &&
919        TSK == TSK_ExplicitInstantiationDefinition) {
920      // An explicit instantiation definition follows an explicit instantiation
921      // declaration (C++0x [temp.explicit]p10); go ahead and perform the
922      // explicit instantiation.
923      ClassTemplateSpec->setSpecializationKind(TSK);
924      InstantiateClassTemplateSpecializationMembers(
925                        /*FIXME?*/ClassTemplateSpec->getPointOfInstantiation(),
926                                  ClassTemplateSpec,
927                                  TSK);
928      return false;
929    }
930
931    // We can only instantiate something that hasn't already been
932    // instantiated or specialized. Fail without any diagnostics: our
933    // caller will provide an error message.
934    return true;
935  }
936
937  if (ClassTemplateSpec->isInvalidDecl())
938    return true;
939
940  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
941  CXXRecordDecl *Pattern = 0;
942
943  // C++ [temp.class.spec.match]p1:
944  //   When a class template is used in a context that requires an
945  //   instantiation of the class, it is necessary to determine
946  //   whether the instantiation is to be generated using the primary
947  //   template or one of the partial specializations. This is done by
948  //   matching the template arguments of the class template
949  //   specialization with the template argument lists of the partial
950  //   specializations.
951  typedef std::pair<ClassTemplatePartialSpecializationDecl *,
952                    TemplateArgumentList *> MatchResult;
953  llvm::SmallVector<MatchResult, 4> Matched;
954  for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
955         Partial = Template->getPartialSpecializations().begin(),
956         PartialEnd = Template->getPartialSpecializations().end();
957       Partial != PartialEnd;
958       ++Partial) {
959    TemplateDeductionInfo Info(Context);
960    if (TemplateDeductionResult Result
961          = DeduceTemplateArguments(&*Partial,
962                                    ClassTemplateSpec->getTemplateArgs(),
963                                    Info)) {
964      // FIXME: Store the failed-deduction information for use in
965      // diagnostics, later.
966      (void)Result;
967    } else {
968      Matched.push_back(std::make_pair(&*Partial, Info.take()));
969    }
970  }
971
972  if (Matched.size() == 1) {
973    //   -- If exactly one matching specialization is found, the
974    //      instantiation is generated from that specialization.
975    Pattern = Matched[0].first;
976    ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second);
977  } else if (Matched.size() > 1) {
978    //   -- If more than one matching specialization is found, the
979    //      partial order rules (14.5.4.2) are used to determine
980    //      whether one of the specializations is more specialized
981    //      than the others. If none of the specializations is more
982    //      specialized than all of the other matching
983    //      specializations, then the use of the class template is
984    //      ambiguous and the program is ill-formed.
985    llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
986    for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
987                                                  PEnd = Matched.end();
988         P != PEnd; ++P) {
989      if (getMoreSpecializedPartialSpecialization(P->first, Best->first)
990            == P->first)
991        Best = P;
992    }
993
994    // Determine if the best partial specialization is more specialized than
995    // the others.
996    bool Ambiguous = false;
997    for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
998                                                  PEnd = Matched.end();
999         P != PEnd; ++P) {
1000      if (P != Best &&
1001          getMoreSpecializedPartialSpecialization(P->first, Best->first)
1002            != Best->first) {
1003        Ambiguous = true;
1004        break;
1005      }
1006    }
1007
1008    if (Ambiguous) {
1009      // Partial ordering did not produce a clear winner. Complain.
1010      ClassTemplateSpec->setInvalidDecl();
1011      Diag(ClassTemplateSpec->getPointOfInstantiation(),
1012           diag::err_partial_spec_ordering_ambiguous)
1013        << ClassTemplateSpec;
1014
1015      // Print the matching partial specializations.
1016      for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1017                                                    PEnd = Matched.end();
1018           P != PEnd; ++P)
1019        Diag(P->first->getLocation(), diag::note_partial_spec_match)
1020          << getTemplateArgumentBindingsText(P->first->getTemplateParameters(),
1021                                             *P->second);
1022
1023      return true;
1024    }
1025
1026    // Instantiate using the best class template partial specialization.
1027    Pattern = Best->first;
1028    ClassTemplateSpec->setInstantiationOf(Best->first, Best->second);
1029  } else {
1030    //   -- If no matches are found, the instantiation is generated
1031    //      from the primary template.
1032    ClassTemplateDecl *OrigTemplate = Template;
1033    while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
1034      // If we've found an explicit specialization of this class template,
1035      // stop here and use that as the pattern.
1036      if (OrigTemplate->isMemberSpecialization())
1037        break;
1038
1039      OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
1040    }
1041
1042    Pattern = OrigTemplate->getTemplatedDecl();
1043  }
1044
1045  // Note that this is an instantiation.
1046  ClassTemplateSpec->setSpecializationKind(TSK);
1047
1048  bool Result = InstantiateClass(ClassTemplateSpec->getPointOfInstantiation(),
1049                                 ClassTemplateSpec, Pattern,
1050                              getTemplateInstantiationArgs(ClassTemplateSpec),
1051                                 TSK,
1052                                 Complain);
1053
1054  for (unsigned I = 0, N = Matched.size(); I != N; ++I) {
1055    // FIXME: Implement TemplateArgumentList::Destroy!
1056    //    if (Matched[I].first != Pattern)
1057    //      Matched[I].second->Destroy(Context);
1058  }
1059
1060  return Result;
1061}
1062
1063/// \brief Instantiates the definitions of all of the member
1064/// of the given class, which is an instantiation of a class template
1065/// or a member class of a template.
1066void
1067Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
1068                              CXXRecordDecl *Instantiation,
1069                        const MultiLevelTemplateArgumentList &TemplateArgs,
1070                              TemplateSpecializationKind TSK) {
1071  for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
1072                               DEnd = Instantiation->decls_end();
1073       D != DEnd; ++D) {
1074    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
1075      if (Function->getInstantiatedFromMemberFunction()) {
1076        // If this member was explicitly specialized, do nothing.
1077        if (Function->getTemplateSpecializationKind() ==
1078              TSK_ExplicitSpecialization)
1079          continue;
1080
1081        Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1082      }
1083
1084      if (!Function->getBody() && TSK == TSK_ExplicitInstantiationDefinition)
1085        InstantiateFunctionDefinition(PointOfInstantiation, Function);
1086    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
1087      if (Var->isStaticDataMember()) {
1088        // If this member was explicitly specialized, do nothing.
1089        if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1090          continue;
1091
1092        Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
1093
1094        if (TSK == TSK_ExplicitInstantiationDefinition)
1095          InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
1096      }
1097    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
1098      if (Record->isInjectedClassName())
1099        continue;
1100
1101      assert(Record->getInstantiatedFromMemberClass() &&
1102             "Missing instantiated-from-template information");
1103
1104      // If this member was explicitly specialized, do nothing.
1105      if (Record->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1106        continue;
1107
1108      if (!Record->getDefinition(Context))
1109        InstantiateClass(PointOfInstantiation, Record,
1110                         Record->getInstantiatedFromMemberClass(),
1111                         TemplateArgs,
1112                         TSK);
1113
1114      InstantiateClassMembers(PointOfInstantiation, Record, TemplateArgs,
1115                              TSK);
1116    }
1117  }
1118}
1119
1120/// \brief Instantiate the definitions of all of the members of the
1121/// given class template specialization, which was named as part of an
1122/// explicit instantiation.
1123void
1124Sema::InstantiateClassTemplateSpecializationMembers(
1125                                           SourceLocation PointOfInstantiation,
1126                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
1127                                               TemplateSpecializationKind TSK) {
1128  // C++0x [temp.explicit]p7:
1129  //   An explicit instantiation that names a class template
1130  //   specialization is an explicit instantion of the same kind
1131  //   (declaration or definition) of each of its members (not
1132  //   including members inherited from base classes) that has not
1133  //   been previously explicitly specialized in the translation unit
1134  //   containing the explicit instantiation, except as described
1135  //   below.
1136  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
1137                          getTemplateInstantiationArgs(ClassTemplateSpec),
1138                          TSK);
1139}
1140
1141Sema::OwningStmtResult
1142Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
1143  if (!S)
1144    return Owned(S);
1145
1146  TemplateInstantiator Instantiator(*this, TemplateArgs,
1147                                    SourceLocation(),
1148                                    DeclarationName());
1149  return Instantiator.TransformStmt(S);
1150}
1151
1152Sema::OwningExprResult
1153Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
1154  if (!E)
1155    return Owned(E);
1156
1157  TemplateInstantiator Instantiator(*this, TemplateArgs,
1158                                    SourceLocation(),
1159                                    DeclarationName());
1160  return Instantiator.TransformExpr(E);
1161}
1162
1163/// \brief Do template substitution on a nested-name-specifier.
1164NestedNameSpecifier *
1165Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS,
1166                               SourceRange Range,
1167                         const MultiLevelTemplateArgumentList &TemplateArgs) {
1168  TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(),
1169                                    DeclarationName());
1170  return Instantiator.TransformNestedNameSpecifier(NNS, Range);
1171}
1172
1173TemplateName
1174Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc,
1175                        const MultiLevelTemplateArgumentList &TemplateArgs) {
1176  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1177                                    DeclarationName());
1178  return Instantiator.TransformTemplateName(Name);
1179}
1180
1181TemplateArgument Sema::Subst(TemplateArgument Arg,
1182                         const MultiLevelTemplateArgumentList &TemplateArgs) {
1183  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
1184                                    DeclarationName());
1185  return Instantiator.TransformTemplateArgument(Arg);
1186}
1187