SemaTemplateVariadic.cpp 44 KB

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