SemaTemplateInstantiate.cpp 122 KB

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