1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 //  This file implements semantic analysis for C++0x variadic templates.
10 //===----------------------------------------------------------------------===/
11 
12 #include "clang/Sema/Sema.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/ParsedTemplate.h"
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/Template.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 
21 using namespace clang;
22 
23 //----------------------------------------------------------------------------
24 // Visitor that collects unexpanded parameter packs
25 //----------------------------------------------------------------------------
26 
27 namespace {
28   /// \brief A class that collects unexpanded parameter packs.
29   class CollectUnexpandedParameterPacksVisitor :
30     public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
31   {
32     typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
33       inherited;
34 
35     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
36 
37   public:
38     explicit CollectUnexpandedParameterPacksVisitor(
39                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
40       : Unexpanded(Unexpanded) { }
41 
42     bool shouldWalkTypesOfTypeLocs() const { return false; }
43 
44     //------------------------------------------------------------------------
45     // Recording occurrences of (unexpanded) parameter packs.
46     //------------------------------------------------------------------------
47 
48     /// \brief Record occurrences of template type parameter packs.
49     bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
50       if (TL.getTypePtr()->isParameterPack())
51         Unexpanded.push_back(std::make_pair(TL.getTypePtr(), TL.getNameLoc()));
52       return true;
53     }
54 
55     /// \brief Record occurrences of template type parameter packs
56     /// when we don't have proper source-location information for
57     /// them.
58     ///
59     /// Ideally, this routine would never be used.
60     bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
61       if (T->isParameterPack())
62         Unexpanded.push_back(std::make_pair(T, SourceLocation()));
63 
64       return true;
65     }
66 
67     /// \brief Record occurrences of function and non-type template
68     /// parameter packs in an expression.
69     bool VisitDeclRefExpr(DeclRefExpr *E) {
70       if (E->getDecl()->isParameterPack())
71         Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
72 
73       return true;
74     }
75 
76     // \brief Record occurrences of function and non-type template parameter
77     // packs in a block-captured expression.
78     bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
79       if (E->getDecl()->isParameterPack())
80         Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()));
81 
82       return true;
83     }
84 
85     /// \brief Record occurrences of template template parameter packs.
86     bool TraverseTemplateName(TemplateName Template) {
87       if (TemplateTemplateParmDecl *TTP
88             = dyn_cast_or_null<TemplateTemplateParmDecl>(
89                                                   Template.getAsTemplateDecl()))
90         if (TTP->isParameterPack())
91           Unexpanded.push_back(std::make_pair(TTP, SourceLocation()));
92 
93       return inherited::TraverseTemplateName(Template);
94     }
95 
96     //------------------------------------------------------------------------
97     // Pruning the search for unexpanded parameter packs.
98     //------------------------------------------------------------------------
99 
100     /// \brief Suppress traversal into statements and expressions that
101     /// do not contain unexpanded parameter packs.
102     bool TraverseStmt(Stmt *S) {
103       if (Expr *E = dyn_cast_or_null<Expr>(S))
104         if (E->containsUnexpandedParameterPack())
105           return inherited::TraverseStmt(E);
106 
107       return true;
108     }
109 
110     /// \brief Suppress traversal into types that do not contain
111     /// unexpanded parameter packs.
112     bool TraverseType(QualType T) {
113       if (!T.isNull() && T->containsUnexpandedParameterPack())
114         return inherited::TraverseType(T);
115 
116       return true;
117     }
118 
119     /// \brief Suppress traversel into types with location information
120     /// that do not contain unexpanded parameter packs.
121     bool TraverseTypeLoc(TypeLoc TL) {
122       if (!TL.getType().isNull() &&
123           TL.getType()->containsUnexpandedParameterPack())
124         return inherited::TraverseTypeLoc(TL);
125 
126       return true;
127     }
128 
129     /// \brief Suppress traversal of non-parameter declarations, since
130     /// they cannot contain unexpanded parameter packs.
131     bool TraverseDecl(Decl *D) {
132       if (D && isa<ParmVarDecl>(D))
133         return inherited::TraverseDecl(D);
134 
135       return true;
136     }
137 
138     /// \brief Suppress traversal of template argument pack expansions.
139     bool TraverseTemplateArgument(const TemplateArgument &Arg) {
140       if (Arg.isPackExpansion())
141         return true;
142 
143       return inherited::TraverseTemplateArgument(Arg);
144     }
145 
146     /// \brief Suppress traversal of template argument pack expansions.
147     bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
148       if (ArgLoc.getArgument().isPackExpansion())
149         return true;
150 
151       return inherited::TraverseTemplateArgumentLoc(ArgLoc);
152     }
153   };
154 }
155 
156 /// \brief Diagnose all of the unexpanded parameter packs in the given
157 /// vector.
158 void
159 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
160                                        UnexpandedParameterPackContext UPPC,
161              const SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
162   if (Unexpanded.empty())
163     return;
164 
165   SmallVector<SourceLocation, 4> Locations;
166   SmallVector<IdentifierInfo *, 4> Names;
167   llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
168 
169   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
170     IdentifierInfo *Name = 0;
171     if (const TemplateTypeParmType *TTP
172           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
173       Name = TTP->getIdentifier();
174     else
175       Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
176 
177     if (Name && NamesKnown.insert(Name))
178       Names.push_back(Name);
179 
180     if (Unexpanded[I].second.isValid())
181       Locations.push_back(Unexpanded[I].second);
182   }
183 
184   DiagnosticBuilder DB
185     = Names.size() == 0? Diag(Loc, diag::err_unexpanded_parameter_pack_0)
186                            << (int)UPPC
187     : Names.size() == 1? Diag(Loc, diag::err_unexpanded_parameter_pack_1)
188                            << (int)UPPC << Names[0]
189     : Names.size() == 2? Diag(Loc, diag::err_unexpanded_parameter_pack_2)
190                            << (int)UPPC << Names[0] << Names[1]
191     : Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
192         << (int)UPPC << Names[0] << Names[1];
193 
194   for (unsigned I = 0, N = Locations.size(); I != N; ++I)
195     DB << SourceRange(Locations[I]);
196 }
197 
198 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
199                                            TypeSourceInfo *T,
200                                          UnexpandedParameterPackContext UPPC) {
201   // C++0x [temp.variadic]p5:
202   //   An appearance of a name of a parameter pack that is not expanded is
203   //   ill-formed.
204   if (!T->getType()->containsUnexpandedParameterPack())
205     return false;
206 
207   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
208   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
209                                                               T->getTypeLoc());
210   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
211   DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
212   return true;
213 }
214 
215 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
216                                         UnexpandedParameterPackContext UPPC) {
217   // C++0x [temp.variadic]p5:
218   //   An appearance of a name of a parameter pack that is not expanded is
219   //   ill-formed.
220   if (!E->containsUnexpandedParameterPack())
221     return false;
222 
223   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
224   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
225   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
226   DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
227   return true;
228 }
229 
230 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
231                                         UnexpandedParameterPackContext UPPC) {
232   // C++0x [temp.variadic]p5:
233   //   An appearance of a name of a parameter pack that is not expanded is
234   //   ill-formed.
235   if (!SS.getScopeRep() ||
236       !SS.getScopeRep()->containsUnexpandedParameterPack())
237     return false;
238 
239   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
240   CollectUnexpandedParameterPacksVisitor(Unexpanded)
241     .TraverseNestedNameSpecifier(SS.getScopeRep());
242   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
243   DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
244                                    UPPC, Unexpanded);
245   return true;
246 }
247 
248 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
249                                          UnexpandedParameterPackContext UPPC) {
250   // C++0x [temp.variadic]p5:
251   //   An appearance of a name of a parameter pack that is not expanded is
252   //   ill-formed.
253   switch (NameInfo.getName().getNameKind()) {
254   case DeclarationName::Identifier:
255   case DeclarationName::ObjCZeroArgSelector:
256   case DeclarationName::ObjCOneArgSelector:
257   case DeclarationName::ObjCMultiArgSelector:
258   case DeclarationName::CXXOperatorName:
259   case DeclarationName::CXXLiteralOperatorName:
260   case DeclarationName::CXXUsingDirective:
261     return false;
262 
263   case DeclarationName::CXXConstructorName:
264   case DeclarationName::CXXDestructorName:
265   case DeclarationName::CXXConversionFunctionName:
266     // FIXME: We shouldn't need this null check!
267     if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
268       return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
269 
270     if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
271       return false;
272 
273     break;
274   }
275 
276   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
277   CollectUnexpandedParameterPacksVisitor(Unexpanded)
278     .TraverseType(NameInfo.getName().getCXXNameType());
279   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
280   DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
281   return true;
282 }
283 
284 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
285                                            TemplateName Template,
286                                        UnexpandedParameterPackContext UPPC) {
287 
288   if (Template.isNull() || !Template.containsUnexpandedParameterPack())
289     return false;
290 
291   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
292   CollectUnexpandedParameterPacksVisitor(Unexpanded)
293     .TraverseTemplateName(Template);
294   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
295   DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
296   return true;
297 }
298 
299 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
300                                          UnexpandedParameterPackContext UPPC) {
301   if (Arg.getArgument().isNull() ||
302       !Arg.getArgument().containsUnexpandedParameterPack())
303     return false;
304 
305   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
306   CollectUnexpandedParameterPacksVisitor(Unexpanded)
307     .TraverseTemplateArgumentLoc(Arg);
308   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
309   DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
310   return true;
311 }
312 
313 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
314                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
315   CollectUnexpandedParameterPacksVisitor(Unexpanded)
316     .TraverseTemplateArgument(Arg);
317 }
318 
319 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
320                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
321   CollectUnexpandedParameterPacksVisitor(Unexpanded)
322     .TraverseTemplateArgumentLoc(Arg);
323 }
324 
325 void Sema::collectUnexpandedParameterPacks(QualType T,
326                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
327   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
328 }
329 
330 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
331                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
332   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
333 }
334 
335 void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
336                                            SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
337   NestedNameSpecifier *Qualifier = SS.getScopeRep();
338   if (!Qualifier)
339     return;
340 
341   NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
342   CollectUnexpandedParameterPacksVisitor(Unexpanded)
343     .TraverseNestedNameSpecifierLoc(QualifierLoc);
344 }
345 
346 void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
347                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
348   CollectUnexpandedParameterPacksVisitor(Unexpanded)
349     .TraverseDeclarationNameInfo(NameInfo);
350 }
351 
352 
353 ParsedTemplateArgument
354 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
355                          SourceLocation EllipsisLoc) {
356   if (Arg.isInvalid())
357     return Arg;
358 
359   switch (Arg.getKind()) {
360   case ParsedTemplateArgument::Type: {
361     TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
362     if (Result.isInvalid())
363       return ParsedTemplateArgument();
364 
365     return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
366                                   Arg.getLocation());
367   }
368 
369   case ParsedTemplateArgument::NonType: {
370     ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
371     if (Result.isInvalid())
372       return ParsedTemplateArgument();
373 
374     return ParsedTemplateArgument(Arg.getKind(), Result.get(),
375                                   Arg.getLocation());
376   }
377 
378   case ParsedTemplateArgument::Template:
379     if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
380       SourceRange R(Arg.getLocation());
381       if (Arg.getScopeSpec().isValid())
382         R.setBegin(Arg.getScopeSpec().getBeginLoc());
383       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
384         << R;
385       return ParsedTemplateArgument();
386     }
387 
388     return Arg.getTemplatePackExpansion(EllipsisLoc);
389   }
390   llvm_unreachable("Unhandled template argument kind?");
391   return ParsedTemplateArgument();
392 }
393 
394 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
395                                     SourceLocation EllipsisLoc) {
396   TypeSourceInfo *TSInfo;
397   GetTypeFromParser(Type, &TSInfo);
398   if (!TSInfo)
399     return true;
400 
401   TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc,
402                                                 llvm::Optional<unsigned>());
403   if (!TSResult)
404     return true;
405 
406   return CreateParsedType(TSResult->getType(), TSResult);
407 }
408 
409 TypeSourceInfo *Sema::CheckPackExpansion(TypeSourceInfo *Pattern,
410                                          SourceLocation EllipsisLoc,
411                                        llvm::Optional<unsigned> NumExpansions) {
412   // Create the pack expansion type and source-location information.
413   QualType Result = CheckPackExpansion(Pattern->getType(),
414                                        Pattern->getTypeLoc().getSourceRange(),
415                                        EllipsisLoc, NumExpansions);
416   if (Result.isNull())
417     return 0;
418 
419   TypeSourceInfo *TSResult = Context.CreateTypeSourceInfo(Result);
420   PackExpansionTypeLoc TL = cast<PackExpansionTypeLoc>(TSResult->getTypeLoc());
421   TL.setEllipsisLoc(EllipsisLoc);
422 
423   // Copy over the source-location information from the type.
424   memcpy(TL.getNextTypeLoc().getOpaqueData(),
425          Pattern->getTypeLoc().getOpaqueData(),
426          Pattern->getTypeLoc().getFullDataSize());
427   return TSResult;
428 }
429 
430 QualType Sema::CheckPackExpansion(QualType Pattern,
431                                   SourceRange PatternRange,
432                                   SourceLocation EllipsisLoc,
433                                   llvm::Optional<unsigned> NumExpansions) {
434   // C++0x [temp.variadic]p5:
435   //   The pattern of a pack expansion shall name one or more
436   //   parameter packs that are not expanded by a nested pack
437   //   expansion.
438   if (!Pattern->containsUnexpandedParameterPack()) {
439     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
440       << PatternRange;
441     return QualType();
442   }
443 
444   return Context.getPackExpansionType(Pattern, NumExpansions);
445 }
446 
447 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
448   return CheckPackExpansion(Pattern, EllipsisLoc, llvm::Optional<unsigned>());
449 }
450 
451 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
452                                     llvm::Optional<unsigned> NumExpansions) {
453   if (!Pattern)
454     return ExprError();
455 
456   // C++0x [temp.variadic]p5:
457   //   The pattern of a pack expansion shall name one or more
458   //   parameter packs that are not expanded by a nested pack
459   //   expansion.
460   if (!Pattern->containsUnexpandedParameterPack()) {
461     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
462     << Pattern->getSourceRange();
463     return ExprError();
464   }
465 
466   // Create the pack expansion expression and source-location information.
467   return Owned(new (Context) PackExpansionExpr(Context.DependentTy, Pattern,
468                                                EllipsisLoc, NumExpansions));
469 }
470 
471 /// \brief Retrieve the depth and index of a parameter pack.
472 static std::pair<unsigned, unsigned>
473 getDepthAndIndex(NamedDecl *ND) {
474   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
475     return std::make_pair(TTP->getDepth(), TTP->getIndex());
476 
477   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
478     return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
479 
480   TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
481   return std::make_pair(TTP->getDepth(), TTP->getIndex());
482 }
483 
484 bool Sema::CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
485                                            SourceRange PatternRange,
486                                    ArrayRef<UnexpandedParameterPack> Unexpanded,
487                              const MultiLevelTemplateArgumentList &TemplateArgs,
488                                            bool &ShouldExpand,
489                                            bool &RetainExpansion,
490                                      llvm::Optional<unsigned> &NumExpansions) {
491   ShouldExpand = true;
492   RetainExpansion = false;
493   std::pair<IdentifierInfo *, SourceLocation> FirstPack;
494   bool HaveFirstPack = false;
495 
496   for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
497                                                  end = Unexpanded.end();
498                                                   i != end; ++i) {
499     // Compute the depth and index for this parameter pack.
500     unsigned Depth = 0, Index = 0;
501     IdentifierInfo *Name;
502     bool IsFunctionParameterPack = false;
503 
504     if (const TemplateTypeParmType *TTP
505         = i->first.dyn_cast<const TemplateTypeParmType *>()) {
506       Depth = TTP->getDepth();
507       Index = TTP->getIndex();
508       Name = TTP->getIdentifier();
509     } else {
510       NamedDecl *ND = i->first.get<NamedDecl *>();
511       if (isa<ParmVarDecl>(ND))
512         IsFunctionParameterPack = true;
513       else
514         llvm::tie(Depth, Index) = getDepthAndIndex(ND);
515 
516       Name = ND->getIdentifier();
517     }
518 
519     // Determine the size of this argument pack.
520     unsigned NewPackSize;
521     if (IsFunctionParameterPack) {
522       // Figure out whether we're instantiating to an argument pack or not.
523       typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
524 
525       llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
526         = CurrentInstantiationScope->findInstantiationOf(
527                                         i->first.get<NamedDecl *>());
528       if (Instantiation->is<DeclArgumentPack *>()) {
529         // We could expand this function parameter pack.
530         NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
531       } else {
532         // We can't expand this function parameter pack, so we can't expand
533         // the pack expansion.
534         ShouldExpand = false;
535         continue;
536       }
537     } else {
538       // If we don't have a template argument at this depth/index, then we
539       // cannot expand the pack expansion. Make a note of this, but we still
540       // want to check any parameter packs we *do* have arguments for.
541       if (Depth >= TemplateArgs.getNumLevels() ||
542           !TemplateArgs.hasTemplateArgument(Depth, Index)) {
543         ShouldExpand = false;
544         continue;
545       }
546 
547       // Determine the size of the argument pack.
548       NewPackSize = TemplateArgs(Depth, Index).pack_size();
549     }
550 
551     // C++0x [temp.arg.explicit]p9:
552     //   Template argument deduction can extend the sequence of template
553     //   arguments corresponding to a template parameter pack, even when the
554     //   sequence contains explicitly specified template arguments.
555     if (!IsFunctionParameterPack) {
556       if (NamedDecl *PartialPack
557                     = CurrentInstantiationScope->getPartiallySubstitutedPack()){
558         unsigned PartialDepth, PartialIndex;
559         llvm::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
560         if (PartialDepth == Depth && PartialIndex == Index)
561           RetainExpansion = true;
562       }
563     }
564 
565     if (!NumExpansions) {
566       // The is the first pack we've seen for which we have an argument.
567       // Record it.
568       NumExpansions = NewPackSize;
569       FirstPack.first = Name;
570       FirstPack.second = i->second;
571       HaveFirstPack = true;
572       continue;
573     }
574 
575     if (NewPackSize != *NumExpansions) {
576       // C++0x [temp.variadic]p5:
577       //   All of the parameter packs expanded by a pack expansion shall have
578       //   the same number of arguments specified.
579       if (HaveFirstPack)
580         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
581           << FirstPack.first << Name << *NumExpansions << NewPackSize
582           << SourceRange(FirstPack.second) << SourceRange(i->second);
583       else
584         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
585           << Name << *NumExpansions << NewPackSize
586           << SourceRange(i->second);
587       return true;
588     }
589   }
590 
591   return false;
592 }
593 
594 unsigned Sema::getNumArgumentsInExpansion(QualType T,
595                           const MultiLevelTemplateArgumentList &TemplateArgs) {
596   QualType Pattern = cast<PackExpansionType>(T)->getPattern();
597   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
598   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
599 
600   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
601     // Compute the depth and index for this parameter pack.
602     unsigned Depth;
603     unsigned Index;
604 
605     if (const TemplateTypeParmType *TTP
606           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
607       Depth = TTP->getDepth();
608       Index = TTP->getIndex();
609     } else {
610       NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
611       if (isa<ParmVarDecl>(ND)) {
612         // Function parameter pack.
613         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
614 
615         llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
616           = CurrentInstantiationScope->findInstantiationOf(
617                                         Unexpanded[I].first.get<NamedDecl *>());
618         if (Instantiation->is<DeclArgumentPack *>())
619           return Instantiation->get<DeclArgumentPack *>()->size();
620 
621         continue;
622       }
623 
624       llvm::tie(Depth, Index) = getDepthAndIndex(ND);
625     }
626     if (Depth >= TemplateArgs.getNumLevels() ||
627         !TemplateArgs.hasTemplateArgument(Depth, Index))
628       continue;
629 
630     // Determine the size of the argument pack.
631     return TemplateArgs(Depth, Index).pack_size();
632   }
633 
634   llvm_unreachable("No unexpanded parameter packs in type expansion.");
635   return 0;
636 }
637 
638 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
639   const DeclSpec &DS = D.getDeclSpec();
640   switch (DS.getTypeSpecType()) {
641   case TST_typename:
642   case TST_typeofType:
643   case TST_underlyingType:
644   case TST_atomic: {
645     QualType T = DS.getRepAsType().get();
646     if (!T.isNull() && T->containsUnexpandedParameterPack())
647       return true;
648     break;
649   }
650 
651   case TST_typeofExpr:
652   case TST_decltype:
653     if (DS.getRepAsExpr() &&
654         DS.getRepAsExpr()->containsUnexpandedParameterPack())
655       return true;
656     break;
657 
658   case TST_unspecified:
659   case TST_void:
660   case TST_char:
661   case TST_wchar:
662   case TST_char16:
663   case TST_char32:
664   case TST_int:
665   case TST_half:
666   case TST_float:
667   case TST_double:
668   case TST_bool:
669   case TST_decimal32:
670   case TST_decimal64:
671   case TST_decimal128:
672   case TST_enum:
673   case TST_union:
674   case TST_struct:
675   case TST_class:
676   case TST_auto:
677   case TST_unknown_anytype:
678   case TST_error:
679     break;
680   }
681 
682   for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
683     const DeclaratorChunk &Chunk = D.getTypeObject(I);
684     switch (Chunk.Kind) {
685     case DeclaratorChunk::Pointer:
686     case DeclaratorChunk::Reference:
687     case DeclaratorChunk::Paren:
688       // These declarator chunks cannot contain any parameter packs.
689       break;
690 
691     case DeclaratorChunk::Array:
692     case DeclaratorChunk::Function:
693     case DeclaratorChunk::BlockPointer:
694       // Syntactically, these kinds of declarator chunks all come after the
695       // declarator-id (conceptually), so the parser should not invoke this
696       // routine at this time.
697       llvm_unreachable("Could not have seen this kind of declarator chunk");
698       break;
699 
700     case DeclaratorChunk::MemberPointer:
701       if (Chunk.Mem.Scope().getScopeRep() &&
702           Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
703         return true;
704       break;
705     }
706   }
707 
708   return false;
709 }
710 
711 /// \brief Called when an expression computing the size of a parameter pack
712 /// is parsed.
713 ///
714 /// \code
715 /// template<typename ...Types> struct count {
716 ///   static const unsigned value = sizeof...(Types);
717 /// };
718 /// \endcode
719 ///
720 //
721 /// \param OpLoc The location of the "sizeof" keyword.
722 /// \param Name The name of the parameter pack whose size will be determined.
723 /// \param NameLoc The source location of the name of the parameter pack.
724 /// \param RParenLoc The location of the closing parentheses.
725 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
726                                               SourceLocation OpLoc,
727                                               IdentifierInfo &Name,
728                                               SourceLocation NameLoc,
729                                               SourceLocation RParenLoc) {
730   // C++0x [expr.sizeof]p5:
731   //   The identifier in a sizeof... expression shall name a parameter pack.
732   LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
733   LookupName(R, S);
734 
735   NamedDecl *ParameterPack = 0;
736   switch (R.getResultKind()) {
737   case LookupResult::Found:
738     ParameterPack = R.getFoundDecl();
739     break;
740 
741   case LookupResult::NotFound:
742   case LookupResult::NotFoundInCurrentInstantiation:
743     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
744                                                R.getLookupKind(), S, 0, 0,
745                                                false, CTC_NoKeywords)) {
746       if (NamedDecl *CorrectedResult = Corrected.getCorrectionDecl())
747         if (CorrectedResult->isParameterPack()) {
748           std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
749           ParameterPack = CorrectedResult;
750           Diag(NameLoc, diag::err_sizeof_pack_no_pack_name_suggest)
751             << &Name << CorrectedQuotedStr
752             << FixItHint::CreateReplacement(
753                 NameLoc, Corrected.getAsString(getLangOptions()));
754           Diag(ParameterPack->getLocation(), diag::note_parameter_pack_here)
755             << CorrectedQuotedStr;
756         }
757     }
758 
759   case LookupResult::FoundOverloaded:
760   case LookupResult::FoundUnresolvedValue:
761     break;
762 
763   case LookupResult::Ambiguous:
764     DiagnoseAmbiguousLookup(R);
765     return ExprError();
766   }
767 
768   if (!ParameterPack || !ParameterPack->isParameterPack()) {
769     Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
770       << &Name;
771     return ExprError();
772   }
773 
774   return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc,
775                                       ParameterPack, NameLoc, RParenLoc);
776 }
777