Clang Project

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