SemaTemplateVariadic.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //===----------------------------------------------------------------------===/
  7. //
  8. // This file implements semantic analysis for C++0x variadic templates.
  9. //===----------------------------------------------------------------------===/
  10. #include "clang/Sema/Sema.h"
  11. #include "TypeLocBuilder.h"
  12. #include "clang/AST/Expr.h"
  13. #include "clang/AST/RecursiveASTVisitor.h"
  14. #include "clang/AST/TypeLoc.h"
  15. #include "clang/Sema/Lookup.h"
  16. #include "clang/Sema/ParsedTemplate.h"
  17. #include "clang/Sema/ScopeInfo.h"
  18. #include "clang/Sema/SemaInternal.h"
  19. #include "clang/Sema/Template.h"
  20. #include <optional>
  21. using namespace clang;
  22. //----------------------------------------------------------------------------
  23. // Visitor that collects unexpanded parameter packs
  24. //----------------------------------------------------------------------------
  25. namespace {
  26. /// A class that collects unexpanded parameter packs.
  27. class CollectUnexpandedParameterPacksVisitor :
  28. public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
  29. {
  30. typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
  31. inherited;
  32. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
  33. bool InLambda = false;
  34. unsigned DepthLimit = (unsigned)-1;
  35. void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
  36. if (auto *VD = dyn_cast<VarDecl>(ND)) {
  37. // For now, the only problematic case is a generic lambda's templated
  38. // call operator, so we don't need to look for all the other ways we
  39. // could have reached a dependent parameter pack.
  40. auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
  41. auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
  42. if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
  43. return;
  44. } else if (getDepthAndIndex(ND).first >= DepthLimit)
  45. return;
  46. Unexpanded.push_back({ND, Loc});
  47. }
  48. void addUnexpanded(const TemplateTypeParmType *T,
  49. SourceLocation Loc = SourceLocation()) {
  50. if (T->getDepth() < DepthLimit)
  51. Unexpanded.push_back({T, Loc});
  52. }
  53. public:
  54. explicit CollectUnexpandedParameterPacksVisitor(
  55. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
  56. : Unexpanded(Unexpanded) {}
  57. bool shouldWalkTypesOfTypeLocs() const { return false; }
  58. //------------------------------------------------------------------------
  59. // Recording occurrences of (unexpanded) parameter packs.
  60. //------------------------------------------------------------------------
  61. /// Record occurrences of template type parameter packs.
  62. bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  63. if (TL.getTypePtr()->isParameterPack())
  64. addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
  65. return true;
  66. }
  67. /// Record occurrences of template type parameter packs
  68. /// when we don't have proper source-location information for
  69. /// them.
  70. ///
  71. /// Ideally, this routine would never be used.
  72. bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
  73. if (T->isParameterPack())
  74. addUnexpanded(T);
  75. return true;
  76. }
  77. /// Record occurrences of function and non-type template
  78. /// parameter packs in an expression.
  79. bool VisitDeclRefExpr(DeclRefExpr *E) {
  80. if (E->getDecl()->isParameterPack())
  81. addUnexpanded(E->getDecl(), E->getLocation());
  82. return true;
  83. }
  84. /// Record occurrences of template template parameter packs.
  85. bool TraverseTemplateName(TemplateName Template) {
  86. if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
  87. Template.getAsTemplateDecl())) {
  88. if (TTP->isParameterPack())
  89. addUnexpanded(TTP);
  90. }
  91. return inherited::TraverseTemplateName(Template);
  92. }
  93. /// Suppress traversal into Objective-C container literal
  94. /// elements that are pack expansions.
  95. bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
  96. if (!E->containsUnexpandedParameterPack())
  97. return true;
  98. for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
  99. ObjCDictionaryElement Element = E->getKeyValueElement(I);
  100. if (Element.isPackExpansion())
  101. continue;
  102. TraverseStmt(Element.Key);
  103. TraverseStmt(Element.Value);
  104. }
  105. return true;
  106. }
  107. //------------------------------------------------------------------------
  108. // Pruning the search for unexpanded parameter packs.
  109. //------------------------------------------------------------------------
  110. /// Suppress traversal into statements and expressions that
  111. /// do not contain unexpanded parameter packs.
  112. bool TraverseStmt(Stmt *S) {
  113. Expr *E = dyn_cast_or_null<Expr>(S);
  114. if ((E && E->containsUnexpandedParameterPack()) || InLambda)
  115. return inherited::TraverseStmt(S);
  116. return true;
  117. }
  118. /// Suppress traversal into types that do not contain
  119. /// unexpanded parameter packs.
  120. bool TraverseType(QualType T) {
  121. if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
  122. return inherited::TraverseType(T);
  123. return true;
  124. }
  125. /// Suppress traversal into types with location information
  126. /// that do not contain unexpanded parameter packs.
  127. bool TraverseTypeLoc(TypeLoc TL) {
  128. if ((!TL.getType().isNull() &&
  129. TL.getType()->containsUnexpandedParameterPack()) ||
  130. InLambda)
  131. return inherited::TraverseTypeLoc(TL);
  132. return true;
  133. }
  134. /// Suppress traversal of parameter packs.
  135. bool TraverseDecl(Decl *D) {
  136. // A function parameter pack is a pack expansion, so cannot contain
  137. // an unexpanded parameter pack. Likewise for a template parameter
  138. // pack that contains any references to other packs.
  139. if (D && D->isParameterPack())
  140. return true;
  141. return inherited::TraverseDecl(D);
  142. }
  143. /// Suppress traversal of pack-expanded attributes.
  144. bool TraverseAttr(Attr *A) {
  145. if (A->isPackExpansion())
  146. return true;
  147. return inherited::TraverseAttr(A);
  148. }
  149. /// Suppress traversal of pack expansion expressions and types.
  150. ///@{
  151. bool TraversePackExpansionType(PackExpansionType *T) { return true; }
  152. bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
  153. bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
  154. bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
  155. ///@}
  156. /// Suppress traversal of using-declaration pack expansion.
  157. bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  158. if (D->isPackExpansion())
  159. return true;
  160. return inherited::TraverseUnresolvedUsingValueDecl(D);
  161. }
  162. /// Suppress traversal of using-declaration pack expansion.
  163. bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
  164. if (D->isPackExpansion())
  165. return true;
  166. return inherited::TraverseUnresolvedUsingTypenameDecl(D);
  167. }
  168. /// Suppress traversal of template argument pack expansions.
  169. bool TraverseTemplateArgument(const TemplateArgument &Arg) {
  170. if (Arg.isPackExpansion())
  171. return true;
  172. return inherited::TraverseTemplateArgument(Arg);
  173. }
  174. /// Suppress traversal of template argument pack expansions.
  175. bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
  176. if (ArgLoc.getArgument().isPackExpansion())
  177. return true;
  178. return inherited::TraverseTemplateArgumentLoc(ArgLoc);
  179. }
  180. /// Suppress traversal of base specifier pack expansions.
  181. bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
  182. if (Base.isPackExpansion())
  183. return true;
  184. return inherited::TraverseCXXBaseSpecifier(Base);
  185. }
  186. /// Suppress traversal of mem-initializer pack expansions.
  187. bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
  188. if (Init->isPackExpansion())
  189. return true;
  190. return inherited::TraverseConstructorInitializer(Init);
  191. }
  192. /// Note whether we're traversing a lambda containing an unexpanded
  193. /// parameter pack. In this case, the unexpanded pack can occur anywhere,
  194. /// including all the places where we normally wouldn't look. Within a
  195. /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
  196. /// outside an expression.
  197. bool TraverseLambdaExpr(LambdaExpr *Lambda) {
  198. // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
  199. // even if it's contained within another lambda.
  200. if (!Lambda->containsUnexpandedParameterPack())
  201. return true;
  202. bool WasInLambda = InLambda;
  203. unsigned OldDepthLimit = DepthLimit;
  204. InLambda = true;
  205. if (auto *TPL = Lambda->getTemplateParameterList())
  206. DepthLimit = TPL->getDepth();
  207. inherited::TraverseLambdaExpr(Lambda);
  208. InLambda = WasInLambda;
  209. DepthLimit = OldDepthLimit;
  210. return true;
  211. }
  212. /// Suppress traversal within pack expansions in lambda captures.
  213. bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
  214. Expr *Init) {
  215. if (C->isPackExpansion())
  216. return true;
  217. return inherited::TraverseLambdaCapture(Lambda, C, Init);
  218. }
  219. };
  220. }
  221. /// Determine whether it's possible for an unexpanded parameter pack to
  222. /// be valid in this location. This only happens when we're in a declaration
  223. /// that is nested within an expression that could be expanded, such as a
  224. /// lambda-expression within a function call.
  225. ///
  226. /// This is conservatively correct, but may claim that some unexpanded packs are
  227. /// permitted when they are not.
  228. bool Sema::isUnexpandedParameterPackPermitted() {
  229. for (auto *SI : FunctionScopes)
  230. if (isa<sema::LambdaScopeInfo>(SI))
  231. return true;
  232. return false;
  233. }
  234. /// Diagnose all of the unexpanded parameter packs in the given
  235. /// vector.
  236. bool
  237. Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
  238. UnexpandedParameterPackContext UPPC,
  239. ArrayRef<UnexpandedParameterPack> Unexpanded) {
  240. if (Unexpanded.empty())
  241. return false;
  242. // If we are within a lambda expression and referencing a pack that is not
  243. // declared within the lambda itself, that lambda contains an unexpanded
  244. // parameter pack, and we are done.
  245. // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
  246. // later.
  247. SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
  248. if (auto *LSI = getEnclosingLambda()) {
  249. for (auto &Pack : Unexpanded) {
  250. auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
  251. if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
  252. auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
  253. return TTPD && TTPD->getTypeForDecl() == TTPT;
  254. }
  255. return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
  256. };
  257. if (llvm::any_of(LSI->LocalPacks, DeclaresThisPack))
  258. LambdaParamPackReferences.push_back(Pack);
  259. }
  260. if (LambdaParamPackReferences.empty()) {
  261. // Construct in lambda only references packs declared outside the lambda.
  262. // That's OK for now, but the lambda itself is considered to contain an
  263. // unexpanded pack in this case, which will require expansion outside the
  264. // lambda.
  265. // We do not permit pack expansion that would duplicate a statement
  266. // expression, not even within a lambda.
  267. // FIXME: We could probably support this for statement expressions that
  268. // do not contain labels.
  269. // FIXME: This is insufficient to detect this problem; consider
  270. // f( ({ bad: 0; }) + pack ... );
  271. bool EnclosingStmtExpr = false;
  272. for (unsigned N = FunctionScopes.size(); N; --N) {
  273. sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
  274. if (llvm::any_of(
  275. Func->CompoundScopes,
  276. [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
  277. EnclosingStmtExpr = true;
  278. break;
  279. }
  280. // Coumpound-statements outside the lambda are OK for now; we'll check
  281. // for those when we finish handling the lambda.
  282. if (Func == LSI)
  283. break;
  284. }
  285. if (!EnclosingStmtExpr) {
  286. LSI->ContainsUnexpandedParameterPack = true;
  287. return false;
  288. }
  289. } else {
  290. Unexpanded = LambdaParamPackReferences;
  291. }
  292. }
  293. SmallVector<SourceLocation, 4> Locations;
  294. SmallVector<IdentifierInfo *, 4> Names;
  295. llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
  296. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  297. IdentifierInfo *Name = nullptr;
  298. if (const TemplateTypeParmType *TTP
  299. = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
  300. Name = TTP->getIdentifier();
  301. else
  302. Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
  303. if (Name && NamesKnown.insert(Name).second)
  304. Names.push_back(Name);
  305. if (Unexpanded[I].second.isValid())
  306. Locations.push_back(Unexpanded[I].second);
  307. }
  308. auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
  309. << (int)UPPC << (int)Names.size();
  310. for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
  311. DB << Names[I];
  312. for (unsigned I = 0, N = Locations.size(); I != N; ++I)
  313. DB << SourceRange(Locations[I]);
  314. return true;
  315. }
  316. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  317. TypeSourceInfo *T,
  318. UnexpandedParameterPackContext UPPC) {
  319. // C++0x [temp.variadic]p5:
  320. // An appearance of a name of a parameter pack that is not expanded is
  321. // ill-formed.
  322. if (!T->getType()->containsUnexpandedParameterPack())
  323. return false;
  324. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  325. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
  326. T->getTypeLoc());
  327. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  328. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  329. }
  330. bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
  331. UnexpandedParameterPackContext UPPC) {
  332. // C++0x [temp.variadic]p5:
  333. // An appearance of a name of a parameter pack that is not expanded is
  334. // ill-formed.
  335. if (!E->containsUnexpandedParameterPack())
  336. return false;
  337. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  338. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
  339. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  340. return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
  341. }
  342. bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
  343. if (!RE->containsUnexpandedParameterPack())
  344. return false;
  345. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  346. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
  347. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  348. // We only care about unexpanded references to the RequiresExpr's own
  349. // parameter packs.
  350. auto Parms = RE->getLocalParameters();
  351. llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end());
  352. SmallVector<UnexpandedParameterPack, 2> UnexpandedParms;
  353. for (auto Parm : Unexpanded)
  354. if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl *>()))
  355. UnexpandedParms.push_back(Parm);
  356. if (UnexpandedParms.empty())
  357. return false;
  358. return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
  359. UnexpandedParms);
  360. }
  361. bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
  362. UnexpandedParameterPackContext UPPC) {
  363. // C++0x [temp.variadic]p5:
  364. // An appearance of a name of a parameter pack that is not expanded is
  365. // ill-formed.
  366. if (!SS.getScopeRep() ||
  367. !SS.getScopeRep()->containsUnexpandedParameterPack())
  368. return false;
  369. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  370. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  371. .TraverseNestedNameSpecifier(SS.getScopeRep());
  372. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  373. return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
  374. UPPC, Unexpanded);
  375. }
  376. bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
  377. UnexpandedParameterPackContext UPPC) {
  378. // C++0x [temp.variadic]p5:
  379. // An appearance of a name of a parameter pack that is not expanded is
  380. // ill-formed.
  381. switch (NameInfo.getName().getNameKind()) {
  382. case DeclarationName::Identifier:
  383. case DeclarationName::ObjCZeroArgSelector:
  384. case DeclarationName::ObjCOneArgSelector:
  385. case DeclarationName::ObjCMultiArgSelector:
  386. case DeclarationName::CXXOperatorName:
  387. case DeclarationName::CXXLiteralOperatorName:
  388. case DeclarationName::CXXUsingDirective:
  389. case DeclarationName::CXXDeductionGuideName:
  390. return false;
  391. case DeclarationName::CXXConstructorName:
  392. case DeclarationName::CXXDestructorName:
  393. case DeclarationName::CXXConversionFunctionName:
  394. // FIXME: We shouldn't need this null check!
  395. if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
  396. return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
  397. if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
  398. return false;
  399. break;
  400. }
  401. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  402. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  403. .TraverseType(NameInfo.getName().getCXXNameType());
  404. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  405. return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
  406. }
  407. bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
  408. TemplateName Template,
  409. UnexpandedParameterPackContext UPPC) {
  410. if (Template.isNull() || !Template.containsUnexpandedParameterPack())
  411. return false;
  412. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  413. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  414. .TraverseTemplateName(Template);
  415. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  416. return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
  417. }
  418. bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
  419. UnexpandedParameterPackContext UPPC) {
  420. if (Arg.getArgument().isNull() ||
  421. !Arg.getArgument().containsUnexpandedParameterPack())
  422. return false;
  423. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  424. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  425. .TraverseTemplateArgumentLoc(Arg);
  426. assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
  427. return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
  428. }
  429. void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
  430. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  431. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  432. .TraverseTemplateArgument(Arg);
  433. }
  434. void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
  435. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  436. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  437. .TraverseTemplateArgumentLoc(Arg);
  438. }
  439. void Sema::collectUnexpandedParameterPacks(QualType T,
  440. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  441. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
  442. }
  443. void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
  444. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  445. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
  446. }
  447. void Sema::collectUnexpandedParameterPacks(
  448. NestedNameSpecifierLoc NNS,
  449. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  450. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  451. .TraverseNestedNameSpecifierLoc(NNS);
  452. }
  453. void Sema::collectUnexpandedParameterPacks(
  454. const DeclarationNameInfo &NameInfo,
  455. SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
  456. CollectUnexpandedParameterPacksVisitor(Unexpanded)
  457. .TraverseDeclarationNameInfo(NameInfo);
  458. }
  459. ParsedTemplateArgument
  460. Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
  461. SourceLocation EllipsisLoc) {
  462. if (Arg.isInvalid())
  463. return Arg;
  464. switch (Arg.getKind()) {
  465. case ParsedTemplateArgument::Type: {
  466. TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
  467. if (Result.isInvalid())
  468. return ParsedTemplateArgument();
  469. return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
  470. Arg.getLocation());
  471. }
  472. case ParsedTemplateArgument::NonType: {
  473. ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
  474. if (Result.isInvalid())
  475. return ParsedTemplateArgument();
  476. return ParsedTemplateArgument(Arg.getKind(), Result.get(),
  477. Arg.getLocation());
  478. }
  479. case ParsedTemplateArgument::Template:
  480. if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
  481. SourceRange R(Arg.getLocation());
  482. if (Arg.getScopeSpec().isValid())
  483. R.setBegin(Arg.getScopeSpec().getBeginLoc());
  484. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  485. << R;
  486. return ParsedTemplateArgument();
  487. }
  488. return Arg.getTemplatePackExpansion(EllipsisLoc);
  489. }
  490. llvm_unreachable("Unhandled template argument kind?");
  491. }
  492. TypeResult Sema::ActOnPackExpansion(ParsedType Type,
  493. SourceLocation EllipsisLoc) {
  494. TypeSourceInfo *TSInfo;
  495. GetTypeFromParser(Type, &TSInfo);
  496. if (!TSInfo)
  497. return true;
  498. TypeSourceInfo *TSResult =
  499. CheckPackExpansion(TSInfo, EllipsisLoc, std::nullopt);
  500. if (!TSResult)
  501. return true;
  502. return CreateParsedType(TSResult->getType(), TSResult);
  503. }
  504. TypeSourceInfo *
  505. Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
  506. std::optional<unsigned> NumExpansions) {
  507. // Create the pack expansion type and source-location information.
  508. QualType Result = CheckPackExpansion(Pattern->getType(),
  509. Pattern->getTypeLoc().getSourceRange(),
  510. EllipsisLoc, NumExpansions);
  511. if (Result.isNull())
  512. return nullptr;
  513. TypeLocBuilder TLB;
  514. TLB.pushFullCopy(Pattern->getTypeLoc());
  515. PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
  516. TL.setEllipsisLoc(EllipsisLoc);
  517. return TLB.getTypeSourceInfo(Context, Result);
  518. }
  519. QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
  520. SourceLocation EllipsisLoc,
  521. std::optional<unsigned> NumExpansions) {
  522. // C++11 [temp.variadic]p5:
  523. // The pattern of a pack expansion shall name one or more
  524. // parameter packs that are not expanded by a nested pack
  525. // expansion.
  526. //
  527. // A pattern containing a deduced type can't occur "naturally" but arises in
  528. // the desugaring of an init-capture pack.
  529. if (!Pattern->containsUnexpandedParameterPack() &&
  530. !Pattern->getContainedDeducedType()) {
  531. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  532. << PatternRange;
  533. return QualType();
  534. }
  535. return Context.getPackExpansionType(Pattern, NumExpansions,
  536. /*ExpectPackInType=*/false);
  537. }
  538. ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
  539. return CheckPackExpansion(Pattern, EllipsisLoc, std::nullopt);
  540. }
  541. ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
  542. std::optional<unsigned> NumExpansions) {
  543. if (!Pattern)
  544. return ExprError();
  545. // C++0x [temp.variadic]p5:
  546. // The pattern of a pack expansion shall name one or more
  547. // parameter packs that are not expanded by a nested pack
  548. // expansion.
  549. if (!Pattern->containsUnexpandedParameterPack()) {
  550. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  551. << Pattern->getSourceRange();
  552. CorrectDelayedTyposInExpr(Pattern);
  553. return ExprError();
  554. }
  555. // Create the pack expansion expression and source-location information.
  556. return new (Context)
  557. PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
  558. }
  559. bool Sema::CheckParameterPacksForExpansion(
  560. SourceLocation EllipsisLoc, SourceRange PatternRange,
  561. ArrayRef<UnexpandedParameterPack> Unexpanded,
  562. const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
  563. bool &RetainExpansion, std::optional<unsigned> &NumExpansions) {
  564. ShouldExpand = true;
  565. RetainExpansion = false;
  566. std::pair<IdentifierInfo *, SourceLocation> FirstPack;
  567. bool HaveFirstPack = false;
  568. std::optional<unsigned> NumPartialExpansions;
  569. SourceLocation PartiallySubstitutedPackLoc;
  570. for (UnexpandedParameterPack ParmPack : Unexpanded) {
  571. // Compute the depth and index for this parameter pack.
  572. unsigned Depth = 0, Index = 0;
  573. IdentifierInfo *Name;
  574. bool IsVarDeclPack = false;
  575. if (const TemplateTypeParmType *TTP =
  576. ParmPack.first.dyn_cast<const TemplateTypeParmType *>()) {
  577. Depth = TTP->getDepth();
  578. Index = TTP->getIndex();
  579. Name = TTP->getIdentifier();
  580. } else {
  581. NamedDecl *ND = ParmPack.first.get<NamedDecl *>();
  582. if (isa<VarDecl>(ND))
  583. IsVarDeclPack = true;
  584. else
  585. std::tie(Depth, Index) = getDepthAndIndex(ND);
  586. Name = ND->getIdentifier();
  587. }
  588. // Determine the size of this argument pack.
  589. unsigned NewPackSize;
  590. if (IsVarDeclPack) {
  591. // Figure out whether we're instantiating to an argument pack or not.
  592. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  593. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
  594. CurrentInstantiationScope->findInstantiationOf(
  595. ParmPack.first.get<NamedDecl *>());
  596. if (Instantiation->is<DeclArgumentPack *>()) {
  597. // We could expand this function parameter pack.
  598. NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
  599. } else {
  600. // We can't expand this function parameter pack, so we can't expand
  601. // the pack expansion.
  602. ShouldExpand = false;
  603. continue;
  604. }
  605. } else {
  606. // If we don't have a template argument at this depth/index, then we
  607. // cannot expand the pack expansion. Make a note of this, but we still
  608. // want to check any parameter packs we *do* have arguments for.
  609. if (Depth >= TemplateArgs.getNumLevels() ||
  610. !TemplateArgs.hasTemplateArgument(Depth, Index)) {
  611. ShouldExpand = false;
  612. continue;
  613. }
  614. // Determine the size of the argument pack.
  615. NewPackSize = TemplateArgs(Depth, Index).pack_size();
  616. }
  617. // C++0x [temp.arg.explicit]p9:
  618. // Template argument deduction can extend the sequence of template
  619. // arguments corresponding to a template parameter pack, even when the
  620. // sequence contains explicitly specified template arguments.
  621. if (!IsVarDeclPack && CurrentInstantiationScope) {
  622. if (NamedDecl *PartialPack =
  623. CurrentInstantiationScope->getPartiallySubstitutedPack()) {
  624. unsigned PartialDepth, PartialIndex;
  625. std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
  626. if (PartialDepth == Depth && PartialIndex == Index) {
  627. RetainExpansion = true;
  628. // We don't actually know the new pack size yet.
  629. NumPartialExpansions = NewPackSize;
  630. PartiallySubstitutedPackLoc = ParmPack.second;
  631. continue;
  632. }
  633. }
  634. }
  635. if (!NumExpansions) {
  636. // The is the first pack we've seen for which we have an argument.
  637. // Record it.
  638. NumExpansions = NewPackSize;
  639. FirstPack.first = Name;
  640. FirstPack.second = ParmPack.second;
  641. HaveFirstPack = true;
  642. continue;
  643. }
  644. if (NewPackSize != *NumExpansions) {
  645. // C++0x [temp.variadic]p5:
  646. // All of the parameter packs expanded by a pack expansion shall have
  647. // the same number of arguments specified.
  648. if (HaveFirstPack)
  649. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
  650. << FirstPack.first << Name << *NumExpansions << NewPackSize
  651. << SourceRange(FirstPack.second) << SourceRange(ParmPack.second);
  652. else
  653. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
  654. << Name << *NumExpansions << NewPackSize
  655. << SourceRange(ParmPack.second);
  656. return true;
  657. }
  658. }
  659. // If we're performing a partial expansion but we also have a full expansion,
  660. // expand to the number of common arguments. For example, given:
  661. //
  662. // template<typename ...T> struct A {
  663. // template<typename ...U> void f(pair<T, U>...);
  664. // };
  665. //
  666. // ... a call to 'A<int, int>().f<int>' should expand the pack once and
  667. // retain an expansion.
  668. if (NumPartialExpansions) {
  669. if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
  670. NamedDecl *PartialPack =
  671. CurrentInstantiationScope->getPartiallySubstitutedPack();
  672. Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
  673. << PartialPack << *NumPartialExpansions << *NumExpansions
  674. << SourceRange(PartiallySubstitutedPackLoc);
  675. return true;
  676. }
  677. NumExpansions = NumPartialExpansions;
  678. }
  679. return false;
  680. }
  681. std::optional<unsigned> Sema::getNumArgumentsInExpansion(
  682. QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) {
  683. QualType Pattern = cast<PackExpansionType>(T)->getPattern();
  684. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  685. CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
  686. std::optional<unsigned> Result;
  687. for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
  688. // Compute the depth and index for this parameter pack.
  689. unsigned Depth;
  690. unsigned Index;
  691. if (const TemplateTypeParmType *TTP =
  692. Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
  693. Depth = TTP->getDepth();
  694. Index = TTP->getIndex();
  695. } else {
  696. NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
  697. if (isa<VarDecl>(ND)) {
  698. // Function parameter pack or init-capture pack.
  699. typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
  700. llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
  701. CurrentInstantiationScope->findInstantiationOf(
  702. Unexpanded[I].first.get<NamedDecl *>());
  703. if (Instantiation->is<Decl *>())
  704. // The pattern refers to an unexpanded pack. We're not ready to expand
  705. // this pack yet.
  706. return std::nullopt;
  707. unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
  708. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  709. Result = Size;
  710. continue;
  711. }
  712. std::tie(Depth, Index) = getDepthAndIndex(ND);
  713. }
  714. if (Depth >= TemplateArgs.getNumLevels() ||
  715. !TemplateArgs.hasTemplateArgument(Depth, Index))
  716. // The pattern refers to an unknown template argument. We're not ready to
  717. // expand this pack yet.
  718. return std::nullopt;
  719. // Determine the size of the argument pack.
  720. unsigned Size = TemplateArgs(Depth, Index).pack_size();
  721. assert((!Result || *Result == Size) && "inconsistent pack sizes");
  722. Result = Size;
  723. }
  724. return Result;
  725. }
  726. bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
  727. const DeclSpec &DS = D.getDeclSpec();
  728. switch (DS.getTypeSpecType()) {
  729. case TST_typename:
  730. case TST_typeof_unqualType:
  731. case TST_typeofType:
  732. #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
  733. #include "clang/Basic/TransformTypeTraits.def"
  734. case TST_atomic: {
  735. QualType T = DS.getRepAsType().get();
  736. if (!T.isNull() && T->containsUnexpandedParameterPack())
  737. return true;
  738. break;
  739. }
  740. case TST_typeof_unqualExpr:
  741. case TST_typeofExpr:
  742. case TST_decltype:
  743. case TST_bitint:
  744. if (DS.getRepAsExpr() &&
  745. DS.getRepAsExpr()->containsUnexpandedParameterPack())
  746. return true;
  747. break;
  748. case TST_unspecified:
  749. case TST_void:
  750. case TST_char:
  751. case TST_wchar:
  752. case TST_char8:
  753. case TST_char16:
  754. case TST_char32:
  755. case TST_int:
  756. case TST_int128:
  757. case TST_half:
  758. case TST_float:
  759. case TST_double:
  760. case TST_Accum:
  761. case TST_Fract:
  762. case TST_Float16:
  763. case TST_float128:
  764. case TST_ibm128:
  765. case TST_bool:
  766. case TST_decimal32:
  767. case TST_decimal64:
  768. case TST_decimal128:
  769. case TST_enum:
  770. case TST_union:
  771. case TST_struct:
  772. case TST_interface:
  773. case TST_class:
  774. case TST_auto:
  775. case TST_auto_type:
  776. case TST_decltype_auto:
  777. case TST_BFloat16:
  778. #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
  779. #include "clang/Basic/OpenCLImageTypes.def"
  780. case TST_unknown_anytype:
  781. case TST_error:
  782. break;
  783. }
  784. for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
  785. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  786. switch (Chunk.Kind) {
  787. case DeclaratorChunk::Pointer:
  788. case DeclaratorChunk::Reference:
  789. case DeclaratorChunk::Paren:
  790. case DeclaratorChunk::Pipe:
  791. case DeclaratorChunk::BlockPointer:
  792. // These declarator chunks cannot contain any parameter packs.
  793. break;
  794. case DeclaratorChunk::Array:
  795. if (Chunk.Arr.NumElts &&
  796. Chunk.Arr.NumElts->containsUnexpandedParameterPack())
  797. return true;
  798. break;
  799. case DeclaratorChunk::Function:
  800. for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
  801. ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
  802. QualType ParamTy = Param->getType();
  803. assert(!ParamTy.isNull() && "Couldn't parse type?");
  804. if (ParamTy->containsUnexpandedParameterPack()) return true;
  805. }
  806. if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
  807. for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
  808. if (Chunk.Fun.Exceptions[i]
  809. .Ty.get()
  810. ->containsUnexpandedParameterPack())
  811. return true;
  812. }
  813. } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
  814. Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
  815. return true;
  816. if (Chunk.Fun.hasTrailingReturnType()) {
  817. QualType T = Chunk.Fun.getTrailingReturnType().get();
  818. if (!T.isNull() && T->containsUnexpandedParameterPack())
  819. return true;
  820. }
  821. break;
  822. case DeclaratorChunk::MemberPointer:
  823. if (Chunk.Mem.Scope().getScopeRep() &&
  824. Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
  825. return true;
  826. break;
  827. }
  828. }
  829. if (Expr *TRC = D.getTrailingRequiresClause())
  830. if (TRC->containsUnexpandedParameterPack())
  831. return true;
  832. return false;
  833. }
  834. namespace {
  835. // Callback to only accept typo corrections that refer to parameter packs.
  836. class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
  837. public:
  838. bool ValidateCandidate(const TypoCorrection &candidate) override {
  839. NamedDecl *ND = candidate.getCorrectionDecl();
  840. return ND && ND->isParameterPack();
  841. }
  842. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  843. return std::make_unique<ParameterPackValidatorCCC>(*this);
  844. }
  845. };
  846. }
  847. /// Called when an expression computing the size of a parameter pack
  848. /// is parsed.
  849. ///
  850. /// \code
  851. /// template<typename ...Types> struct count {
  852. /// static const unsigned value = sizeof...(Types);
  853. /// };
  854. /// \endcode
  855. ///
  856. //
  857. /// \param OpLoc The location of the "sizeof" keyword.
  858. /// \param Name The name of the parameter pack whose size will be determined.
  859. /// \param NameLoc The source location of the name of the parameter pack.
  860. /// \param RParenLoc The location of the closing parentheses.
  861. ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
  862. SourceLocation OpLoc,
  863. IdentifierInfo &Name,
  864. SourceLocation NameLoc,
  865. SourceLocation RParenLoc) {
  866. // C++0x [expr.sizeof]p5:
  867. // The identifier in a sizeof... expression shall name a parameter pack.
  868. LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
  869. LookupName(R, S);
  870. NamedDecl *ParameterPack = nullptr;
  871. switch (R.getResultKind()) {
  872. case LookupResult::Found:
  873. ParameterPack = R.getFoundDecl();
  874. break;
  875. case LookupResult::NotFound:
  876. case LookupResult::NotFoundInCurrentInstantiation: {
  877. ParameterPackValidatorCCC CCC{};
  878. if (TypoCorrection Corrected =
  879. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
  880. CCC, CTK_ErrorRecovery)) {
  881. diagnoseTypo(Corrected,
  882. PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
  883. PDiag(diag::note_parameter_pack_here));
  884. ParameterPack = Corrected.getCorrectionDecl();
  885. }
  886. break;
  887. }
  888. case LookupResult::FoundOverloaded:
  889. case LookupResult::FoundUnresolvedValue:
  890. break;
  891. case LookupResult::Ambiguous:
  892. DiagnoseAmbiguousLookup(R);
  893. return ExprError();
  894. }
  895. if (!ParameterPack || !ParameterPack->isParameterPack()) {
  896. Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
  897. << &Name;
  898. return ExprError();
  899. }
  900. MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
  901. return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
  902. RParenLoc);
  903. }
  904. TemplateArgumentLoc Sema::getTemplateArgumentPackExpansionPattern(
  905. TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
  906. std::optional<unsigned> &NumExpansions) const {
  907. const TemplateArgument &Argument = OrigLoc.getArgument();
  908. assert(Argument.isPackExpansion());
  909. switch (Argument.getKind()) {
  910. case TemplateArgument::Type: {
  911. // FIXME: We shouldn't ever have to worry about missing
  912. // type-source info!
  913. TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
  914. if (!ExpansionTSInfo)
  915. ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
  916. Ellipsis);
  917. PackExpansionTypeLoc Expansion =
  918. ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
  919. Ellipsis = Expansion.getEllipsisLoc();
  920. TypeLoc Pattern = Expansion.getPatternLoc();
  921. NumExpansions = Expansion.getTypePtr()->getNumExpansions();
  922. // We need to copy the TypeLoc because TemplateArgumentLocs store a
  923. // TypeSourceInfo.
  924. // FIXME: Find some way to avoid the copy?
  925. TypeLocBuilder TLB;
  926. TLB.pushFullCopy(Pattern);
  927. TypeSourceInfo *PatternTSInfo =
  928. TLB.getTypeSourceInfo(Context, Pattern.getType());
  929. return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
  930. PatternTSInfo);
  931. }
  932. case TemplateArgument::Expression: {
  933. PackExpansionExpr *Expansion
  934. = cast<PackExpansionExpr>(Argument.getAsExpr());
  935. Expr *Pattern = Expansion->getPattern();
  936. Ellipsis = Expansion->getEllipsisLoc();
  937. NumExpansions = Expansion->getNumExpansions();
  938. return TemplateArgumentLoc(Pattern, Pattern);
  939. }
  940. case TemplateArgument::TemplateExpansion:
  941. Ellipsis = OrigLoc.getTemplateEllipsisLoc();
  942. NumExpansions = Argument.getNumTemplateExpansions();
  943. return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(),
  944. OrigLoc.getTemplateQualifierLoc(),
  945. OrigLoc.getTemplateNameLoc());
  946. case TemplateArgument::Declaration:
  947. case TemplateArgument::NullPtr:
  948. case TemplateArgument::Template:
  949. case TemplateArgument::Integral:
  950. case TemplateArgument::Pack:
  951. case TemplateArgument::Null:
  952. return TemplateArgumentLoc();
  953. }
  954. llvm_unreachable("Invalid TemplateArgument Kind!");
  955. }
  956. std::optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
  957. assert(Arg.containsUnexpandedParameterPack());
  958. // If this is a substituted pack, grab that pack. If not, we don't know
  959. // the size yet.
  960. // FIXME: We could find a size in more cases by looking for a substituted
  961. // pack anywhere within this argument, but that's not necessary in the common
  962. // case for 'sizeof...(A)' handling.
  963. TemplateArgument Pack;
  964. switch (Arg.getKind()) {
  965. case TemplateArgument::Type:
  966. if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
  967. Pack = Subst->getArgumentPack();
  968. else
  969. return std::nullopt;
  970. break;
  971. case TemplateArgument::Expression:
  972. if (auto *Subst =
  973. dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
  974. Pack = Subst->getArgumentPack();
  975. else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
  976. for (VarDecl *PD : *Subst)
  977. if (PD->isParameterPack())
  978. return std::nullopt;
  979. return Subst->getNumExpansions();
  980. } else
  981. return std::nullopt;
  982. break;
  983. case TemplateArgument::Template:
  984. if (SubstTemplateTemplateParmPackStorage *Subst =
  985. Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
  986. Pack = Subst->getArgumentPack();
  987. else
  988. return std::nullopt;
  989. break;
  990. case TemplateArgument::Declaration:
  991. case TemplateArgument::NullPtr:
  992. case TemplateArgument::TemplateExpansion:
  993. case TemplateArgument::Integral:
  994. case TemplateArgument::Pack:
  995. case TemplateArgument::Null:
  996. return std::nullopt;
  997. }
  998. // Check that no argument in the pack is itself a pack expansion.
  999. for (TemplateArgument Elem : Pack.pack_elements()) {
  1000. // There's no point recursing in this case; we would have already
  1001. // expanded this pack expansion into the enclosing pack if we could.
  1002. if (Elem.isPackExpansion())
  1003. return std::nullopt;
  1004. }
  1005. return Pack.pack_size();
  1006. }
  1007. static void CheckFoldOperand(Sema &S, Expr *E) {
  1008. if (!E)
  1009. return;
  1010. E = E->IgnoreImpCasts();
  1011. auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
  1012. if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
  1013. isa<AbstractConditionalOperator>(E)) {
  1014. S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
  1015. << E->getSourceRange()
  1016. << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
  1017. << FixItHint::CreateInsertion(E->getEndLoc(), ")");
  1018. }
  1019. }
  1020. ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
  1021. tok::TokenKind Operator,
  1022. SourceLocation EllipsisLoc, Expr *RHS,
  1023. SourceLocation RParenLoc) {
  1024. // LHS and RHS must be cast-expressions. We allow an arbitrary expression
  1025. // in the parser and reduce down to just cast-expressions here.
  1026. CheckFoldOperand(*this, LHS);
  1027. CheckFoldOperand(*this, RHS);
  1028. auto DiscardOperands = [&] {
  1029. CorrectDelayedTyposInExpr(LHS);
  1030. CorrectDelayedTyposInExpr(RHS);
  1031. };
  1032. // [expr.prim.fold]p3:
  1033. // In a binary fold, op1 and op2 shall be the same fold-operator, and
  1034. // either e1 shall contain an unexpanded parameter pack or e2 shall contain
  1035. // an unexpanded parameter pack, but not both.
  1036. if (LHS && RHS &&
  1037. LHS->containsUnexpandedParameterPack() ==
  1038. RHS->containsUnexpandedParameterPack()) {
  1039. DiscardOperands();
  1040. return Diag(EllipsisLoc,
  1041. LHS->containsUnexpandedParameterPack()
  1042. ? diag::err_fold_expression_packs_both_sides
  1043. : diag::err_pack_expansion_without_parameter_packs)
  1044. << LHS->getSourceRange() << RHS->getSourceRange();
  1045. }
  1046. // [expr.prim.fold]p2:
  1047. // In a unary fold, the cast-expression shall contain an unexpanded
  1048. // parameter pack.
  1049. if (!LHS || !RHS) {
  1050. Expr *Pack = LHS ? LHS : RHS;
  1051. assert(Pack && "fold expression with neither LHS nor RHS");
  1052. DiscardOperands();
  1053. if (!Pack->containsUnexpandedParameterPack())
  1054. return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1055. << Pack->getSourceRange();
  1056. }
  1057. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
  1058. // Perform first-phase name lookup now.
  1059. UnresolvedLookupExpr *ULE = nullptr;
  1060. {
  1061. UnresolvedSet<16> Functions;
  1062. LookupBinOp(S, EllipsisLoc, Opc, Functions);
  1063. if (!Functions.empty()) {
  1064. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
  1065. BinaryOperator::getOverloadedOperator(Opc));
  1066. ExprResult Callee = CreateUnresolvedLookupExpr(
  1067. /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
  1068. DeclarationNameInfo(OpName, EllipsisLoc), Functions);
  1069. if (Callee.isInvalid())
  1070. return ExprError();
  1071. ULE = cast<UnresolvedLookupExpr>(Callee.get());
  1072. }
  1073. }
  1074. return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
  1075. std::nullopt);
  1076. }
  1077. ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
  1078. SourceLocation LParenLoc, Expr *LHS,
  1079. BinaryOperatorKind Operator,
  1080. SourceLocation EllipsisLoc, Expr *RHS,
  1081. SourceLocation RParenLoc,
  1082. std::optional<unsigned> NumExpansions) {
  1083. return new (Context)
  1084. CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
  1085. EllipsisLoc, RHS, RParenLoc, NumExpansions);
  1086. }
  1087. ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
  1088. BinaryOperatorKind Operator) {
  1089. // [temp.variadic]p9:
  1090. // If N is zero for a unary fold-expression, the value of the expression is
  1091. // && -> true
  1092. // || -> false
  1093. // , -> void()
  1094. // if the operator is not listed [above], the instantiation is ill-formed.
  1095. //
  1096. // Note that we need to use something like int() here, not merely 0, to
  1097. // prevent the result from being a null pointer constant.
  1098. QualType ScalarType;
  1099. switch (Operator) {
  1100. case BO_LOr:
  1101. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
  1102. case BO_LAnd:
  1103. return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
  1104. case BO_Comma:
  1105. ScalarType = Context.VoidTy;
  1106. break;
  1107. default:
  1108. return Diag(EllipsisLoc, diag::err_fold_expression_empty)
  1109. << BinaryOperator::getOpcodeStr(Operator);
  1110. }
  1111. return new (Context) CXXScalarValueInitExpr(
  1112. ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
  1113. EllipsisLoc);
  1114. }