SemaTemplateInstantiate.cpp revision 5eada844fa70b6e2bc941dd7306f7a4fb1e8529d
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 "clang/Sema/SemaInternal.h"
14#include "TreeTransform.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/Initialization.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/Template.h"
24#include "clang/Sema/TemplateDeduction.h"
25
26using namespace clang;
27using namespace sema;
28
29//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
33/// \brief Retrieve the template argument list(s) that should be used to
34/// instantiate the definition of the given declaration.
35///
36/// \param D the declaration for which we are computing template instantiation
37/// arguments.
38///
39/// \param Innermost if non-NULL, the innermost template argument list.
40///
41/// \param RelativeToPrimary true if we should get the template
42/// arguments relative to the primary template, even when we're
43/// dealing with a specialization. This is only relevant for function
44/// template specializations.
45///
46/// \param Pattern If non-NULL, indicates the pattern from which we will be
47/// instantiating the definition of the given declaration, \p D. This is
48/// used to determine the proper set of template instantiation arguments for
49/// friend function template specializations.
50MultiLevelTemplateArgumentList
51Sema::getTemplateInstantiationArgs(NamedDecl *D,
52                                   const TemplateArgumentList *Innermost,
53                                   bool RelativeToPrimary,
54                                   const FunctionDecl *Pattern) {
55  // Accumulate the set of template argument lists in this structure.
56  MultiLevelTemplateArgumentList Result;
57
58  if (Innermost)
59    Result.addOuterTemplateArguments(Innermost);
60
61  DeclContext *Ctx = dyn_cast<DeclContext>(D);
62  if (!Ctx) {
63    Ctx = D->getDeclContext();
64
65    // If we have a template template parameter with translation unit context,
66    // then we're performing substitution into a default template argument of
67    // this template template parameter before we've constructed the template
68    // that will own this template template parameter. In this case, we
69    // use empty template parameter lists for all of the outer templates
70    // to avoid performing any substitutions.
71    if (Ctx->isTranslationUnit()) {
72      if (TemplateTemplateParmDecl *TTP
73                                      = dyn_cast<TemplateTemplateParmDecl>(D)) {
74        for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75          Result.addOuterTemplateArguments(0, 0);
76        return Result;
77      }
78    }
79  }
80
81  while (!Ctx->isFileContext()) {
82    // Add template arguments from a class template instantiation.
83    if (ClassTemplateSpecializationDecl *Spec
84          = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85      // We're done when we hit an explicit specialization.
86      if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87          !isa<ClassTemplatePartialSpecializationDecl>(Spec))
88        break;
89
90      Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
91
92      // If this class template specialization was instantiated from a
93      // specialized member that is a class template, we're done.
94      assert(Spec->getSpecializedTemplate() && "No class template?");
95      if (Spec->getSpecializedTemplate()->isMemberSpecialization())
96        break;
97    }
98    // Add template arguments from a function template specialization.
99    else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
100      if (!RelativeToPrimary &&
101          (Function->getTemplateSpecializationKind() ==
102                                                  TSK_ExplicitSpecialization &&
103           !Function->getClassScopeSpecializationPattern()))
104        break;
105
106      if (const TemplateArgumentList *TemplateArgs
107            = Function->getTemplateSpecializationArgs()) {
108        // Add the template arguments for this specialization.
109        Result.addOuterTemplateArguments(TemplateArgs);
110
111        // If this function was instantiated from a specialized member that is
112        // a function template, we're done.
113        assert(Function->getPrimaryTemplate() && "No function template?");
114        if (Function->getPrimaryTemplate()->isMemberSpecialization())
115          break;
116      } else if (FunctionTemplateDecl *FunTmpl
117                                   = Function->getDescribedFunctionTemplate()) {
118        // Add the "injected" template arguments.
119        std::pair<const TemplateArgument *, unsigned>
120          Injected = FunTmpl->getInjectedTemplateArgs();
121        Result.addOuterTemplateArguments(Injected.first, Injected.second);
122      }
123
124      // If this is a friend declaration and it declares an entity at
125      // namespace scope, take arguments from its lexical parent
126      // instead of its semantic parent, unless of course the pattern we're
127      // instantiating actually comes from the file's context!
128      if (Function->getFriendObjectKind() &&
129          Function->getDeclContext()->isFileContext() &&
130          (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
131        Ctx = Function->getLexicalDeclContext();
132        RelativeToPrimary = false;
133        continue;
134      }
135    } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136      if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137        QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138        const TemplateSpecializationType *TST
139          = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140        Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141        if (ClassTemplate->isMemberSpecialization())
142          break;
143      }
144    }
145
146    Ctx = Ctx->getParent();
147    RelativeToPrimary = false;
148  }
149
150  return Result;
151}
152
153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
154  switch (Kind) {
155  case TemplateInstantiation:
156  case ExceptionSpecInstantiation:
157  case DefaultTemplateArgumentInstantiation:
158  case DefaultFunctionArgumentInstantiation:
159  case ExplicitTemplateArgumentSubstitution:
160  case DeducedTemplateArgumentSubstitution:
161  case PriorTemplateArgumentSubstitution:
162    return true;
163
164  case DefaultTemplateArgumentChecking:
165    return false;
166  }
167
168  llvm_unreachable("Invalid InstantiationKind!");
169}
170
171Sema::InstantiatingTemplate::
172InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
173                      Decl *Entity,
174                      SourceRange InstantiationRange)
175  : SemaRef(SemaRef),
176    SavedInNonInstantiationSFINAEContext(
177                                        SemaRef.InNonInstantiationSFINAEContext)
178{
179  Invalid = CheckInstantiationDepth(PointOfInstantiation,
180                                    InstantiationRange);
181  if (!Invalid) {
182    ActiveTemplateInstantiation Inst;
183    Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
184    Inst.PointOfInstantiation = PointOfInstantiation;
185    Inst.Entity = Entity;
186    Inst.TemplateArgs = 0;
187    Inst.NumTemplateArgs = 0;
188    Inst.InstantiationRange = InstantiationRange;
189    SemaRef.InNonInstantiationSFINAEContext = false;
190    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
191  }
192}
193
194Sema::InstantiatingTemplate::
195InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
196                      FunctionDecl *Entity, ExceptionSpecification,
197                      SourceRange InstantiationRange)
198  : SemaRef(SemaRef),
199    SavedInNonInstantiationSFINAEContext(
200                                        SemaRef.InNonInstantiationSFINAEContext)
201{
202  Invalid = CheckInstantiationDepth(PointOfInstantiation,
203                                    InstantiationRange);
204  if (!Invalid) {
205    ActiveTemplateInstantiation Inst;
206    Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
207    Inst.PointOfInstantiation = PointOfInstantiation;
208    Inst.Entity = Entity;
209    Inst.TemplateArgs = 0;
210    Inst.NumTemplateArgs = 0;
211    Inst.InstantiationRange = InstantiationRange;
212    SemaRef.InNonInstantiationSFINAEContext = false;
213    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
214  }
215}
216
217Sema::InstantiatingTemplate::
218InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
219                      TemplateDecl *Template,
220                      ArrayRef<TemplateArgument> TemplateArgs,
221                      SourceRange InstantiationRange)
222  : SemaRef(SemaRef),
223    SavedInNonInstantiationSFINAEContext(
224                                     SemaRef.InNonInstantiationSFINAEContext)
225{
226  Invalid = CheckInstantiationDepth(PointOfInstantiation,
227                                    InstantiationRange);
228  if (!Invalid) {
229    ActiveTemplateInstantiation Inst;
230    Inst.Kind
231      = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
232    Inst.PointOfInstantiation = PointOfInstantiation;
233    Inst.Entity = Template;
234    Inst.TemplateArgs = TemplateArgs.data();
235    Inst.NumTemplateArgs = TemplateArgs.size();
236    Inst.InstantiationRange = InstantiationRange;
237    SemaRef.InNonInstantiationSFINAEContext = false;
238    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
239  }
240}
241
242Sema::InstantiatingTemplate::
243InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
244                      FunctionTemplateDecl *FunctionTemplate,
245                      ArrayRef<TemplateArgument> TemplateArgs,
246                      ActiveTemplateInstantiation::InstantiationKind Kind,
247                      sema::TemplateDeductionInfo &DeductionInfo,
248                      SourceRange InstantiationRange)
249  : SemaRef(SemaRef),
250    SavedInNonInstantiationSFINAEContext(
251                                     SemaRef.InNonInstantiationSFINAEContext)
252{
253  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
254  if (!Invalid) {
255    ActiveTemplateInstantiation Inst;
256    Inst.Kind = Kind;
257    Inst.PointOfInstantiation = PointOfInstantiation;
258    Inst.Entity = FunctionTemplate;
259    Inst.TemplateArgs = TemplateArgs.data();
260    Inst.NumTemplateArgs = TemplateArgs.size();
261    Inst.DeductionInfo = &DeductionInfo;
262    Inst.InstantiationRange = InstantiationRange;
263    SemaRef.InNonInstantiationSFINAEContext = false;
264    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
265
266    if (!Inst.isInstantiationRecord())
267      ++SemaRef.NonInstantiationEntries;
268  }
269}
270
271Sema::InstantiatingTemplate::
272InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
273                      ClassTemplatePartialSpecializationDecl *PartialSpec,
274                      ArrayRef<TemplateArgument> TemplateArgs,
275                      sema::TemplateDeductionInfo &DeductionInfo,
276                      SourceRange InstantiationRange)
277  : SemaRef(SemaRef),
278    SavedInNonInstantiationSFINAEContext(
279                                     SemaRef.InNonInstantiationSFINAEContext)
280{
281  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
282  if (!Invalid) {
283    ActiveTemplateInstantiation Inst;
284    Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
285    Inst.PointOfInstantiation = PointOfInstantiation;
286    Inst.Entity = PartialSpec;
287    Inst.TemplateArgs = TemplateArgs.data();
288    Inst.NumTemplateArgs = TemplateArgs.size();
289    Inst.DeductionInfo = &DeductionInfo;
290    Inst.InstantiationRange = InstantiationRange;
291    SemaRef.InNonInstantiationSFINAEContext = false;
292    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
293  }
294}
295
296Sema::InstantiatingTemplate::
297InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
298                      ParmVarDecl *Param,
299                      ArrayRef<TemplateArgument> TemplateArgs,
300                      SourceRange InstantiationRange)
301  : SemaRef(SemaRef),
302    SavedInNonInstantiationSFINAEContext(
303                                     SemaRef.InNonInstantiationSFINAEContext)
304{
305  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
306  if (!Invalid) {
307    ActiveTemplateInstantiation Inst;
308    Inst.Kind
309      = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
310    Inst.PointOfInstantiation = PointOfInstantiation;
311    Inst.Entity = Param;
312    Inst.TemplateArgs = TemplateArgs.data();
313    Inst.NumTemplateArgs = TemplateArgs.size();
314    Inst.InstantiationRange = InstantiationRange;
315    SemaRef.InNonInstantiationSFINAEContext = false;
316    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
317  }
318}
319
320Sema::InstantiatingTemplate::
321InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
322                      NamedDecl *Template, NonTypeTemplateParmDecl *Param,
323                      ArrayRef<TemplateArgument> TemplateArgs,
324                      SourceRange InstantiationRange)
325  : SemaRef(SemaRef),
326    SavedInNonInstantiationSFINAEContext(
327                                     SemaRef.InNonInstantiationSFINAEContext)
328{
329  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
330  if (!Invalid) {
331    ActiveTemplateInstantiation Inst;
332    Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
333    Inst.PointOfInstantiation = PointOfInstantiation;
334    Inst.Template = Template;
335    Inst.Entity = Param;
336    Inst.TemplateArgs = TemplateArgs.data();
337    Inst.NumTemplateArgs = TemplateArgs.size();
338    Inst.InstantiationRange = InstantiationRange;
339    SemaRef.InNonInstantiationSFINAEContext = false;
340    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
341  }
342}
343
344Sema::InstantiatingTemplate::
345InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
346                      NamedDecl *Template, TemplateTemplateParmDecl *Param,
347                      ArrayRef<TemplateArgument> TemplateArgs,
348                      SourceRange InstantiationRange)
349  : SemaRef(SemaRef),
350    SavedInNonInstantiationSFINAEContext(
351                                     SemaRef.InNonInstantiationSFINAEContext)
352{
353  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
354  if (!Invalid) {
355    ActiveTemplateInstantiation Inst;
356    Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
357    Inst.PointOfInstantiation = PointOfInstantiation;
358    Inst.Template = Template;
359    Inst.Entity = Param;
360    Inst.TemplateArgs = TemplateArgs.data();
361    Inst.NumTemplateArgs = TemplateArgs.size();
362    Inst.InstantiationRange = InstantiationRange;
363    SemaRef.InNonInstantiationSFINAEContext = false;
364    SemaRef.ActiveTemplateInstantiations.push_back(Inst);
365  }
366}
367
368Sema::InstantiatingTemplate::
369InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
370                      TemplateDecl *Template, NamedDecl *Param,
371                      ArrayRef<TemplateArgument> TemplateArgs,
372                      SourceRange InstantiationRange)
373  : SemaRef(SemaRef),
374    SavedInNonInstantiationSFINAEContext(
375                                     SemaRef.InNonInstantiationSFINAEContext)
376{
377  Invalid = false;
378
379  ActiveTemplateInstantiation Inst;
380  Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
381  Inst.PointOfInstantiation = PointOfInstantiation;
382  Inst.Template = Template;
383  Inst.Entity = Param;
384  Inst.TemplateArgs = TemplateArgs.data();
385  Inst.NumTemplateArgs = TemplateArgs.size();
386  Inst.InstantiationRange = InstantiationRange;
387  SemaRef.InNonInstantiationSFINAEContext = false;
388  SemaRef.ActiveTemplateInstantiations.push_back(Inst);
389
390  assert(!Inst.isInstantiationRecord());
391  ++SemaRef.NonInstantiationEntries;
392}
393
394void Sema::InstantiatingTemplate::Clear() {
395  if (!Invalid) {
396    if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
397      assert(SemaRef.NonInstantiationEntries > 0);
398      --SemaRef.NonInstantiationEntries;
399    }
400    SemaRef.InNonInstantiationSFINAEContext
401      = SavedInNonInstantiationSFINAEContext;
402    SemaRef.ActiveTemplateInstantiations.pop_back();
403    Invalid = true;
404  }
405}
406
407bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
408                                        SourceLocation PointOfInstantiation,
409                                           SourceRange InstantiationRange) {
410  assert(SemaRef.NonInstantiationEntries <=
411                                   SemaRef.ActiveTemplateInstantiations.size());
412  if ((SemaRef.ActiveTemplateInstantiations.size() -
413          SemaRef.NonInstantiationEntries)
414        <= SemaRef.getLangOpts().InstantiationDepth)
415    return false;
416
417  SemaRef.Diag(PointOfInstantiation,
418               diag::err_template_recursion_depth_exceeded)
419    << SemaRef.getLangOpts().InstantiationDepth
420    << InstantiationRange;
421  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
422    << SemaRef.getLangOpts().InstantiationDepth;
423  return true;
424}
425
426/// \brief Prints the current instantiation stack through a series of
427/// notes.
428void Sema::PrintInstantiationStack() {
429  // Determine which template instantiations to skip, if any.
430  unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
431  unsigned Limit = Diags.getTemplateBacktraceLimit();
432  if (Limit && Limit < ActiveTemplateInstantiations.size()) {
433    SkipStart = Limit / 2 + Limit % 2;
434    SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
435  }
436
437  // FIXME: In all of these cases, we need to show the template arguments
438  unsigned InstantiationIdx = 0;
439  for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
440         Active = ActiveTemplateInstantiations.rbegin(),
441         ActiveEnd = ActiveTemplateInstantiations.rend();
442       Active != ActiveEnd;
443       ++Active, ++InstantiationIdx) {
444    // Skip this instantiation?
445    if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
446      if (InstantiationIdx == SkipStart) {
447        // Note that we're skipping instantiations.
448        Diags.Report(Active->PointOfInstantiation,
449                     diag::note_instantiation_contexts_suppressed)
450          << unsigned(ActiveTemplateInstantiations.size() - Limit);
451      }
452      continue;
453    }
454
455    switch (Active->Kind) {
456    case ActiveTemplateInstantiation::TemplateInstantiation: {
457      Decl *D = Active->Entity;
458      if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
459        unsigned DiagID = diag::note_template_member_class_here;
460        if (isa<ClassTemplateSpecializationDecl>(Record))
461          DiagID = diag::note_template_class_instantiation_here;
462        Diags.Report(Active->PointOfInstantiation, DiagID)
463          << Context.getTypeDeclType(Record)
464          << Active->InstantiationRange;
465      } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
466        unsigned DiagID;
467        if (Function->getPrimaryTemplate())
468          DiagID = diag::note_function_template_spec_here;
469        else
470          DiagID = diag::note_template_member_function_here;
471        Diags.Report(Active->PointOfInstantiation, DiagID)
472          << Function
473          << Active->InstantiationRange;
474      } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
475        Diags.Report(Active->PointOfInstantiation,
476                     diag::note_template_static_data_member_def_here)
477          << VD
478          << Active->InstantiationRange;
479      } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
480        Diags.Report(Active->PointOfInstantiation,
481                     diag::note_template_enum_def_here)
482          << ED
483          << Active->InstantiationRange;
484      } else {
485        Diags.Report(Active->PointOfInstantiation,
486                     diag::note_template_type_alias_instantiation_here)
487          << cast<TypeAliasTemplateDecl>(D)
488          << Active->InstantiationRange;
489      }
490      break;
491    }
492
493    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
494      TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
495      SmallVector<char, 128> TemplateArgsStr;
496      llvm::raw_svector_ostream OS(TemplateArgsStr);
497      Template->printName(OS);
498      TemplateSpecializationType::PrintTemplateArgumentList(OS,
499                                                         Active->TemplateArgs,
500                                                      Active->NumTemplateArgs,
501                                                      getPrintingPolicy());
502      Diags.Report(Active->PointOfInstantiation,
503                   diag::note_default_arg_instantiation_here)
504        << OS.str()
505        << Active->InstantiationRange;
506      break;
507    }
508
509    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
510      FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
511      Diags.Report(Active->PointOfInstantiation,
512                   diag::note_explicit_template_arg_substitution_here)
513        << FnTmpl
514        << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
515                                           Active->TemplateArgs,
516                                           Active->NumTemplateArgs)
517        << Active->InstantiationRange;
518      break;
519    }
520
521    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
522      if (ClassTemplatePartialSpecializationDecl *PartialSpec =
523            dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
524        Diags.Report(Active->PointOfInstantiation,
525                     diag::note_partial_spec_deduct_instantiation_here)
526          << Context.getTypeDeclType(PartialSpec)
527          << getTemplateArgumentBindingsText(
528                                         PartialSpec->getTemplateParameters(),
529                                             Active->TemplateArgs,
530                                             Active->NumTemplateArgs)
531          << Active->InstantiationRange;
532      } else {
533        FunctionTemplateDecl *FnTmpl
534          = cast<FunctionTemplateDecl>(Active->Entity);
535        Diags.Report(Active->PointOfInstantiation,
536                     diag::note_function_template_deduction_instantiation_here)
537          << FnTmpl
538          << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
539                                             Active->TemplateArgs,
540                                             Active->NumTemplateArgs)
541          << Active->InstantiationRange;
542      }
543      break;
544
545    case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
546      ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
547      FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
548
549      SmallVector<char, 128> TemplateArgsStr;
550      llvm::raw_svector_ostream OS(TemplateArgsStr);
551      FD->printName(OS);
552      TemplateSpecializationType::PrintTemplateArgumentList(OS,
553                                                         Active->TemplateArgs,
554                                                      Active->NumTemplateArgs,
555                                                      getPrintingPolicy());
556      Diags.Report(Active->PointOfInstantiation,
557                   diag::note_default_function_arg_instantiation_here)
558        << OS.str()
559        << Active->InstantiationRange;
560      break;
561    }
562
563    case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
564      NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
565      std::string Name;
566      if (!Parm->getName().empty())
567        Name = std::string(" '") + Parm->getName().str() + "'";
568
569      TemplateParameterList *TemplateParams = 0;
570      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
571        TemplateParams = Template->getTemplateParameters();
572      else
573        TemplateParams =
574          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
575                                                      ->getTemplateParameters();
576      Diags.Report(Active->PointOfInstantiation,
577                   diag::note_prior_template_arg_substitution)
578        << isa<TemplateTemplateParmDecl>(Parm)
579        << Name
580        << getTemplateArgumentBindingsText(TemplateParams,
581                                           Active->TemplateArgs,
582                                           Active->NumTemplateArgs)
583        << Active->InstantiationRange;
584      break;
585    }
586
587    case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
588      TemplateParameterList *TemplateParams = 0;
589      if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
590        TemplateParams = Template->getTemplateParameters();
591      else
592        TemplateParams =
593          cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
594                                                      ->getTemplateParameters();
595
596      Diags.Report(Active->PointOfInstantiation,
597                   diag::note_template_default_arg_checking)
598        << getTemplateArgumentBindingsText(TemplateParams,
599                                           Active->TemplateArgs,
600                                           Active->NumTemplateArgs)
601        << Active->InstantiationRange;
602      break;
603    }
604
605    case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
606      Diags.Report(Active->PointOfInstantiation,
607                   diag::note_template_exception_spec_instantiation_here)
608        << cast<FunctionDecl>(Active->Entity)
609        << Active->InstantiationRange;
610      break;
611    }
612  }
613}
614
615Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
616  if (InNonInstantiationSFINAEContext)
617    return Optional<TemplateDeductionInfo *>(0);
618
619  for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
620         Active = ActiveTemplateInstantiations.rbegin(),
621         ActiveEnd = ActiveTemplateInstantiations.rend();
622       Active != ActiveEnd;
623       ++Active)
624  {
625    switch(Active->Kind) {
626    case ActiveTemplateInstantiation::TemplateInstantiation:
627      // An instantiation of an alias template may or may not be a SFINAE
628      // context, depending on what else is on the stack.
629      if (isa<TypeAliasTemplateDecl>(Active->Entity))
630        break;
631      // Fall through.
632    case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
633    case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
634      // This is a template instantiation, so there is no SFINAE.
635      return None;
636
637    case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
638    case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
639    case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
640      // A default template argument instantiation and substitution into
641      // template parameters with arguments for prior parameters may or may
642      // not be a SFINAE context; look further up the stack.
643      break;
644
645    case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
646    case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
647      // We're either substitution explicitly-specified template arguments
648      // or deduced template arguments, so SFINAE applies.
649      assert(Active->DeductionInfo && "Missing deduction info pointer");
650      return Active->DeductionInfo;
651    }
652  }
653
654  return None;
655}
656
657/// \brief Retrieve the depth and index of a parameter pack.
658static std::pair<unsigned, unsigned>
659getDepthAndIndex(NamedDecl *ND) {
660  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
661    return std::make_pair(TTP->getDepth(), TTP->getIndex());
662
663  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
664    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
665
666  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
667  return std::make_pair(TTP->getDepth(), TTP->getIndex());
668}
669
670//===----------------------------------------------------------------------===/
671// Template Instantiation for Types
672//===----------------------------------------------------------------------===/
673namespace {
674  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
675    const MultiLevelTemplateArgumentList &TemplateArgs;
676    SourceLocation Loc;
677    DeclarationName Entity;
678
679  public:
680    typedef TreeTransform<TemplateInstantiator> inherited;
681
682    TemplateInstantiator(Sema &SemaRef,
683                         const MultiLevelTemplateArgumentList &TemplateArgs,
684                         SourceLocation Loc,
685                         DeclarationName Entity)
686      : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
687        Entity(Entity) { }
688
689    /// \brief Determine whether the given type \p T has already been
690    /// transformed.
691    ///
692    /// For the purposes of template instantiation, a type has already been
693    /// transformed if it is NULL or if it is not dependent.
694    bool AlreadyTransformed(QualType T);
695
696    /// \brief Returns the location of the entity being instantiated, if known.
697    SourceLocation getBaseLocation() { return Loc; }
698
699    /// \brief Returns the name of the entity being instantiated, if any.
700    DeclarationName getBaseEntity() { return Entity; }
701
702    /// \brief Sets the "base" location and entity when that
703    /// information is known based on another transformation.
704    void setBase(SourceLocation Loc, DeclarationName Entity) {
705      this->Loc = Loc;
706      this->Entity = Entity;
707    }
708
709    bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
710                                 SourceRange PatternRange,
711                             llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
712                                 bool &ShouldExpand,
713                                 bool &RetainExpansion,
714                                 Optional<unsigned> &NumExpansions) {
715      return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
716                                                       PatternRange, Unexpanded,
717                                                       TemplateArgs,
718                                                       ShouldExpand,
719                                                       RetainExpansion,
720                                                       NumExpansions);
721    }
722
723    void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
724      SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
725    }
726
727    TemplateArgument ForgetPartiallySubstitutedPack() {
728      TemplateArgument Result;
729      if (NamedDecl *PartialPack
730            = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
731        MultiLevelTemplateArgumentList &TemplateArgs
732          = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
733        unsigned Depth, Index;
734        llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
735        if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
736          Result = TemplateArgs(Depth, Index);
737          TemplateArgs.setArgument(Depth, Index, TemplateArgument());
738        }
739      }
740
741      return Result;
742    }
743
744    void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
745      if (Arg.isNull())
746        return;
747
748      if (NamedDecl *PartialPack
749            = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
750        MultiLevelTemplateArgumentList &TemplateArgs
751        = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
752        unsigned Depth, Index;
753        llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
754        TemplateArgs.setArgument(Depth, Index, Arg);
755      }
756    }
757
758    /// \brief Transform the given declaration by instantiating a reference to
759    /// this declaration.
760    Decl *TransformDecl(SourceLocation Loc, Decl *D);
761
762    void transformAttrs(Decl *Old, Decl *New) {
763      SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
764    }
765
766    void transformedLocalDecl(Decl *Old, Decl *New) {
767      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
768    }
769
770    /// \brief Transform the definition of the given declaration by
771    /// instantiating it.
772    Decl *TransformDefinition(SourceLocation Loc, Decl *D);
773
774    /// \brief Transform the first qualifier within a scope by instantiating the
775    /// declaration.
776    NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
777
778    /// \brief Rebuild the exception declaration and register the declaration
779    /// as an instantiated local.
780    VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
781                                  TypeSourceInfo *Declarator,
782                                  SourceLocation StartLoc,
783                                  SourceLocation NameLoc,
784                                  IdentifierInfo *Name);
785
786    /// \brief Rebuild the Objective-C exception declaration and register the
787    /// declaration as an instantiated local.
788    VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
789                                      TypeSourceInfo *TSInfo, QualType T);
790
791    /// \brief Check for tag mismatches when instantiating an
792    /// elaborated type.
793    QualType RebuildElaboratedType(SourceLocation KeywordLoc,
794                                   ElaboratedTypeKeyword Keyword,
795                                   NestedNameSpecifierLoc QualifierLoc,
796                                   QualType T);
797
798    TemplateName TransformTemplateName(CXXScopeSpec &SS,
799                                       TemplateName Name,
800                                       SourceLocation NameLoc,
801                                       QualType ObjectType = QualType(),
802                                       NamedDecl *FirstQualifierInScope = 0);
803
804    ExprResult TransformPredefinedExpr(PredefinedExpr *E);
805    ExprResult TransformDeclRefExpr(DeclRefExpr *E);
806    ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
807
808    ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
809                                            NonTypeTemplateParmDecl *D);
810    ExprResult TransformSubstNonTypeTemplateParmPackExpr(
811                                           SubstNonTypeTemplateParmPackExpr *E);
812
813    /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
814    ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
815
816    /// \brief Transform a reference to a function parameter pack.
817    ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
818                                                ParmVarDecl *PD);
819
820    /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
821    /// expand a function parameter pack reference which refers to an expanded
822    /// pack.
823    ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
824
825    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
826                                        FunctionProtoTypeLoc TL);
827    QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
828                                        FunctionProtoTypeLoc TL,
829                                        CXXRecordDecl *ThisContext,
830                                        unsigned ThisTypeQuals);
831
832    ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
833                                            int indexAdjustment,
834                                            Optional<unsigned> NumExpansions,
835                                            bool ExpectParameterPack);
836
837    /// \brief Transforms a template type parameter type by performing
838    /// substitution of the corresponding template type argument.
839    QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
840                                           TemplateTypeParmTypeLoc TL);
841
842    /// \brief Transforms an already-substituted template type parameter pack
843    /// into either itself (if we aren't substituting into its pack expansion)
844    /// or the appropriate substituted argument.
845    QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
846                                           SubstTemplateTypeParmPackTypeLoc TL);
847
848    ExprResult TransformCallExpr(CallExpr *CE) {
849      getSema().CallsUndergoingInstantiation.push_back(CE);
850      ExprResult Result =
851          TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
852      getSema().CallsUndergoingInstantiation.pop_back();
853      return Result;
854    }
855
856    ExprResult TransformLambdaExpr(LambdaExpr *E) {
857      LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
858      return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
859    }
860
861    ExprResult TransformLambdaScope(LambdaExpr *E,
862                                    CXXMethodDecl *CallOperator) {
863      CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
864                                                     TSK_ImplicitInstantiation);
865      return TreeTransform<TemplateInstantiator>::
866         TransformLambdaScope(E, CallOperator);
867    }
868
869  private:
870    ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
871                                               SourceLocation loc,
872                                               TemplateArgument arg);
873  };
874}
875
876bool TemplateInstantiator::AlreadyTransformed(QualType T) {
877  if (T.isNull())
878    return true;
879
880  if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
881    return false;
882
883  getSema().MarkDeclarationsReferencedInType(Loc, T);
884  return true;
885}
886
887Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
888  if (!D)
889    return 0;
890
891  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
892    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
893      // If the corresponding template argument is NULL or non-existent, it's
894      // because we are performing instantiation from explicitly-specified
895      // template arguments in a function template, but there were some
896      // arguments left unspecified.
897      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
898                                            TTP->getPosition()))
899        return D;
900
901      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
902
903      if (TTP->isParameterPack()) {
904        assert(Arg.getKind() == TemplateArgument::Pack &&
905               "Missing argument pack");
906
907        assert(getSema().ArgumentPackSubstitutionIndex >= 0);
908        assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
909        Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
910      }
911
912      TemplateName Template = Arg.getAsTemplate();
913      assert(!Template.isNull() && Template.getAsTemplateDecl() &&
914             "Wrong kind of template template argument");
915      return Template.getAsTemplateDecl();
916    }
917
918    // Fall through to find the instantiated declaration for this template
919    // template parameter.
920  }
921
922  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
923}
924
925Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
926  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
927  if (!Inst)
928    return 0;
929
930  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
931  return Inst;
932}
933
934NamedDecl *
935TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
936                                                     SourceLocation Loc) {
937  // If the first part of the nested-name-specifier was a template type
938  // parameter, instantiate that type parameter down to a tag type.
939  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
940    const TemplateTypeParmType *TTP
941      = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
942
943    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
944      // FIXME: This needs testing w/ member access expressions.
945      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
946
947      if (TTP->isParameterPack()) {
948        assert(Arg.getKind() == TemplateArgument::Pack &&
949               "Missing argument pack");
950
951        if (getSema().ArgumentPackSubstitutionIndex == -1)
952          return 0;
953
954        assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
955        Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
956      }
957
958      QualType T = Arg.getAsType();
959      if (T.isNull())
960        return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
961
962      if (const TagType *Tag = T->getAs<TagType>())
963        return Tag->getDecl();
964
965      // The resulting type is not a tag; complain.
966      getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
967      return 0;
968    }
969  }
970
971  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
972}
973
974VarDecl *
975TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
976                                           TypeSourceInfo *Declarator,
977                                           SourceLocation StartLoc,
978                                           SourceLocation NameLoc,
979                                           IdentifierInfo *Name) {
980  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
981                                                 StartLoc, NameLoc, Name);
982  if (Var)
983    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
984  return Var;
985}
986
987VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
988                                                        TypeSourceInfo *TSInfo,
989                                                        QualType T) {
990  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
991  if (Var)
992    getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
993  return Var;
994}
995
996QualType
997TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
998                                            ElaboratedTypeKeyword Keyword,
999                                            NestedNameSpecifierLoc QualifierLoc,
1000                                            QualType T) {
1001  if (const TagType *TT = T->getAs<TagType>()) {
1002    TagDecl* TD = TT->getDecl();
1003
1004    SourceLocation TagLocation = KeywordLoc;
1005
1006    IdentifierInfo *Id = TD->getIdentifier();
1007
1008    // TODO: should we even warn on struct/class mismatches for this?  Seems
1009    // like it's likely to produce a lot of spurious errors.
1010    if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1011      TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1012      if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1013                                                TagLocation, *Id)) {
1014        SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1015          << Id
1016          << FixItHint::CreateReplacement(SourceRange(TagLocation),
1017                                          TD->getKindName());
1018        SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1019      }
1020    }
1021  }
1022
1023  return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1024                                                                    Keyword,
1025                                                                  QualifierLoc,
1026                                                                    T);
1027}
1028
1029TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1030                                                         TemplateName Name,
1031                                                         SourceLocation NameLoc,
1032                                                         QualType ObjectType,
1033                                             NamedDecl *FirstQualifierInScope) {
1034  if (TemplateTemplateParmDecl *TTP
1035       = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1036    if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1037      // If the corresponding template argument is NULL or non-existent, it's
1038      // because we are performing instantiation from explicitly-specified
1039      // template arguments in a function template, but there were some
1040      // arguments left unspecified.
1041      if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1042                                            TTP->getPosition()))
1043        return Name;
1044
1045      TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1046
1047      if (TTP->isParameterPack()) {
1048        assert(Arg.getKind() == TemplateArgument::Pack &&
1049               "Missing argument pack");
1050
1051        if (getSema().ArgumentPackSubstitutionIndex == -1) {
1052          // We have the template argument pack to substitute, but we're not
1053          // actually expanding the enclosing pack expansion yet. So, just
1054          // keep the entire argument pack.
1055          return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1056        }
1057
1058        assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1059        Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1060      }
1061
1062      TemplateName Template = Arg.getAsTemplate();
1063      assert(!Template.isNull() && "Null template template argument");
1064
1065      // We don't ever want to substitute for a qualified template name, since
1066      // the qualifier is handled separately. So, look through the qualified
1067      // template name to its underlying declaration.
1068      if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1069        Template = TemplateName(QTN->getTemplateDecl());
1070
1071      Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1072      return Template;
1073    }
1074  }
1075
1076  if (SubstTemplateTemplateParmPackStorage *SubstPack
1077      = Name.getAsSubstTemplateTemplateParmPack()) {
1078    if (getSema().ArgumentPackSubstitutionIndex == -1)
1079      return Name;
1080
1081    const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1082    assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1083           "Pack substitution index out-of-range");
1084    return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1085    .getAsTemplate();
1086  }
1087
1088  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1089                                          FirstQualifierInScope);
1090}
1091
1092ExprResult
1093TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1094  if (!E->isTypeDependent())
1095    return SemaRef.Owned(E);
1096
1097  FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1098  assert(currentDecl && "Must have current function declaration when "
1099                        "instantiating.");
1100
1101  PredefinedExpr::IdentType IT = E->getIdentType();
1102
1103  unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1104
1105  llvm::APInt LengthI(32, Length + 1);
1106  QualType ResTy;
1107  if (IT == PredefinedExpr::LFunction)
1108    ResTy = getSema().Context.WCharTy.withConst();
1109  else
1110    ResTy = getSema().Context.CharTy.withConst();
1111  ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1112                                                 ArrayType::Normal, 0);
1113  PredefinedExpr *PE =
1114    new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1115  return getSema().Owned(PE);
1116}
1117
1118ExprResult
1119TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1120                                               NonTypeTemplateParmDecl *NTTP) {
1121  // If the corresponding template argument is NULL or non-existent, it's
1122  // because we are performing instantiation from explicitly-specified
1123  // template arguments in a function template, but there were some
1124  // arguments left unspecified.
1125  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1126                                        NTTP->getPosition()))
1127    return SemaRef.Owned(E);
1128
1129  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1130  if (NTTP->isParameterPack()) {
1131    assert(Arg.getKind() == TemplateArgument::Pack &&
1132           "Missing argument pack");
1133
1134    if (getSema().ArgumentPackSubstitutionIndex == -1) {
1135      // We have an argument pack, but we can't select a particular argument
1136      // out of it yet. Therefore, we'll build an expression to hold on to that
1137      // argument pack.
1138      QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1139                                              E->getLocation(),
1140                                              NTTP->getDeclName());
1141      if (TargetType.isNull())
1142        return ExprError();
1143
1144      return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1145                                                                    NTTP,
1146                                                              E->getLocation(),
1147                                                                    Arg);
1148    }
1149
1150    assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1151    Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1152  }
1153
1154  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1155}
1156
1157ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1158                                                 NonTypeTemplateParmDecl *parm,
1159                                                 SourceLocation loc,
1160                                                 TemplateArgument arg) {
1161  ExprResult result;
1162  QualType type;
1163
1164  // If the argument is a pack expansion, the parameter must actually be a
1165  // parameter pack, and we should substitute the pattern itself, producing
1166  // an expression which contains an unexpanded parameter pack.
1167  if (arg.isPackExpansion()) {
1168    assert(parm->isParameterPack() && "pack expansion for non-pack");
1169    arg = arg.getPackExpansionPattern();
1170  }
1171
1172  // The template argument itself might be an expression, in which
1173  // case we just return that expression.
1174  if (arg.getKind() == TemplateArgument::Expression) {
1175    Expr *argExpr = arg.getAsExpr();
1176    result = SemaRef.Owned(argExpr);
1177    type = argExpr->getType();
1178
1179  } else if (arg.getKind() == TemplateArgument::Declaration ||
1180             arg.getKind() == TemplateArgument::NullPtr) {
1181    ValueDecl *VD;
1182    if (arg.getKind() == TemplateArgument::Declaration) {
1183      VD = cast<ValueDecl>(arg.getAsDecl());
1184
1185      // Find the instantiation of the template argument.  This is
1186      // required for nested templates.
1187      VD = cast_or_null<ValueDecl>(
1188             getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1189      if (!VD)
1190        return ExprError();
1191    } else {
1192      // Propagate NULL template argument.
1193      VD = 0;
1194    }
1195
1196    // Derive the type we want the substituted decl to have.  This had
1197    // better be non-dependent, or these checks will have serious problems.
1198    if (parm->isExpandedParameterPack()) {
1199      type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1200    } else if (parm->isParameterPack() &&
1201               isa<PackExpansionType>(parm->getType())) {
1202      type = SemaRef.SubstType(
1203                        cast<PackExpansionType>(parm->getType())->getPattern(),
1204                                     TemplateArgs, loc, parm->getDeclName());
1205    } else {
1206      type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1207                               loc, parm->getDeclName());
1208    }
1209    assert(!type.isNull() && "type substitution failed for param type");
1210    assert(!type->isDependentType() && "param type still dependent");
1211    result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1212
1213    if (!result.isInvalid()) type = result.get()->getType();
1214  } else {
1215    result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1216
1217    // Note that this type can be different from the type of 'result',
1218    // e.g. if it's an enum type.
1219    type = arg.getIntegralType();
1220  }
1221  if (result.isInvalid()) return ExprError();
1222
1223  Expr *resultExpr = result.take();
1224  return SemaRef.Owned(new (SemaRef.Context)
1225                SubstNonTypeTemplateParmExpr(type,
1226                                             resultExpr->getValueKind(),
1227                                             loc, parm, resultExpr));
1228}
1229
1230ExprResult
1231TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1232                                          SubstNonTypeTemplateParmPackExpr *E) {
1233  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1234    // We aren't expanding the parameter pack, so just return ourselves.
1235    return getSema().Owned(E);
1236  }
1237
1238  const TemplateArgument &ArgPack = E->getArgumentPack();
1239  unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1240  assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1241
1242  const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1243  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1244                                         E->getParameterPackLocation(),
1245                                         Arg);
1246}
1247
1248ExprResult
1249TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1250                                                SourceLocation Loc) {
1251  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1252  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1253}
1254
1255ExprResult
1256TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1257  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1258    // We can expand this parameter pack now.
1259    ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1260    ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1261    if (!VD)
1262      return ExprError();
1263    return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1264  }
1265
1266  QualType T = TransformType(E->getType());
1267  if (T.isNull())
1268    return ExprError();
1269
1270  // Transform each of the parameter expansions into the corresponding
1271  // parameters in the instantiation of the function decl.
1272  SmallVector<Decl *, 8> Parms;
1273  Parms.reserve(E->getNumExpansions());
1274  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1275       I != End; ++I) {
1276    ParmVarDecl *D =
1277        cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1278    if (!D)
1279      return ExprError();
1280    Parms.push_back(D);
1281  }
1282
1283  return FunctionParmPackExpr::Create(getSema().Context, T,
1284                                      E->getParameterPack(),
1285                                      E->getParameterPackLocation(), Parms);
1286}
1287
1288ExprResult
1289TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1290                                                       ParmVarDecl *PD) {
1291  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1292  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1293    = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1294  assert(Found && "no instantiation for parameter pack");
1295
1296  Decl *TransformedDecl;
1297  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1298    // If this is a reference to a function parameter pack which we can substitute
1299    // but can't yet expand, build a FunctionParmPackExpr for it.
1300    if (getSema().ArgumentPackSubstitutionIndex == -1) {
1301      QualType T = TransformType(E->getType());
1302      if (T.isNull())
1303        return ExprError();
1304      return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1305                                          E->getExprLoc(), *Pack);
1306    }
1307
1308    TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1309  } else {
1310    TransformedDecl = Found->get<Decl*>();
1311  }
1312
1313  // We have either an unexpanded pack or a specific expansion.
1314  return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1315                                   E->getExprLoc());
1316}
1317
1318ExprResult
1319TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1320  NamedDecl *D = E->getDecl();
1321
1322  // Handle references to non-type template parameters and non-type template
1323  // parameter packs.
1324  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1325    if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1326      return TransformTemplateParmRefExpr(E, NTTP);
1327
1328    // We have a non-type template parameter that isn't fully substituted;
1329    // FindInstantiatedDecl will find it in the local instantiation scope.
1330  }
1331
1332  // Handle references to function parameter packs.
1333  if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1334    if (PD->isParameterPack())
1335      return TransformFunctionParmPackRefExpr(E, PD);
1336
1337  return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1338}
1339
1340ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1341    CXXDefaultArgExpr *E) {
1342  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1343             getDescribedFunctionTemplate() &&
1344         "Default arg expressions are never formed in dependent cases.");
1345  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1346                           cast<FunctionDecl>(E->getParam()->getDeclContext()),
1347                                        E->getParam());
1348}
1349
1350QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1351                                                      FunctionProtoTypeLoc TL) {
1352  // We need a local instantiation scope for this function prototype.
1353  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1354  return inherited::TransformFunctionProtoType(TLB, TL);
1355}
1356
1357QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1358                                 FunctionProtoTypeLoc TL,
1359                                 CXXRecordDecl *ThisContext,
1360                                 unsigned ThisTypeQuals) {
1361  // We need a local instantiation scope for this function prototype.
1362  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1363  return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1364                                               ThisTypeQuals);
1365}
1366
1367ParmVarDecl *
1368TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1369                                                 int indexAdjustment,
1370                                               Optional<unsigned> NumExpansions,
1371                                                 bool ExpectParameterPack) {
1372  return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1373                                  NumExpansions, ExpectParameterPack);
1374}
1375
1376QualType
1377TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1378                                                TemplateTypeParmTypeLoc TL) {
1379  const TemplateTypeParmType *T = TL.getTypePtr();
1380  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1381    // Replace the template type parameter with its corresponding
1382    // template argument.
1383
1384    // If the corresponding template argument is NULL or doesn't exist, it's
1385    // because we are performing instantiation from explicitly-specified
1386    // template arguments in a function template class, but there were some
1387    // arguments left unspecified.
1388    if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1389      TemplateTypeParmTypeLoc NewTL
1390        = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1391      NewTL.setNameLoc(TL.getNameLoc());
1392      return TL.getType();
1393    }
1394
1395    TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1396
1397    if (T->isParameterPack()) {
1398      assert(Arg.getKind() == TemplateArgument::Pack &&
1399             "Missing argument pack");
1400
1401      if (getSema().ArgumentPackSubstitutionIndex == -1) {
1402        // We have the template argument pack, but we're not expanding the
1403        // enclosing pack expansion yet. Just save the template argument
1404        // pack for later substitution.
1405        QualType Result
1406          = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1407        SubstTemplateTypeParmPackTypeLoc NewTL
1408          = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1409        NewTL.setNameLoc(TL.getNameLoc());
1410        return Result;
1411      }
1412
1413      assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1414      Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1415    }
1416
1417    assert(Arg.getKind() == TemplateArgument::Type &&
1418           "Template argument kind mismatch");
1419
1420    QualType Replacement = Arg.getAsType();
1421
1422    // TODO: only do this uniquing once, at the start of instantiation.
1423    QualType Result
1424      = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1425    SubstTemplateTypeParmTypeLoc NewTL
1426      = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1427    NewTL.setNameLoc(TL.getNameLoc());
1428    return Result;
1429  }
1430
1431  // The template type parameter comes from an inner template (e.g.,
1432  // the template parameter list of a member template inside the
1433  // template we are instantiating). Create a new template type
1434  // parameter with the template "level" reduced by one.
1435  TemplateTypeParmDecl *NewTTPDecl = 0;
1436  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1437    NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1438                                  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1439
1440  QualType Result
1441    = getSema().Context.getTemplateTypeParmType(T->getDepth()
1442                                                 - TemplateArgs.getNumLevels(),
1443                                                T->getIndex(),
1444                                                T->isParameterPack(),
1445                                                NewTTPDecl);
1446  TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1447  NewTL.setNameLoc(TL.getNameLoc());
1448  return Result;
1449}
1450
1451QualType
1452TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1453                                                            TypeLocBuilder &TLB,
1454                                         SubstTemplateTypeParmPackTypeLoc TL) {
1455  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1456    // We aren't expanding the parameter pack, so just return ourselves.
1457    SubstTemplateTypeParmPackTypeLoc NewTL
1458      = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1459    NewTL.setNameLoc(TL.getNameLoc());
1460    return TL.getType();
1461  }
1462
1463  const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1464  unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1465  assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1466
1467  QualType Result = ArgPack.pack_begin()[Index].getAsType();
1468  Result = getSema().Context.getSubstTemplateTypeParmType(
1469                                      TL.getTypePtr()->getReplacedParameter(),
1470                                                          Result);
1471  SubstTemplateTypeParmTypeLoc NewTL
1472    = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1473  NewTL.setNameLoc(TL.getNameLoc());
1474  return Result;
1475}
1476
1477/// \brief Perform substitution on the type T with a given set of template
1478/// arguments.
1479///
1480/// This routine substitutes the given template arguments into the
1481/// type T and produces the instantiated type.
1482///
1483/// \param T the type into which the template arguments will be
1484/// substituted. If this type is not dependent, it will be returned
1485/// immediately.
1486///
1487/// \param Args the template arguments that will be
1488/// substituted for the top-level template parameters within T.
1489///
1490/// \param Loc the location in the source code where this substitution
1491/// is being performed. It will typically be the location of the
1492/// declarator (if we're instantiating the type of some declaration)
1493/// or the location of the type in the source code (if, e.g., we're
1494/// instantiating the type of a cast expression).
1495///
1496/// \param Entity the name of the entity associated with a declaration
1497/// being instantiated (if any). May be empty to indicate that there
1498/// is no such entity (if, e.g., this is a type that occurs as part of
1499/// a cast expression) or that the entity has no name (e.g., an
1500/// unnamed function parameter).
1501///
1502/// \returns If the instantiation succeeds, the instantiated
1503/// type. Otherwise, produces diagnostics and returns a NULL type.
1504TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1505                                const MultiLevelTemplateArgumentList &Args,
1506                                SourceLocation Loc,
1507                                DeclarationName Entity) {
1508  assert(!ActiveTemplateInstantiations.empty() &&
1509         "Cannot perform an instantiation without some context on the "
1510         "instantiation stack");
1511
1512  if (!T->getType()->isInstantiationDependentType() &&
1513      !T->getType()->isVariablyModifiedType())
1514    return T;
1515
1516  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1517  return Instantiator.TransformType(T);
1518}
1519
1520TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1521                                const MultiLevelTemplateArgumentList &Args,
1522                                SourceLocation Loc,
1523                                DeclarationName Entity) {
1524  assert(!ActiveTemplateInstantiations.empty() &&
1525         "Cannot perform an instantiation without some context on the "
1526         "instantiation stack");
1527
1528  if (TL.getType().isNull())
1529    return 0;
1530
1531  if (!TL.getType()->isInstantiationDependentType() &&
1532      !TL.getType()->isVariablyModifiedType()) {
1533    // FIXME: Make a copy of the TypeLoc data here, so that we can
1534    // return a new TypeSourceInfo. Inefficient!
1535    TypeLocBuilder TLB;
1536    TLB.pushFullCopy(TL);
1537    return TLB.getTypeSourceInfo(Context, TL.getType());
1538  }
1539
1540  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1541  TypeLocBuilder TLB;
1542  TLB.reserve(TL.getFullDataSize());
1543  QualType Result = Instantiator.TransformType(TLB, TL);
1544  if (Result.isNull())
1545    return 0;
1546
1547  return TLB.getTypeSourceInfo(Context, Result);
1548}
1549
1550/// Deprecated form of the above.
1551QualType Sema::SubstType(QualType T,
1552                         const MultiLevelTemplateArgumentList &TemplateArgs,
1553                         SourceLocation Loc, DeclarationName Entity) {
1554  assert(!ActiveTemplateInstantiations.empty() &&
1555         "Cannot perform an instantiation without some context on the "
1556         "instantiation stack");
1557
1558  // If T is not a dependent type or a variably-modified type, there
1559  // is nothing to do.
1560  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1561    return T;
1562
1563  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1564  return Instantiator.TransformType(T);
1565}
1566
1567static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1568  if (T->getType()->isInstantiationDependentType() ||
1569      T->getType()->isVariablyModifiedType())
1570    return true;
1571
1572  TypeLoc TL = T->getTypeLoc().IgnoreParens();
1573  if (!TL.getAs<FunctionProtoTypeLoc>())
1574    return false;
1575
1576  FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1577  for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1578    ParmVarDecl *P = FP.getArg(I);
1579
1580    // The parameter's type as written might be dependent even if the
1581    // decayed type was not dependent.
1582    if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1583      if (TSInfo->getType()->isInstantiationDependentType())
1584        return true;
1585
1586    // TODO: currently we always rebuild expressions.  When we
1587    // properly get lazier about this, we should use the same
1588    // logic to avoid rebuilding prototypes here.
1589    if (P->hasDefaultArg())
1590      return true;
1591  }
1592
1593  return false;
1594}
1595
1596/// A form of SubstType intended specifically for instantiating the
1597/// type of a FunctionDecl.  Its purpose is solely to force the
1598/// instantiation of default-argument expressions.
1599TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1600                                const MultiLevelTemplateArgumentList &Args,
1601                                SourceLocation Loc,
1602                                DeclarationName Entity,
1603                                CXXRecordDecl *ThisContext,
1604                                unsigned ThisTypeQuals) {
1605  assert(!ActiveTemplateInstantiations.empty() &&
1606         "Cannot perform an instantiation without some context on the "
1607         "instantiation stack");
1608
1609  if (!NeedsInstantiationAsFunctionType(T))
1610    return T;
1611
1612  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1613
1614  TypeLocBuilder TLB;
1615
1616  TypeLoc TL = T->getTypeLoc();
1617  TLB.reserve(TL.getFullDataSize());
1618
1619  QualType Result;
1620
1621  if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1622    Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
1623                                                     ThisTypeQuals);
1624  } else {
1625    Result = Instantiator.TransformType(TLB, TL);
1626  }
1627  if (Result.isNull())
1628    return 0;
1629
1630  return TLB.getTypeSourceInfo(Context, Result);
1631}
1632
1633ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1634                            const MultiLevelTemplateArgumentList &TemplateArgs,
1635                                    int indexAdjustment,
1636                                    Optional<unsigned> NumExpansions,
1637                                    bool ExpectParameterPack) {
1638  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1639  TypeSourceInfo *NewDI = 0;
1640
1641  TypeLoc OldTL = OldDI->getTypeLoc();
1642  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1643
1644    // We have a function parameter pack. Substitute into the pattern of the
1645    // expansion.
1646    NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1647                      OldParm->getLocation(), OldParm->getDeclName());
1648    if (!NewDI)
1649      return 0;
1650
1651    if (NewDI->getType()->containsUnexpandedParameterPack()) {
1652      // We still have unexpanded parameter packs, which means that
1653      // our function parameter is still a function parameter pack.
1654      // Therefore, make its type a pack expansion type.
1655      NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1656                                 NumExpansions);
1657    } else if (ExpectParameterPack) {
1658      // We expected to get a parameter pack but didn't (because the type
1659      // itself is not a pack expansion type), so complain. This can occur when
1660      // the substitution goes through an alias template that "loses" the
1661      // pack expansion.
1662      Diag(OldParm->getLocation(),
1663           diag::err_function_parameter_pack_without_parameter_packs)
1664        << NewDI->getType();
1665      return 0;
1666    }
1667  } else {
1668    NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1669                      OldParm->getDeclName());
1670  }
1671
1672  if (!NewDI)
1673    return 0;
1674
1675  if (NewDI->getType()->isVoidType()) {
1676    Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1677    return 0;
1678  }
1679
1680  ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1681                                        OldParm->getInnerLocStart(),
1682                                        OldParm->getLocation(),
1683                                        OldParm->getIdentifier(),
1684                                        NewDI->getType(), NewDI,
1685                                        OldParm->getStorageClass(),
1686                                        OldParm->getStorageClassAsWritten());
1687  if (!NewParm)
1688    return 0;
1689
1690  // Mark the (new) default argument as uninstantiated (if any).
1691  if (OldParm->hasUninstantiatedDefaultArg()) {
1692    Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1693    NewParm->setUninstantiatedDefaultArg(Arg);
1694  } else if (OldParm->hasUnparsedDefaultArg()) {
1695    NewParm->setUnparsedDefaultArg();
1696    UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1697  } else if (Expr *Arg = OldParm->getDefaultArg())
1698    // FIXME: if we non-lazily instantiated non-dependent default args for
1699    // non-dependent parameter types we could remove a bunch of duplicate
1700    // conversion warnings for such arguments.
1701    NewParm->setUninstantiatedDefaultArg(Arg);
1702
1703  NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1704
1705  if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1706    // Add the new parameter to the instantiated parameter pack.
1707    CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1708  } else {
1709    // Introduce an Old -> New mapping
1710    CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1711  }
1712
1713  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1714  // can be anything, is this right ?
1715  NewParm->setDeclContext(CurContext);
1716
1717  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1718                        OldParm->getFunctionScopeIndex() + indexAdjustment);
1719
1720  return NewParm;
1721}
1722
1723/// \brief Substitute the given template arguments into the given set of
1724/// parameters, producing the set of parameter types that would be generated
1725/// from such a substitution.
1726bool Sema::SubstParmTypes(SourceLocation Loc,
1727                          ParmVarDecl **Params, unsigned NumParams,
1728                          const MultiLevelTemplateArgumentList &TemplateArgs,
1729                          SmallVectorImpl<QualType> &ParamTypes,
1730                          SmallVectorImpl<ParmVarDecl *> *OutParams) {
1731  assert(!ActiveTemplateInstantiations.empty() &&
1732         "Cannot perform an instantiation without some context on the "
1733         "instantiation stack");
1734
1735  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1736                                    DeclarationName());
1737  return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
1738                                                  ParamTypes, OutParams);
1739}
1740
1741/// \brief Perform substitution on the base class specifiers of the
1742/// given class template specialization.
1743///
1744/// Produces a diagnostic and returns true on error, returns false and
1745/// attaches the instantiated base classes to the class template
1746/// specialization if successful.
1747bool
1748Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1749                          CXXRecordDecl *Pattern,
1750                          const MultiLevelTemplateArgumentList &TemplateArgs) {
1751  bool Invalid = false;
1752  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1753  for (ClassTemplateSpecializationDecl::base_class_iterator
1754         Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
1755       Base != BaseEnd; ++Base) {
1756    if (!Base->getType()->isDependentType()) {
1757      InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
1758      continue;
1759    }
1760
1761    SourceLocation EllipsisLoc;
1762    TypeSourceInfo *BaseTypeLoc;
1763    if (Base->isPackExpansion()) {
1764      // This is a pack expansion. See whether we should expand it now, or
1765      // wait until later.
1766      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1767      collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1768                                      Unexpanded);
1769      bool ShouldExpand = false;
1770      bool RetainExpansion = false;
1771      Optional<unsigned> NumExpansions;
1772      if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1773                                          Base->getSourceRange(),
1774                                          Unexpanded,
1775                                          TemplateArgs, ShouldExpand,
1776                                          RetainExpansion,
1777                                          NumExpansions)) {
1778        Invalid = true;
1779        continue;
1780      }
1781
1782      // If we should expand this pack expansion now, do so.
1783      if (ShouldExpand) {
1784        for (unsigned I = 0; I != *NumExpansions; ++I) {
1785            Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1786
1787          TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1788                                                  TemplateArgs,
1789                                              Base->getSourceRange().getBegin(),
1790                                                  DeclarationName());
1791          if (!BaseTypeLoc) {
1792            Invalid = true;
1793            continue;
1794          }
1795
1796          if (CXXBaseSpecifier *InstantiatedBase
1797                = CheckBaseSpecifier(Instantiation,
1798                                     Base->getSourceRange(),
1799                                     Base->isVirtual(),
1800                                     Base->getAccessSpecifierAsWritten(),
1801                                     BaseTypeLoc,
1802                                     SourceLocation()))
1803            InstantiatedBases.push_back(InstantiatedBase);
1804          else
1805            Invalid = true;
1806        }
1807
1808        continue;
1809      }
1810
1811      // The resulting base specifier will (still) be a pack expansion.
1812      EllipsisLoc = Base->getEllipsisLoc();
1813      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1814      BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1815                              TemplateArgs,
1816                              Base->getSourceRange().getBegin(),
1817                              DeclarationName());
1818    } else {
1819      BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1820                              TemplateArgs,
1821                              Base->getSourceRange().getBegin(),
1822                              DeclarationName());
1823    }
1824
1825    if (!BaseTypeLoc) {
1826      Invalid = true;
1827      continue;
1828    }
1829
1830    if (CXXBaseSpecifier *InstantiatedBase
1831          = CheckBaseSpecifier(Instantiation,
1832                               Base->getSourceRange(),
1833                               Base->isVirtual(),
1834                               Base->getAccessSpecifierAsWritten(),
1835                               BaseTypeLoc,
1836                               EllipsisLoc))
1837      InstantiatedBases.push_back(InstantiatedBase);
1838    else
1839      Invalid = true;
1840  }
1841
1842  if (!Invalid &&
1843      AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1844                           InstantiatedBases.size()))
1845    Invalid = true;
1846
1847  return Invalid;
1848}
1849
1850// Defined via #include from SemaTemplateInstantiateDecl.cpp
1851namespace clang {
1852  namespace sema {
1853    Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1854                            const MultiLevelTemplateArgumentList &TemplateArgs);
1855  }
1856}
1857
1858/// Determine whether we would be unable to instantiate this template (because
1859/// it either has no definition, or is in the process of being instantiated).
1860static bool DiagnoseUninstantiableTemplate(Sema &S,
1861                                           SourceLocation PointOfInstantiation,
1862                                           TagDecl *Instantiation,
1863                                           bool InstantiatedFromMember,
1864                                           TagDecl *Pattern,
1865                                           TagDecl *PatternDef,
1866                                           TemplateSpecializationKind TSK,
1867                                           bool Complain = true) {
1868  if (PatternDef && !PatternDef->isBeingDefined())
1869    return false;
1870
1871  if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1872    // Say nothing
1873  } else if (PatternDef) {
1874    assert(PatternDef->isBeingDefined());
1875    S.Diag(PointOfInstantiation,
1876           diag::err_template_instantiate_within_definition)
1877      << (TSK != TSK_ImplicitInstantiation)
1878      << S.Context.getTypeDeclType(Instantiation);
1879    // Not much point in noting the template declaration here, since
1880    // we're lexically inside it.
1881    Instantiation->setInvalidDecl();
1882  } else if (InstantiatedFromMember) {
1883    S.Diag(PointOfInstantiation,
1884           diag::err_implicit_instantiate_member_undefined)
1885      << S.Context.getTypeDeclType(Instantiation);
1886    S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1887  } else {
1888    S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1889      << (TSK != TSK_ImplicitInstantiation)
1890      << S.Context.getTypeDeclType(Instantiation);
1891    S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1892  }
1893
1894  // In general, Instantiation isn't marked invalid to get more than one
1895  // error for multiple undefined instantiations. But the code that does
1896  // explicit declaration -> explicit definition conversion can't handle
1897  // invalid declarations, so mark as invalid in that case.
1898  if (TSK == TSK_ExplicitInstantiationDeclaration)
1899    Instantiation->setInvalidDecl();
1900  return true;
1901}
1902
1903/// \brief Instantiate the definition of a class from a given pattern.
1904///
1905/// \param PointOfInstantiation The point of instantiation within the
1906/// source code.
1907///
1908/// \param Instantiation is the declaration whose definition is being
1909/// instantiated. This will be either a class template specialization
1910/// or a member class of a class template specialization.
1911///
1912/// \param Pattern is the pattern from which the instantiation
1913/// occurs. This will be either the declaration of a class template or
1914/// the declaration of a member class of a class template.
1915///
1916/// \param TemplateArgs The template arguments to be substituted into
1917/// the pattern.
1918///
1919/// \param TSK the kind of implicit or explicit instantiation to perform.
1920///
1921/// \param Complain whether to complain if the class cannot be instantiated due
1922/// to the lack of a definition.
1923///
1924/// \returns true if an error occurred, false otherwise.
1925bool
1926Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1927                       CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1928                       const MultiLevelTemplateArgumentList &TemplateArgs,
1929                       TemplateSpecializationKind TSK,
1930                       bool Complain) {
1931  CXXRecordDecl *PatternDef
1932    = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1933  if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1934                                Instantiation->getInstantiatedFromMemberClass(),
1935                                     Pattern, PatternDef, TSK, Complain))
1936    return true;
1937  Pattern = PatternDef;
1938
1939  // \brief Record the point of instantiation.
1940  if (MemberSpecializationInfo *MSInfo
1941        = Instantiation->getMemberSpecializationInfo()) {
1942    MSInfo->setTemplateSpecializationKind(TSK);
1943    MSInfo->setPointOfInstantiation(PointOfInstantiation);
1944  } else if (ClassTemplateSpecializationDecl *Spec
1945        = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1946    Spec->setTemplateSpecializationKind(TSK);
1947    Spec->setPointOfInstantiation(PointOfInstantiation);
1948  }
1949
1950  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1951  if (Inst)
1952    return true;
1953
1954  // Enter the scope of this instantiation. We don't use
1955  // PushDeclContext because we don't have a scope.
1956  ContextRAII SavedContext(*this, Instantiation);
1957  EnterExpressionEvaluationContext EvalContext(*this,
1958                                               Sema::PotentiallyEvaluated);
1959
1960  // If this is an instantiation of a local class, merge this local
1961  // instantiation scope with the enclosing scope. Otherwise, every
1962  // instantiation of a class has its own local instantiation scope.
1963  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1964  LocalInstantiationScope Scope(*this, MergeWithParentScope);
1965
1966  // Pull attributes from the pattern onto the instantiation.
1967  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1968
1969  // Start the definition of this instantiation.
1970  Instantiation->startDefinition();
1971
1972  Instantiation->setTagKind(Pattern->getTagKind());
1973
1974  // Do substitution on the base class specifiers.
1975  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1976    Instantiation->setInvalidDecl();
1977
1978  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1979  SmallVector<Decl*, 4> Fields;
1980  SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1981    FieldsWithMemberInitializers;
1982  // Delay instantiation of late parsed attributes.
1983  LateInstantiatedAttrVec LateAttrs;
1984  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1985
1986  for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1987         MemberEnd = Pattern->decls_end();
1988       Member != MemberEnd; ++Member) {
1989    // Don't instantiate members not belonging in this semantic context.
1990    // e.g. for:
1991    // @code
1992    //    template <int i> class A {
1993    //      class B *g;
1994    //    };
1995    // @endcode
1996    // 'class B' has the template as lexical context but semantically it is
1997    // introduced in namespace scope.
1998    if ((*Member)->getDeclContext() != Pattern)
1999      continue;
2000
2001    if ((*Member)->isInvalidDecl()) {
2002      Instantiation->setInvalidDecl();
2003      continue;
2004    }
2005
2006    Decl *NewMember = Instantiator.Visit(*Member);
2007    if (NewMember) {
2008      if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2009        Fields.push_back(Field);
2010        FieldDecl *OldField = cast<FieldDecl>(*Member);
2011        if (OldField->getInClassInitializer())
2012          FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2013                                                                Field));
2014      } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2015        // C++11 [temp.inst]p1: The implicit instantiation of a class template
2016        // specialization causes the implicit instantiation of the definitions
2017        // of unscoped member enumerations.
2018        // Record a point of instantiation for this implicit instantiation.
2019        if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2020            Enum->isCompleteDefinition()) {
2021          MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2022          assert(MSInfo && "no spec info for member enum specialization");
2023          MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2024          MSInfo->setPointOfInstantiation(PointOfInstantiation);
2025        }
2026      } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2027        if (SA->isFailed()) {
2028          // A static_assert failed. Bail out; instantiating this
2029          // class is probably not meaningful.
2030          Instantiation->setInvalidDecl();
2031          break;
2032        }
2033      }
2034
2035      if (NewMember->isInvalidDecl())
2036        Instantiation->setInvalidDecl();
2037    } else {
2038      // FIXME: Eventually, a NULL return will mean that one of the
2039      // instantiations was a semantic disaster, and we'll want to mark the
2040      // declaration invalid.
2041      // For now, we expect to skip some members that we can't yet handle.
2042    }
2043  }
2044
2045  // Finish checking fields.
2046  ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2047              SourceLocation(), SourceLocation(), 0);
2048  CheckCompletedCXXClass(Instantiation);
2049
2050  // Attach any in-class member initializers now the class is complete.
2051  // FIXME: We are supposed to defer instantiating these until they are needed.
2052  if (!FieldsWithMemberInitializers.empty()) {
2053    // C++11 [expr.prim.general]p4:
2054    //   Otherwise, if a member-declarator declares a non-static data member
2055    //  (9.2) of a class X, the expression this is a prvalue of type "pointer
2056    //  to X" within the optional brace-or-equal-initializer. It shall not
2057    //  appear elsewhere in the member-declarator.
2058    CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2059
2060    for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2061      FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2062      FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2063      Expr *OldInit = OldField->getInClassInitializer();
2064
2065      ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2066                                            /*CXXDirectInit=*/false);
2067      if (NewInit.isInvalid())
2068        NewField->setInvalidDecl();
2069      else {
2070        Expr *Init = NewInit.take();
2071        assert(Init && "no-argument initializer in class");
2072        assert(!isa<ParenListExpr>(Init) && "call-style init in class");
2073        ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
2074      }
2075    }
2076  }
2077  // Instantiate late parsed attributes, and attach them to their decls.
2078  // See Sema::InstantiateAttrs
2079  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2080       E = LateAttrs.end(); I != E; ++I) {
2081    assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2082    CurrentInstantiationScope = I->Scope;
2083    Attr *NewAttr =
2084      instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2085    I->NewDecl->addAttr(NewAttr);
2086    LocalInstantiationScope::deleteScopes(I->Scope,
2087                                          Instantiator.getStartingScope());
2088  }
2089  Instantiator.disableLateAttributeInstantiation();
2090  LateAttrs.clear();
2091
2092  ActOnFinishDelayedMemberInitializers(Instantiation);
2093
2094  if (TSK == TSK_ImplicitInstantiation) {
2095    Instantiation->setLocation(Pattern->getLocation());
2096    Instantiation->setLocStart(Pattern->getInnerLocStart());
2097    Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
2098  }
2099
2100  if (!Instantiation->isInvalidDecl()) {
2101    // Perform any dependent diagnostics from the pattern.
2102    PerformDependentDiagnostics(Pattern, TemplateArgs);
2103
2104    // Instantiate any out-of-line class template partial
2105    // specializations now.
2106    for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2107              P = Instantiator.delayed_partial_spec_begin(),
2108           PEnd = Instantiator.delayed_partial_spec_end();
2109         P != PEnd; ++P) {
2110      if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2111                                                                P->first,
2112                                                                P->second)) {
2113        Instantiation->setInvalidDecl();
2114        break;
2115      }
2116    }
2117  }
2118
2119  // Exit the scope of this instantiation.
2120  SavedContext.pop();
2121
2122  if (!Instantiation->isInvalidDecl()) {
2123    Consumer.HandleTagDeclDefinition(Instantiation);
2124
2125    // Always emit the vtable for an explicit instantiation definition
2126    // of a polymorphic class template specialization.
2127    if (TSK == TSK_ExplicitInstantiationDefinition)
2128      MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2129  }
2130
2131  return Instantiation->isInvalidDecl();
2132}
2133
2134/// \brief Instantiate the definition of an enum from a given pattern.
2135///
2136/// \param PointOfInstantiation The point of instantiation within the
2137///        source code.
2138/// \param Instantiation is the declaration whose definition is being
2139///        instantiated. This will be a member enumeration of a class
2140///        temploid specialization, or a local enumeration within a
2141///        function temploid specialization.
2142/// \param Pattern The templated declaration from which the instantiation
2143///        occurs.
2144/// \param TemplateArgs The template arguments to be substituted into
2145///        the pattern.
2146/// \param TSK The kind of implicit or explicit instantiation to perform.
2147///
2148/// \return \c true if an error occurred, \c false otherwise.
2149bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2150                           EnumDecl *Instantiation, EnumDecl *Pattern,
2151                           const MultiLevelTemplateArgumentList &TemplateArgs,
2152                           TemplateSpecializationKind TSK) {
2153  EnumDecl *PatternDef = Pattern->getDefinition();
2154  if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2155                                 Instantiation->getInstantiatedFromMemberEnum(),
2156                                     Pattern, PatternDef, TSK,/*Complain*/true))
2157    return true;
2158  Pattern = PatternDef;
2159
2160  // Record the point of instantiation.
2161  if (MemberSpecializationInfo *MSInfo
2162        = Instantiation->getMemberSpecializationInfo()) {
2163    MSInfo->setTemplateSpecializationKind(TSK);
2164    MSInfo->setPointOfInstantiation(PointOfInstantiation);
2165  }
2166
2167  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2168  if (Inst)
2169    return true;
2170
2171  // Enter the scope of this instantiation. We don't use
2172  // PushDeclContext because we don't have a scope.
2173  ContextRAII SavedContext(*this, Instantiation);
2174  EnterExpressionEvaluationContext EvalContext(*this,
2175                                               Sema::PotentiallyEvaluated);
2176
2177  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2178
2179  // Pull attributes from the pattern onto the instantiation.
2180  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2181
2182  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2183  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2184
2185  // Exit the scope of this instantiation.
2186  SavedContext.pop();
2187
2188  return Instantiation->isInvalidDecl();
2189}
2190
2191namespace {
2192  /// \brief A partial specialization whose template arguments have matched
2193  /// a given template-id.
2194  struct PartialSpecMatchResult {
2195    ClassTemplatePartialSpecializationDecl *Partial;
2196    TemplateArgumentList *Args;
2197  };
2198}
2199
2200bool
2201Sema::InstantiateClassTemplateSpecialization(
2202                           SourceLocation PointOfInstantiation,
2203                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
2204                           TemplateSpecializationKind TSK,
2205                           bool Complain) {
2206  // Perform the actual instantiation on the canonical declaration.
2207  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2208                                         ClassTemplateSpec->getCanonicalDecl());
2209
2210  // Check whether we have already instantiated or specialized this class
2211  // template specialization.
2212  if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2213    if (ClassTemplateSpec->getSpecializationKind() ==
2214          TSK_ExplicitInstantiationDeclaration &&
2215        TSK == TSK_ExplicitInstantiationDefinition) {
2216      // An explicit instantiation definition follows an explicit instantiation
2217      // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2218      // explicit instantiation.
2219      ClassTemplateSpec->setSpecializationKind(TSK);
2220
2221      // If this is an explicit instantiation definition, mark the
2222      // vtable as used.
2223      if (TSK == TSK_ExplicitInstantiationDefinition &&
2224          !ClassTemplateSpec->isInvalidDecl())
2225        MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2226
2227      return false;
2228    }
2229
2230    // We can only instantiate something that hasn't already been
2231    // instantiated or specialized. Fail without any diagnostics: our
2232    // caller will provide an error message.
2233    return true;
2234  }
2235
2236  if (ClassTemplateSpec->isInvalidDecl())
2237    return true;
2238
2239  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2240  CXXRecordDecl *Pattern = 0;
2241
2242  // C++ [temp.class.spec.match]p1:
2243  //   When a class template is used in a context that requires an
2244  //   instantiation of the class, it is necessary to determine
2245  //   whether the instantiation is to be generated using the primary
2246  //   template or one of the partial specializations. This is done by
2247  //   matching the template arguments of the class template
2248  //   specialization with the template argument lists of the partial
2249  //   specializations.
2250  typedef PartialSpecMatchResult MatchResult;
2251  SmallVector<MatchResult, 4> Matched;
2252  SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2253  Template->getPartialSpecializations(PartialSpecs);
2254  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2255    ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2256    TemplateDeductionInfo Info(PointOfInstantiation);
2257    if (TemplateDeductionResult Result
2258          = DeduceTemplateArguments(Partial,
2259                                    ClassTemplateSpec->getTemplateArgs(),
2260                                    Info)) {
2261      // FIXME: Store the failed-deduction information for use in
2262      // diagnostics, later.
2263      (void)Result;
2264    } else {
2265      Matched.push_back(PartialSpecMatchResult());
2266      Matched.back().Partial = Partial;
2267      Matched.back().Args = Info.take();
2268    }
2269  }
2270
2271  // If we're dealing with a member template where the template parameters
2272  // have been instantiated, this provides the original template parameters
2273  // from which the member template's parameters were instantiated.
2274  SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
2275
2276  if (Matched.size() >= 1) {
2277    SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2278    if (Matched.size() == 1) {
2279      //   -- If exactly one matching specialization is found, the
2280      //      instantiation is generated from that specialization.
2281      // We don't need to do anything for this.
2282    } else {
2283      //   -- If more than one matching specialization is found, the
2284      //      partial order rules (14.5.4.2) are used to determine
2285      //      whether one of the specializations is more specialized
2286      //      than the others. If none of the specializations is more
2287      //      specialized than all of the other matching
2288      //      specializations, then the use of the class template is
2289      //      ambiguous and the program is ill-formed.
2290      for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2291                                                    PEnd = Matched.end();
2292           P != PEnd; ++P) {
2293        if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2294                                                    PointOfInstantiation)
2295              == P->Partial)
2296          Best = P;
2297      }
2298
2299      // Determine if the best partial specialization is more specialized than
2300      // the others.
2301      bool Ambiguous = false;
2302      for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2303                                                    PEnd = Matched.end();
2304           P != PEnd; ++P) {
2305        if (P != Best &&
2306            getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2307                                                    PointOfInstantiation)
2308              != Best->Partial) {
2309          Ambiguous = true;
2310          break;
2311        }
2312      }
2313
2314      if (Ambiguous) {
2315        // Partial ordering did not produce a clear winner. Complain.
2316        ClassTemplateSpec->setInvalidDecl();
2317        Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2318          << ClassTemplateSpec;
2319
2320        // Print the matching partial specializations.
2321        for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2322                                                      PEnd = Matched.end();
2323             P != PEnd; ++P)
2324          Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2325            << getTemplateArgumentBindingsText(
2326                                            P->Partial->getTemplateParameters(),
2327                                               *P->Args);
2328
2329        return true;
2330      }
2331    }
2332
2333    // Instantiate using the best class template partial specialization.
2334    ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2335    while (OrigPartialSpec->getInstantiatedFromMember()) {
2336      // If we've found an explicit specialization of this class template,
2337      // stop here and use that as the pattern.
2338      if (OrigPartialSpec->isMemberSpecialization())
2339        break;
2340
2341      OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2342    }
2343
2344    Pattern = OrigPartialSpec;
2345    ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2346  } else {
2347    //   -- If no matches are found, the instantiation is generated
2348    //      from the primary template.
2349    ClassTemplateDecl *OrigTemplate = Template;
2350    while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2351      // If we've found an explicit specialization of this class template,
2352      // stop here and use that as the pattern.
2353      if (OrigTemplate->isMemberSpecialization())
2354        break;
2355
2356      OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2357    }
2358
2359    Pattern = OrigTemplate->getTemplatedDecl();
2360  }
2361
2362  bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2363                                 Pattern,
2364                                getTemplateInstantiationArgs(ClassTemplateSpec),
2365                                 TSK,
2366                                 Complain);
2367
2368  return Result;
2369}
2370
2371/// \brief Instantiates the definitions of all of the member
2372/// of the given class, which is an instantiation of a class template
2373/// or a member class of a template.
2374void
2375Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2376                              CXXRecordDecl *Instantiation,
2377                        const MultiLevelTemplateArgumentList &TemplateArgs,
2378                              TemplateSpecializationKind TSK) {
2379  for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2380                               DEnd = Instantiation->decls_end();
2381       D != DEnd; ++D) {
2382    bool SuppressNew = false;
2383    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
2384      if (FunctionDecl *Pattern
2385            = Function->getInstantiatedFromMemberFunction()) {
2386        MemberSpecializationInfo *MSInfo
2387          = Function->getMemberSpecializationInfo();
2388        assert(MSInfo && "No member specialization information?");
2389        if (MSInfo->getTemplateSpecializationKind()
2390                                                 == TSK_ExplicitSpecialization)
2391          continue;
2392
2393        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2394                                                   Function,
2395                                        MSInfo->getTemplateSpecializationKind(),
2396                                              MSInfo->getPointOfInstantiation(),
2397                                                   SuppressNew) ||
2398            SuppressNew)
2399          continue;
2400
2401        if (Function->isDefined())
2402          continue;
2403
2404        if (TSK == TSK_ExplicitInstantiationDefinition) {
2405          // C++0x [temp.explicit]p8:
2406          //   An explicit instantiation definition that names a class template
2407          //   specialization explicitly instantiates the class template
2408          //   specialization and is only an explicit instantiation definition
2409          //   of members whose definition is visible at the point of
2410          //   instantiation.
2411          if (!Pattern->isDefined())
2412            continue;
2413
2414          Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2415
2416          InstantiateFunctionDefinition(PointOfInstantiation, Function);
2417        } else {
2418          Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2419        }
2420      }
2421    } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
2422      if (Var->isStaticDataMember()) {
2423        MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2424        assert(MSInfo && "No member specialization information?");
2425        if (MSInfo->getTemplateSpecializationKind()
2426                                                 == TSK_ExplicitSpecialization)
2427          continue;
2428
2429        if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2430                                                   Var,
2431                                        MSInfo->getTemplateSpecializationKind(),
2432                                              MSInfo->getPointOfInstantiation(),
2433                                                   SuppressNew) ||
2434            SuppressNew)
2435          continue;
2436
2437        if (TSK == TSK_ExplicitInstantiationDefinition) {
2438          // C++0x [temp.explicit]p8:
2439          //   An explicit instantiation definition that names a class template
2440          //   specialization explicitly instantiates the class template
2441          //   specialization and is only an explicit instantiation definition
2442          //   of members whose definition is visible at the point of
2443          //   instantiation.
2444          if (!Var->getInstantiatedFromStaticDataMember()
2445                                                     ->getOutOfLineDefinition())
2446            continue;
2447
2448          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2449          InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2450        } else {
2451          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2452        }
2453      }
2454    } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
2455      // Always skip the injected-class-name, along with any
2456      // redeclarations of nested classes, since both would cause us
2457      // to try to instantiate the members of a class twice.
2458      if (Record->isInjectedClassName() || Record->getPreviousDecl())
2459        continue;
2460
2461      MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2462      assert(MSInfo && "No member specialization information?");
2463
2464      if (MSInfo->getTemplateSpecializationKind()
2465                                                == TSK_ExplicitSpecialization)
2466        continue;
2467
2468      if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2469                                                 Record,
2470                                        MSInfo->getTemplateSpecializationKind(),
2471                                              MSInfo->getPointOfInstantiation(),
2472                                                 SuppressNew) ||
2473          SuppressNew)
2474        continue;
2475
2476      CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2477      assert(Pattern && "Missing instantiated-from-template information");
2478
2479      if (!Record->getDefinition()) {
2480        if (!Pattern->getDefinition()) {
2481          // C++0x [temp.explicit]p8:
2482          //   An explicit instantiation definition that names a class template
2483          //   specialization explicitly instantiates the class template
2484          //   specialization and is only an explicit instantiation definition
2485          //   of members whose definition is visible at the point of
2486          //   instantiation.
2487          if (TSK == TSK_ExplicitInstantiationDeclaration) {
2488            MSInfo->setTemplateSpecializationKind(TSK);
2489            MSInfo->setPointOfInstantiation(PointOfInstantiation);
2490          }
2491
2492          continue;
2493        }
2494
2495        InstantiateClass(PointOfInstantiation, Record, Pattern,
2496                         TemplateArgs,
2497                         TSK);
2498      } else {
2499        if (TSK == TSK_ExplicitInstantiationDefinition &&
2500            Record->getTemplateSpecializationKind() ==
2501                TSK_ExplicitInstantiationDeclaration) {
2502          Record->setTemplateSpecializationKind(TSK);
2503          MarkVTableUsed(PointOfInstantiation, Record, true);
2504        }
2505      }
2506
2507      Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2508      if (Pattern)
2509        InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2510                                TSK);
2511    } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2512      MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2513      assert(MSInfo && "No member specialization information?");
2514
2515      if (MSInfo->getTemplateSpecializationKind()
2516            == TSK_ExplicitSpecialization)
2517        continue;
2518
2519      if (CheckSpecializationInstantiationRedecl(
2520            PointOfInstantiation, TSK, Enum,
2521            MSInfo->getTemplateSpecializationKind(),
2522            MSInfo->getPointOfInstantiation(), SuppressNew) ||
2523          SuppressNew)
2524        continue;
2525
2526      if (Enum->getDefinition())
2527        continue;
2528
2529      EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2530      assert(Pattern && "Missing instantiated-from-template information");
2531
2532      if (TSK == TSK_ExplicitInstantiationDefinition) {
2533        if (!Pattern->getDefinition())
2534          continue;
2535
2536        InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2537      } else {
2538        MSInfo->setTemplateSpecializationKind(TSK);
2539        MSInfo->setPointOfInstantiation(PointOfInstantiation);
2540      }
2541    }
2542  }
2543}
2544
2545/// \brief Instantiate the definitions of all of the members of the
2546/// given class template specialization, which was named as part of an
2547/// explicit instantiation.
2548void
2549Sema::InstantiateClassTemplateSpecializationMembers(
2550                                           SourceLocation PointOfInstantiation,
2551                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
2552                                               TemplateSpecializationKind TSK) {
2553  // C++0x [temp.explicit]p7:
2554  //   An explicit instantiation that names a class template
2555  //   specialization is an explicit instantion of the same kind
2556  //   (declaration or definition) of each of its members (not
2557  //   including members inherited from base classes) that has not
2558  //   been previously explicitly specialized in the translation unit
2559  //   containing the explicit instantiation, except as described
2560  //   below.
2561  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2562                          getTemplateInstantiationArgs(ClassTemplateSpec),
2563                          TSK);
2564}
2565
2566StmtResult
2567Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2568  if (!S)
2569    return Owned(S);
2570
2571  TemplateInstantiator Instantiator(*this, TemplateArgs,
2572                                    SourceLocation(),
2573                                    DeclarationName());
2574  return Instantiator.TransformStmt(S);
2575}
2576
2577ExprResult
2578Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2579  if (!E)
2580    return Owned(E);
2581
2582  TemplateInstantiator Instantiator(*this, TemplateArgs,
2583                                    SourceLocation(),
2584                                    DeclarationName());
2585  return Instantiator.TransformExpr(E);
2586}
2587
2588ExprResult Sema::SubstInitializer(Expr *Init,
2589                          const MultiLevelTemplateArgumentList &TemplateArgs,
2590                          bool CXXDirectInit) {
2591  TemplateInstantiator Instantiator(*this, TemplateArgs,
2592                                    SourceLocation(),
2593                                    DeclarationName());
2594  return Instantiator.TransformInitializer(Init, CXXDirectInit);
2595}
2596
2597bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2598                      const MultiLevelTemplateArgumentList &TemplateArgs,
2599                      SmallVectorImpl<Expr *> &Outputs) {
2600  if (NumExprs == 0)
2601    return false;
2602
2603  TemplateInstantiator Instantiator(*this, TemplateArgs,
2604                                    SourceLocation(),
2605                                    DeclarationName());
2606  return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2607}
2608
2609NestedNameSpecifierLoc
2610Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2611                        const MultiLevelTemplateArgumentList &TemplateArgs) {
2612  if (!NNS)
2613    return NestedNameSpecifierLoc();
2614
2615  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2616                                    DeclarationName());
2617  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2618}
2619
2620/// \brief Do template substitution on declaration name info.
2621DeclarationNameInfo
2622Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2623                         const MultiLevelTemplateArgumentList &TemplateArgs) {
2624  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2625                                    NameInfo.getName());
2626  return Instantiator.TransformDeclarationNameInfo(NameInfo);
2627}
2628
2629TemplateName
2630Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2631                        TemplateName Name, SourceLocation Loc,
2632                        const MultiLevelTemplateArgumentList &TemplateArgs) {
2633  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2634                                    DeclarationName());
2635  CXXScopeSpec SS;
2636  SS.Adopt(QualifierLoc);
2637  return Instantiator.TransformTemplateName(SS, Name, Loc);
2638}
2639
2640bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2641                 TemplateArgumentListInfo &Result,
2642                 const MultiLevelTemplateArgumentList &TemplateArgs) {
2643  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2644                                    DeclarationName());
2645
2646  return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2647}
2648
2649
2650static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2651  // When storing ParmVarDecls in the local instantiation scope, we always
2652  // want to use the ParmVarDecl from the canonical function declaration,
2653  // since the map is then valid for any redeclaration or definition of that
2654  // function.
2655  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2656    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2657      unsigned i = PV->getFunctionScopeIndex();
2658      return FD->getCanonicalDecl()->getParamDecl(i);
2659    }
2660  }
2661  return D;
2662}
2663
2664
2665llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2666LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2667  D = getCanonicalParmVarDecl(D);
2668  for (LocalInstantiationScope *Current = this; Current;
2669       Current = Current->Outer) {
2670
2671    // Check if we found something within this scope.
2672    const Decl *CheckD = D;
2673    do {
2674      LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2675      if (Found != Current->LocalDecls.end())
2676        return &Found->second;
2677
2678      // If this is a tag declaration, it's possible that we need to look for
2679      // a previous declaration.
2680      if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2681        CheckD = Tag->getPreviousDecl();
2682      else
2683        CheckD = 0;
2684    } while (CheckD);
2685
2686    // If we aren't combined with our outer scope, we're done.
2687    if (!Current->CombineWithOuterScope)
2688      break;
2689  }
2690
2691  // If we didn't find the decl, then we either have a sema bug, or we have a
2692  // forward reference to a label declaration.  Return null to indicate that
2693  // we have an uninstantiated label.
2694  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2695  return 0;
2696}
2697
2698void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2699  D = getCanonicalParmVarDecl(D);
2700  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2701  if (Stored.isNull())
2702    Stored = Inst;
2703  else if (Stored.is<Decl *>()) {
2704    assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2705    Stored = Inst;
2706  } else
2707    LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
2708}
2709
2710void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2711                                                       Decl *Inst) {
2712  D = getCanonicalParmVarDecl(D);
2713  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2714  Pack->push_back(Inst);
2715}
2716
2717void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2718  D = getCanonicalParmVarDecl(D);
2719  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2720  assert(Stored.isNull() && "Already instantiated this local");
2721  DeclArgumentPack *Pack = new DeclArgumentPack;
2722  Stored = Pack;
2723  ArgumentPacks.push_back(Pack);
2724}
2725
2726void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2727                                          const TemplateArgument *ExplicitArgs,
2728                                                    unsigned NumExplicitArgs) {
2729  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2730         "Already have a partially-substituted pack");
2731  assert((!PartiallySubstitutedPack
2732          || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2733         "Wrong number of arguments in partially-substituted pack");
2734  PartiallySubstitutedPack = Pack;
2735  ArgsInPartiallySubstitutedPack = ExplicitArgs;
2736  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2737}
2738
2739NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2740                                         const TemplateArgument **ExplicitArgs,
2741                                              unsigned *NumExplicitArgs) const {
2742  if (ExplicitArgs)
2743    *ExplicitArgs = 0;
2744  if (NumExplicitArgs)
2745    *NumExplicitArgs = 0;
2746
2747  for (const LocalInstantiationScope *Current = this; Current;
2748       Current = Current->Outer) {
2749    if (Current->PartiallySubstitutedPack) {
2750      if (ExplicitArgs)
2751        *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2752      if (NumExplicitArgs)
2753        *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2754
2755      return Current->PartiallySubstitutedPack;
2756    }
2757
2758    if (!Current->CombineWithOuterScope)
2759      break;
2760  }
2761
2762  return 0;
2763}
2764