clang API Documentation
00001 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/ 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 //===----------------------------------------------------------------------===/ 00008 // 00009 // This file implements C++ template argument deduction. 00010 // 00011 //===----------------------------------------------------------------------===/ 00012 00013 #include "clang/Sema/Sema.h" 00014 #include "clang/Sema/DeclSpec.h" 00015 #include "clang/Sema/Template.h" 00016 #include "clang/Sema/TemplateDeduction.h" 00017 #include "clang/AST/ASTContext.h" 00018 #include "clang/AST/DeclObjC.h" 00019 #include "clang/AST/DeclTemplate.h" 00020 #include "clang/AST/StmtVisitor.h" 00021 #include "clang/AST/Expr.h" 00022 #include "clang/AST/ExprCXX.h" 00023 #include "llvm/ADT/SmallBitVector.h" 00024 #include "TreeTransform.h" 00025 #include <algorithm> 00026 00027 namespace clang { 00028 using namespace sema; 00029 00030 /// \brief Various flags that control template argument deduction. 00031 /// 00032 /// These flags can be bitwise-OR'd together. 00033 enum TemplateDeductionFlags { 00034 /// \brief No template argument deduction flags, which indicates the 00035 /// strictest results for template argument deduction (as used for, e.g., 00036 /// matching class template partial specializations). 00037 TDF_None = 0, 00038 /// \brief Within template argument deduction from a function call, we are 00039 /// matching with a parameter type for which the original parameter was 00040 /// a reference. 00041 TDF_ParamWithReferenceType = 0x1, 00042 /// \brief Within template argument deduction from a function call, we 00043 /// are matching in a case where we ignore cv-qualifiers. 00044 TDF_IgnoreQualifiers = 0x02, 00045 /// \brief Within template argument deduction from a function call, 00046 /// we are matching in a case where we can perform template argument 00047 /// deduction from a template-id of a derived class of the argument type. 00048 TDF_DerivedClass = 0x04, 00049 /// \brief Allow non-dependent types to differ, e.g., when performing 00050 /// template argument deduction from a function call where conversions 00051 /// may apply. 00052 TDF_SkipNonDependent = 0x08, 00053 /// \brief Whether we are performing template argument deduction for 00054 /// parameters and arguments in a top-level template argument 00055 TDF_TopLevelParameterTypeList = 0x10 00056 }; 00057 } 00058 00059 using namespace clang; 00060 00061 /// \brief Compare two APSInts, extending and switching the sign as 00062 /// necessary to compare their values regardless of underlying type. 00063 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) { 00064 if (Y.getBitWidth() > X.getBitWidth()) 00065 X = X.extend(Y.getBitWidth()); 00066 else if (Y.getBitWidth() < X.getBitWidth()) 00067 Y = Y.extend(X.getBitWidth()); 00068 00069 // If there is a signedness mismatch, correct it. 00070 if (X.isSigned() != Y.isSigned()) { 00071 // If the signed value is negative, then the values cannot be the same. 00072 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative())) 00073 return false; 00074 00075 Y.setIsSigned(true); 00076 X.setIsSigned(true); 00077 } 00078 00079 return X == Y; 00080 } 00081 00082 static Sema::TemplateDeductionResult 00083 DeduceTemplateArguments(Sema &S, 00084 TemplateParameterList *TemplateParams, 00085 const TemplateArgument &Param, 00086 TemplateArgument Arg, 00087 TemplateDeductionInfo &Info, 00088 SmallVectorImpl<DeducedTemplateArgument> &Deduced); 00089 00090 /// \brief Whether template argument deduction for two reference parameters 00091 /// resulted in the argument type, parameter type, or neither type being more 00092 /// qualified than the other. 00093 enum DeductionQualifierComparison { 00094 NeitherMoreQualified = 0, 00095 ParamMoreQualified, 00096 ArgMoreQualified 00097 }; 00098 00099 /// \brief Stores the result of comparing two reference parameters while 00100 /// performing template argument deduction for partial ordering of function 00101 /// templates. 00102 struct RefParamPartialOrderingComparison { 00103 /// \brief Whether the parameter type is an rvalue reference type. 00104 bool ParamIsRvalueRef; 00105 /// \brief Whether the argument type is an rvalue reference type. 00106 bool ArgIsRvalueRef; 00107 00108 /// \brief Whether the parameter or argument (or neither) is more qualified. 00109 DeductionQualifierComparison Qualifiers; 00110 }; 00111 00112 00113 00114 static Sema::TemplateDeductionResult 00115 DeduceTemplateArgumentsByTypeMatch(Sema &S, 00116 TemplateParameterList *TemplateParams, 00117 QualType Param, 00118 QualType Arg, 00119 TemplateDeductionInfo &Info, 00120 SmallVectorImpl<DeducedTemplateArgument> & 00121 Deduced, 00122 unsigned TDF, 00123 bool PartialOrdering = false, 00124 SmallVectorImpl<RefParamPartialOrderingComparison> * 00125 RefParamComparisons = 0); 00126 00127 static Sema::TemplateDeductionResult 00128 DeduceTemplateArguments(Sema &S, 00129 TemplateParameterList *TemplateParams, 00130 const TemplateArgument *Params, unsigned NumParams, 00131 const TemplateArgument *Args, unsigned NumArgs, 00132 TemplateDeductionInfo &Info, 00133 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00134 bool NumberOfArgumentsMustMatch = true); 00135 00136 /// \brief If the given expression is of a form that permits the deduction 00137 /// of a non-type template parameter, return the declaration of that 00138 /// non-type template parameter. 00139 static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) { 00140 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E)) 00141 E = IC->getSubExpr(); 00142 00143 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 00144 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 00145 00146 return 0; 00147 } 00148 00149 /// \brief Determine whether two declaration pointers refer to the same 00150 /// declaration. 00151 static bool isSameDeclaration(Decl *X, Decl *Y) { 00152 if (!X || !Y) 00153 return !X && !Y; 00154 00155 if (NamedDecl *NX = dyn_cast<NamedDecl>(X)) 00156 X = NX->getUnderlyingDecl(); 00157 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y)) 00158 Y = NY->getUnderlyingDecl(); 00159 00160 return X->getCanonicalDecl() == Y->getCanonicalDecl(); 00161 } 00162 00163 /// \brief Verify that the given, deduced template arguments are compatible. 00164 /// 00165 /// \returns The deduced template argument, or a NULL template argument if 00166 /// the deduced template arguments were incompatible. 00167 static DeducedTemplateArgument 00168 checkDeducedTemplateArguments(ASTContext &Context, 00169 const DeducedTemplateArgument &X, 00170 const DeducedTemplateArgument &Y) { 00171 // We have no deduction for one or both of the arguments; they're compatible. 00172 if (X.isNull()) 00173 return Y; 00174 if (Y.isNull()) 00175 return X; 00176 00177 switch (X.getKind()) { 00178 case TemplateArgument::Null: 00179 llvm_unreachable("Non-deduced template arguments handled above"); 00180 00181 case TemplateArgument::Type: 00182 // If two template type arguments have the same type, they're compatible. 00183 if (Y.getKind() == TemplateArgument::Type && 00184 Context.hasSameType(X.getAsType(), Y.getAsType())) 00185 return X; 00186 00187 return DeducedTemplateArgument(); 00188 00189 case TemplateArgument::Integral: 00190 // If we deduced a constant in one case and either a dependent expression or 00191 // declaration in another case, keep the integral constant. 00192 // If both are integral constants with the same value, keep that value. 00193 if (Y.getKind() == TemplateArgument::Expression || 00194 Y.getKind() == TemplateArgument::Declaration || 00195 (Y.getKind() == TemplateArgument::Integral && 00196 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral()))) 00197 return DeducedTemplateArgument(X, 00198 X.wasDeducedFromArrayBound() && 00199 Y.wasDeducedFromArrayBound()); 00200 00201 // All other combinations are incompatible. 00202 return DeducedTemplateArgument(); 00203 00204 case TemplateArgument::Template: 00205 if (Y.getKind() == TemplateArgument::Template && 00206 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate())) 00207 return X; 00208 00209 // All other combinations are incompatible. 00210 return DeducedTemplateArgument(); 00211 00212 case TemplateArgument::TemplateExpansion: 00213 if (Y.getKind() == TemplateArgument::TemplateExpansion && 00214 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(), 00215 Y.getAsTemplateOrTemplatePattern())) 00216 return X; 00217 00218 // All other combinations are incompatible. 00219 return DeducedTemplateArgument(); 00220 00221 case TemplateArgument::Expression: 00222 // If we deduced a dependent expression in one case and either an integral 00223 // constant or a declaration in another case, keep the integral constant 00224 // or declaration. 00225 if (Y.getKind() == TemplateArgument::Integral || 00226 Y.getKind() == TemplateArgument::Declaration) 00227 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() && 00228 Y.wasDeducedFromArrayBound()); 00229 00230 if (Y.getKind() == TemplateArgument::Expression) { 00231 // Compare the expressions for equality 00232 llvm::FoldingSetNodeID ID1, ID2; 00233 X.getAsExpr()->Profile(ID1, Context, true); 00234 Y.getAsExpr()->Profile(ID2, Context, true); 00235 if (ID1 == ID2) 00236 return X; 00237 } 00238 00239 // All other combinations are incompatible. 00240 return DeducedTemplateArgument(); 00241 00242 case TemplateArgument::Declaration: 00243 // If we deduced a declaration and a dependent expression, keep the 00244 // declaration. 00245 if (Y.getKind() == TemplateArgument::Expression) 00246 return X; 00247 00248 // If we deduced a declaration and an integral constant, keep the 00249 // integral constant. 00250 if (Y.getKind() == TemplateArgument::Integral) 00251 return Y; 00252 00253 // If we deduced two declarations, make sure they they refer to the 00254 // same declaration. 00255 if (Y.getKind() == TemplateArgument::Declaration && 00256 isSameDeclaration(X.getAsDecl(), Y.getAsDecl())) 00257 return X; 00258 00259 // All other combinations are incompatible. 00260 return DeducedTemplateArgument(); 00261 00262 case TemplateArgument::Pack: 00263 if (Y.getKind() != TemplateArgument::Pack || 00264 X.pack_size() != Y.pack_size()) 00265 return DeducedTemplateArgument(); 00266 00267 for (TemplateArgument::pack_iterator XA = X.pack_begin(), 00268 XAEnd = X.pack_end(), 00269 YA = Y.pack_begin(); 00270 XA != XAEnd; ++XA, ++YA) { 00271 if (checkDeducedTemplateArguments(Context, 00272 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()), 00273 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound())) 00274 .isNull()) 00275 return DeducedTemplateArgument(); 00276 } 00277 00278 return X; 00279 } 00280 00281 llvm_unreachable("Invalid TemplateArgument Kind!"); 00282 } 00283 00284 /// \brief Deduce the value of the given non-type template parameter 00285 /// from the given constant. 00286 static Sema::TemplateDeductionResult 00287 DeduceNonTypeTemplateArgument(Sema &S, 00288 NonTypeTemplateParmDecl *NTTP, 00289 llvm::APSInt Value, QualType ValueType, 00290 bool DeducedFromArrayBound, 00291 TemplateDeductionInfo &Info, 00292 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00293 assert(NTTP->getDepth() == 0 && 00294 "Cannot deduce non-type template argument with depth > 0"); 00295 00296 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound); 00297 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00298 Deduced[NTTP->getIndex()], 00299 NewDeduced); 00300 if (Result.isNull()) { 00301 Info.Param = NTTP; 00302 Info.FirstArg = Deduced[NTTP->getIndex()]; 00303 Info.SecondArg = NewDeduced; 00304 return Sema::TDK_Inconsistent; 00305 } 00306 00307 Deduced[NTTP->getIndex()] = Result; 00308 return Sema::TDK_Success; 00309 } 00310 00311 /// \brief Deduce the value of the given non-type template parameter 00312 /// from the given type- or value-dependent expression. 00313 /// 00314 /// \returns true if deduction succeeded, false otherwise. 00315 static Sema::TemplateDeductionResult 00316 DeduceNonTypeTemplateArgument(Sema &S, 00317 NonTypeTemplateParmDecl *NTTP, 00318 Expr *Value, 00319 TemplateDeductionInfo &Info, 00320 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00321 assert(NTTP->getDepth() == 0 && 00322 "Cannot deduce non-type template argument with depth > 0"); 00323 assert((Value->isTypeDependent() || Value->isValueDependent()) && 00324 "Expression template argument must be type- or value-dependent."); 00325 00326 DeducedTemplateArgument NewDeduced(Value); 00327 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00328 Deduced[NTTP->getIndex()], 00329 NewDeduced); 00330 00331 if (Result.isNull()) { 00332 Info.Param = NTTP; 00333 Info.FirstArg = Deduced[NTTP->getIndex()]; 00334 Info.SecondArg = NewDeduced; 00335 return Sema::TDK_Inconsistent; 00336 } 00337 00338 Deduced[NTTP->getIndex()] = Result; 00339 return Sema::TDK_Success; 00340 } 00341 00342 /// \brief Deduce the value of the given non-type template parameter 00343 /// from the given declaration. 00344 /// 00345 /// \returns true if deduction succeeded, false otherwise. 00346 static Sema::TemplateDeductionResult 00347 DeduceNonTypeTemplateArgument(Sema &S, 00348 NonTypeTemplateParmDecl *NTTP, 00349 Decl *D, 00350 TemplateDeductionInfo &Info, 00351 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00352 assert(NTTP->getDepth() == 0 && 00353 "Cannot deduce non-type template argument with depth > 0"); 00354 00355 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0); 00356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00357 Deduced[NTTP->getIndex()], 00358 NewDeduced); 00359 if (Result.isNull()) { 00360 Info.Param = NTTP; 00361 Info.FirstArg = Deduced[NTTP->getIndex()]; 00362 Info.SecondArg = NewDeduced; 00363 return Sema::TDK_Inconsistent; 00364 } 00365 00366 Deduced[NTTP->getIndex()] = Result; 00367 return Sema::TDK_Success; 00368 } 00369 00370 static Sema::TemplateDeductionResult 00371 DeduceTemplateArguments(Sema &S, 00372 TemplateParameterList *TemplateParams, 00373 TemplateName Param, 00374 TemplateName Arg, 00375 TemplateDeductionInfo &Info, 00376 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00377 TemplateDecl *ParamDecl = Param.getAsTemplateDecl(); 00378 if (!ParamDecl) { 00379 // The parameter type is dependent and is not a template template parameter, 00380 // so there is nothing that we can deduce. 00381 return Sema::TDK_Success; 00382 } 00383 00384 if (TemplateTemplateParmDecl *TempParam 00385 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) { 00386 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg)); 00387 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 00388 Deduced[TempParam->getIndex()], 00389 NewDeduced); 00390 if (Result.isNull()) { 00391 Info.Param = TempParam; 00392 Info.FirstArg = Deduced[TempParam->getIndex()]; 00393 Info.SecondArg = NewDeduced; 00394 return Sema::TDK_Inconsistent; 00395 } 00396 00397 Deduced[TempParam->getIndex()] = Result; 00398 return Sema::TDK_Success; 00399 } 00400 00401 // Verify that the two template names are equivalent. 00402 if (S.Context.hasSameTemplateName(Param, Arg)) 00403 return Sema::TDK_Success; 00404 00405 // Mismatch of non-dependent template parameter to argument. 00406 Info.FirstArg = TemplateArgument(Param); 00407 Info.SecondArg = TemplateArgument(Arg); 00408 return Sema::TDK_NonDeducedMismatch; 00409 } 00410 00411 /// \brief Deduce the template arguments by comparing the template parameter 00412 /// type (which is a template-id) with the template argument type. 00413 /// 00414 /// \param S the Sema 00415 /// 00416 /// \param TemplateParams the template parameters that we are deducing 00417 /// 00418 /// \param Param the parameter type 00419 /// 00420 /// \param Arg the argument type 00421 /// 00422 /// \param Info information about the template argument deduction itself 00423 /// 00424 /// \param Deduced the deduced template arguments 00425 /// 00426 /// \returns the result of template argument deduction so far. Note that a 00427 /// "success" result means that template argument deduction has not yet failed, 00428 /// but it may still fail, later, for other reasons. 00429 static Sema::TemplateDeductionResult 00430 DeduceTemplateArguments(Sema &S, 00431 TemplateParameterList *TemplateParams, 00432 const TemplateSpecializationType *Param, 00433 QualType Arg, 00434 TemplateDeductionInfo &Info, 00435 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 00436 assert(Arg.isCanonical() && "Argument type must be canonical"); 00437 00438 // Check whether the template argument is a dependent template-id. 00439 if (const TemplateSpecializationType *SpecArg 00440 = dyn_cast<TemplateSpecializationType>(Arg)) { 00441 // Perform template argument deduction for the template name. 00442 if (Sema::TemplateDeductionResult Result 00443 = DeduceTemplateArguments(S, TemplateParams, 00444 Param->getTemplateName(), 00445 SpecArg->getTemplateName(), 00446 Info, Deduced)) 00447 return Result; 00448 00449 00450 // Perform template argument deduction on each template 00451 // argument. Ignore any missing/extra arguments, since they could be 00452 // filled in by default arguments. 00453 return DeduceTemplateArguments(S, TemplateParams, 00454 Param->getArgs(), Param->getNumArgs(), 00455 SpecArg->getArgs(), SpecArg->getNumArgs(), 00456 Info, Deduced, 00457 /*NumberOfArgumentsMustMatch=*/false); 00458 } 00459 00460 // If the argument type is a class template specialization, we 00461 // perform template argument deduction using its template 00462 // arguments. 00463 const RecordType *RecordArg = dyn_cast<RecordType>(Arg); 00464 if (!RecordArg) 00465 return Sema::TDK_NonDeducedMismatch; 00466 00467 ClassTemplateSpecializationDecl *SpecArg 00468 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl()); 00469 if (!SpecArg) 00470 return Sema::TDK_NonDeducedMismatch; 00471 00472 // Perform template argument deduction for the template name. 00473 if (Sema::TemplateDeductionResult Result 00474 = DeduceTemplateArguments(S, 00475 TemplateParams, 00476 Param->getTemplateName(), 00477 TemplateName(SpecArg->getSpecializedTemplate()), 00478 Info, Deduced)) 00479 return Result; 00480 00481 // Perform template argument deduction for the template arguments. 00482 return DeduceTemplateArguments(S, TemplateParams, 00483 Param->getArgs(), Param->getNumArgs(), 00484 SpecArg->getTemplateArgs().data(), 00485 SpecArg->getTemplateArgs().size(), 00486 Info, Deduced); 00487 } 00488 00489 /// \brief Determines whether the given type is an opaque type that 00490 /// might be more qualified when instantiated. 00491 static bool IsPossiblyOpaquelyQualifiedType(QualType T) { 00492 switch (T->getTypeClass()) { 00493 case Type::TypeOfExpr: 00494 case Type::TypeOf: 00495 case Type::DependentName: 00496 case Type::Decltype: 00497 case Type::UnresolvedUsing: 00498 case Type::TemplateTypeParm: 00499 return true; 00500 00501 case Type::ConstantArray: 00502 case Type::IncompleteArray: 00503 case Type::VariableArray: 00504 case Type::DependentSizedArray: 00505 return IsPossiblyOpaquelyQualifiedType( 00506 cast<ArrayType>(T)->getElementType()); 00507 00508 default: 00509 return false; 00510 } 00511 } 00512 00513 /// \brief Retrieve the depth and index of a template parameter. 00514 static std::pair<unsigned, unsigned> 00515 getDepthAndIndex(NamedDecl *ND) { 00516 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND)) 00517 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 00518 00519 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND)) 00520 return std::make_pair(NTTP->getDepth(), NTTP->getIndex()); 00521 00522 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND); 00523 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 00524 } 00525 00526 /// \brief Retrieve the depth and index of an unexpanded parameter pack. 00527 static std::pair<unsigned, unsigned> 00528 getDepthAndIndex(UnexpandedParameterPack UPP) { 00529 if (const TemplateTypeParmType *TTP 00530 = UPP.first.dyn_cast<const TemplateTypeParmType *>()) 00531 return std::make_pair(TTP->getDepth(), TTP->getIndex()); 00532 00533 return getDepthAndIndex(UPP.first.get<NamedDecl *>()); 00534 } 00535 00536 /// \brief Helper function to build a TemplateParameter when we don't 00537 /// know its type statically. 00538 static TemplateParameter makeTemplateParameter(Decl *D) { 00539 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D)) 00540 return TemplateParameter(TTP); 00541 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) 00542 return TemplateParameter(NTTP); 00543 00544 return TemplateParameter(cast<TemplateTemplateParmDecl>(D)); 00545 } 00546 00547 /// \brief Prepare to perform template argument deduction for all of the 00548 /// arguments in a set of argument packs. 00549 static void PrepareArgumentPackDeduction(Sema &S, 00550 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00551 ArrayRef<unsigned> PackIndices, 00552 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks, 00553 SmallVectorImpl< 00554 SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) { 00555 // Save the deduced template arguments for each parameter pack expanded 00556 // by this pack expansion, then clear out the deduction. 00557 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 00558 // Save the previously-deduced argument pack, then clear it out so that we 00559 // can deduce a new argument pack. 00560 SavedPacks[I] = Deduced[PackIndices[I]]; 00561 Deduced[PackIndices[I]] = TemplateArgument(); 00562 00563 // If the template arugment pack was explicitly specified, add that to 00564 // the set of deduced arguments. 00565 const TemplateArgument *ExplicitArgs; 00566 unsigned NumExplicitArgs; 00567 if (NamedDecl *PartiallySubstitutedPack 00568 = S.CurrentInstantiationScope->getPartiallySubstitutedPack( 00569 &ExplicitArgs, 00570 &NumExplicitArgs)) { 00571 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I]) 00572 NewlyDeducedPacks[I].append(ExplicitArgs, 00573 ExplicitArgs + NumExplicitArgs); 00574 } 00575 } 00576 } 00577 00578 /// \brief Finish template argument deduction for a set of argument packs, 00579 /// producing the argument packs and checking for consistency with prior 00580 /// deductions. 00581 static Sema::TemplateDeductionResult 00582 FinishArgumentPackDeduction(Sema &S, 00583 TemplateParameterList *TemplateParams, 00584 bool HasAnyArguments, 00585 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00586 ArrayRef<unsigned> PackIndices, 00587 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks, 00588 SmallVectorImpl< 00589 SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks, 00590 TemplateDeductionInfo &Info) { 00591 // Build argument packs for each of the parameter packs expanded by this 00592 // pack expansion. 00593 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 00594 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) { 00595 // We were not able to deduce anything for this parameter pack, 00596 // so just restore the saved argument pack. 00597 Deduced[PackIndices[I]] = SavedPacks[I]; 00598 continue; 00599 } 00600 00601 DeducedTemplateArgument NewPack; 00602 00603 if (NewlyDeducedPacks[I].empty()) { 00604 // If we deduced an empty argument pack, create it now. 00605 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0)); 00606 } else { 00607 TemplateArgument *ArgumentPack 00608 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()]; 00609 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(), 00610 ArgumentPack); 00611 NewPack 00612 = DeducedTemplateArgument(TemplateArgument(ArgumentPack, 00613 NewlyDeducedPacks[I].size()), 00614 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound()); 00615 } 00616 00617 DeducedTemplateArgument Result 00618 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack); 00619 if (Result.isNull()) { 00620 Info.Param 00621 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I])); 00622 Info.FirstArg = SavedPacks[I]; 00623 Info.SecondArg = NewPack; 00624 return Sema::TDK_Inconsistent; 00625 } 00626 00627 Deduced[PackIndices[I]] = Result; 00628 } 00629 00630 return Sema::TDK_Success; 00631 } 00632 00633 /// \brief Deduce the template arguments by comparing the list of parameter 00634 /// types to the list of argument types, as in the parameter-type-lists of 00635 /// function types (C++ [temp.deduct.type]p10). 00636 /// 00637 /// \param S The semantic analysis object within which we are deducing 00638 /// 00639 /// \param TemplateParams The template parameters that we are deducing 00640 /// 00641 /// \param Params The list of parameter types 00642 /// 00643 /// \param NumParams The number of types in \c Params 00644 /// 00645 /// \param Args The list of argument types 00646 /// 00647 /// \param NumArgs The number of types in \c Args 00648 /// 00649 /// \param Info information about the template argument deduction itself 00650 /// 00651 /// \param Deduced the deduced template arguments 00652 /// 00653 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 00654 /// how template argument deduction is performed. 00655 /// 00656 /// \param PartialOrdering If true, we are performing template argument 00657 /// deduction for during partial ordering for a call 00658 /// (C++0x [temp.deduct.partial]). 00659 /// 00660 /// \param RefParamComparisons If we're performing template argument deduction 00661 /// in the context of partial ordering, the set of qualifier comparisons. 00662 /// 00663 /// \returns the result of template argument deduction so far. Note that a 00664 /// "success" result means that template argument deduction has not yet failed, 00665 /// but it may still fail, later, for other reasons. 00666 static Sema::TemplateDeductionResult 00667 DeduceTemplateArguments(Sema &S, 00668 TemplateParameterList *TemplateParams, 00669 const QualType *Params, unsigned NumParams, 00670 const QualType *Args, unsigned NumArgs, 00671 TemplateDeductionInfo &Info, 00672 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00673 unsigned TDF, 00674 bool PartialOrdering = false, 00675 SmallVectorImpl<RefParamPartialOrderingComparison> * 00676 RefParamComparisons = 0) { 00677 // Fast-path check to see if we have too many/too few arguments. 00678 if (NumParams != NumArgs && 00679 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) && 00680 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1]))) 00681 return Sema::TDK_NonDeducedMismatch; 00682 00683 // C++0x [temp.deduct.type]p10: 00684 // Similarly, if P has a form that contains (T), then each parameter type 00685 // Pi of the respective parameter-type- list of P is compared with the 00686 // corresponding parameter type Ai of the corresponding parameter-type-list 00687 // of A. [...] 00688 unsigned ArgIdx = 0, ParamIdx = 0; 00689 for (; ParamIdx != NumParams; ++ParamIdx) { 00690 // Check argument types. 00691 const PackExpansionType *Expansion 00692 = dyn_cast<PackExpansionType>(Params[ParamIdx]); 00693 if (!Expansion) { 00694 // Simple case: compare the parameter and argument types at this point. 00695 00696 // Make sure we have an argument. 00697 if (ArgIdx >= NumArgs) 00698 return Sema::TDK_NonDeducedMismatch; 00699 00700 if (isa<PackExpansionType>(Args[ArgIdx])) { 00701 // C++0x [temp.deduct.type]p22: 00702 // If the original function parameter associated with A is a function 00703 // parameter pack and the function parameter associated with P is not 00704 // a function parameter pack, then template argument deduction fails. 00705 return Sema::TDK_NonDeducedMismatch; 00706 } 00707 00708 if (Sema::TemplateDeductionResult Result 00709 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 00710 Params[ParamIdx], Args[ArgIdx], 00711 Info, Deduced, TDF, 00712 PartialOrdering, 00713 RefParamComparisons)) 00714 return Result; 00715 00716 ++ArgIdx; 00717 continue; 00718 } 00719 00720 // C++0x [temp.deduct.type]p5: 00721 // The non-deduced contexts are: 00722 // - A function parameter pack that does not occur at the end of the 00723 // parameter-declaration-clause. 00724 if (ParamIdx + 1 < NumParams) 00725 return Sema::TDK_Success; 00726 00727 // C++0x [temp.deduct.type]p10: 00728 // If the parameter-declaration corresponding to Pi is a function 00729 // parameter pack, then the type of its declarator- id is compared with 00730 // each remaining parameter type in the parameter-type-list of A. Each 00731 // comparison deduces template arguments for subsequent positions in the 00732 // template parameter packs expanded by the function parameter pack. 00733 00734 // Compute the set of template parameter indices that correspond to 00735 // parameter packs expanded by the pack expansion. 00736 SmallVector<unsigned, 2> PackIndices; 00737 QualType Pattern = Expansion->getPattern(); 00738 { 00739 llvm::SmallBitVector SawIndices(TemplateParams->size()); 00740 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 00741 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 00742 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 00743 unsigned Depth, Index; 00744 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 00745 if (Depth == 0 && !SawIndices[Index]) { 00746 SawIndices[Index] = true; 00747 PackIndices.push_back(Index); 00748 } 00749 } 00750 } 00751 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?"); 00752 00753 // Keep track of the deduced template arguments for each parameter pack 00754 // expanded by this pack expansion (the outer index) and for each 00755 // template argument (the inner SmallVectors). 00756 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2> 00757 NewlyDeducedPacks(PackIndices.size()); 00758 SmallVector<DeducedTemplateArgument, 2> 00759 SavedPacks(PackIndices.size()); 00760 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks, 00761 NewlyDeducedPacks); 00762 00763 bool HasAnyArguments = false; 00764 for (; ArgIdx < NumArgs; ++ArgIdx) { 00765 HasAnyArguments = true; 00766 00767 // Deduce template arguments from the pattern. 00768 if (Sema::TemplateDeductionResult Result 00769 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern, 00770 Args[ArgIdx], Info, Deduced, 00771 TDF, PartialOrdering, 00772 RefParamComparisons)) 00773 return Result; 00774 00775 // Capture the deduced template arguments for each parameter pack expanded 00776 // by this pack expansion, add them to the list of arguments we've deduced 00777 // for that pack, then clear out the deduced argument. 00778 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 00779 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]]; 00780 if (!DeducedArg.isNull()) { 00781 NewlyDeducedPacks[I].push_back(DeducedArg); 00782 DeducedArg = DeducedTemplateArgument(); 00783 } 00784 } 00785 } 00786 00787 // Build argument packs for each of the parameter packs expanded by this 00788 // pack expansion. 00789 if (Sema::TemplateDeductionResult Result 00790 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments, 00791 Deduced, PackIndices, SavedPacks, 00792 NewlyDeducedPacks, Info)) 00793 return Result; 00794 } 00795 00796 // Make sure we don't have any extra arguments. 00797 if (ArgIdx < NumArgs) 00798 return Sema::TDK_NonDeducedMismatch; 00799 00800 return Sema::TDK_Success; 00801 } 00802 00803 /// \brief Determine whether the parameter has qualifiers that are either 00804 /// inconsistent with or a superset of the argument's qualifiers. 00805 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, 00806 QualType ArgType) { 00807 Qualifiers ParamQs = ParamType.getQualifiers(); 00808 Qualifiers ArgQs = ArgType.getQualifiers(); 00809 00810 if (ParamQs == ArgQs) 00811 return false; 00812 00813 // Mismatched (but not missing) Objective-C GC attributes. 00814 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() && 00815 ParamQs.hasObjCGCAttr()) 00816 return true; 00817 00818 // Mismatched (but not missing) address spaces. 00819 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() && 00820 ParamQs.hasAddressSpace()) 00821 return true; 00822 00823 // Mismatched (but not missing) Objective-C lifetime qualifiers. 00824 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() && 00825 ParamQs.hasObjCLifetime()) 00826 return true; 00827 00828 // CVR qualifier superset. 00829 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) && 00830 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers()) 00831 == ParamQs.getCVRQualifiers()); 00832 } 00833 00834 /// \brief Deduce the template arguments by comparing the parameter type and 00835 /// the argument type (C++ [temp.deduct.type]). 00836 /// 00837 /// \param S the semantic analysis object within which we are deducing 00838 /// 00839 /// \param TemplateParams the template parameters that we are deducing 00840 /// 00841 /// \param ParamIn the parameter type 00842 /// 00843 /// \param ArgIn the argument type 00844 /// 00845 /// \param Info information about the template argument deduction itself 00846 /// 00847 /// \param Deduced the deduced template arguments 00848 /// 00849 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe 00850 /// how template argument deduction is performed. 00851 /// 00852 /// \param PartialOrdering Whether we're performing template argument deduction 00853 /// in the context of partial ordering (C++0x [temp.deduct.partial]). 00854 /// 00855 /// \param RefParamComparisons If we're performing template argument deduction 00856 /// in the context of partial ordering, the set of qualifier comparisons. 00857 /// 00858 /// \returns the result of template argument deduction so far. Note that a 00859 /// "success" result means that template argument deduction has not yet failed, 00860 /// but it may still fail, later, for other reasons. 00861 static Sema::TemplateDeductionResult 00862 DeduceTemplateArgumentsByTypeMatch(Sema &S, 00863 TemplateParameterList *TemplateParams, 00864 QualType ParamIn, QualType ArgIn, 00865 TemplateDeductionInfo &Info, 00866 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 00867 unsigned TDF, 00868 bool PartialOrdering, 00869 SmallVectorImpl<RefParamPartialOrderingComparison> * 00870 RefParamComparisons) { 00871 // We only want to look at the canonical types, since typedefs and 00872 // sugar are not part of template argument deduction. 00873 QualType Param = S.Context.getCanonicalType(ParamIn); 00874 QualType Arg = S.Context.getCanonicalType(ArgIn); 00875 00876 // If the argument type is a pack expansion, look at its pattern. 00877 // This isn't explicitly called out 00878 if (const PackExpansionType *ArgExpansion 00879 = dyn_cast<PackExpansionType>(Arg)) 00880 Arg = ArgExpansion->getPattern(); 00881 00882 if (PartialOrdering) { 00883 // C++0x [temp.deduct.partial]p5: 00884 // Before the partial ordering is done, certain transformations are 00885 // performed on the types used for partial ordering: 00886 // - If P is a reference type, P is replaced by the type referred to. 00887 const ReferenceType *ParamRef = Param->getAs<ReferenceType>(); 00888 if (ParamRef) 00889 Param = ParamRef->getPointeeType(); 00890 00891 // - If A is a reference type, A is replaced by the type referred to. 00892 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>(); 00893 if (ArgRef) 00894 Arg = ArgRef->getPointeeType(); 00895 00896 if (RefParamComparisons && ParamRef && ArgRef) { 00897 // C++0x [temp.deduct.partial]p6: 00898 // If both P and A were reference types (before being replaced with the 00899 // type referred to above), determine which of the two types (if any) is 00900 // more cv-qualified than the other; otherwise the types are considered 00901 // to be equally cv-qualified for partial ordering purposes. The result 00902 // of this determination will be used below. 00903 // 00904 // We save this information for later, using it only when deduction 00905 // succeeds in both directions. 00906 RefParamPartialOrderingComparison Comparison; 00907 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>(); 00908 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>(); 00909 Comparison.Qualifiers = NeitherMoreQualified; 00910 00911 Qualifiers ParamQuals = Param.getQualifiers(); 00912 Qualifiers ArgQuals = Arg.getQualifiers(); 00913 if (ParamQuals.isStrictSupersetOf(ArgQuals)) 00914 Comparison.Qualifiers = ParamMoreQualified; 00915 else if (ArgQuals.isStrictSupersetOf(ParamQuals)) 00916 Comparison.Qualifiers = ArgMoreQualified; 00917 RefParamComparisons->push_back(Comparison); 00918 } 00919 00920 // C++0x [temp.deduct.partial]p7: 00921 // Remove any top-level cv-qualifiers: 00922 // - If P is a cv-qualified type, P is replaced by the cv-unqualified 00923 // version of P. 00924 Param = Param.getUnqualifiedType(); 00925 // - If A is a cv-qualified type, A is replaced by the cv-unqualified 00926 // version of A. 00927 Arg = Arg.getUnqualifiedType(); 00928 } else { 00929 // C++0x [temp.deduct.call]p4 bullet 1: 00930 // - If the original P is a reference type, the deduced A (i.e., the type 00931 // referred to by the reference) can be more cv-qualified than the 00932 // transformed A. 00933 if (TDF & TDF_ParamWithReferenceType) { 00934 Qualifiers Quals; 00935 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals); 00936 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & 00937 Arg.getCVRQualifiers()); 00938 Param = S.Context.getQualifiedType(UnqualParam, Quals); 00939 } 00940 00941 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) { 00942 // C++0x [temp.deduct.type]p10: 00943 // If P and A are function types that originated from deduction when 00944 // taking the address of a function template (14.8.2.2) or when deducing 00945 // template arguments from a function declaration (14.8.2.6) and Pi and 00946 // Ai are parameters of the top-level parameter-type-list of P and A, 00947 // respectively, Pi is adjusted if it is an rvalue reference to a 00948 // cv-unqualified template parameter and Ai is an lvalue reference, in 00949 // which case the type of Pi is changed to be the template parameter 00950 // type (i.e., T&& is changed to simply T). [ Note: As a result, when 00951 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be 00952 // deduced as X&. - end note ] 00953 TDF &= ~TDF_TopLevelParameterTypeList; 00954 00955 if (const RValueReferenceType *ParamRef 00956 = Param->getAs<RValueReferenceType>()) { 00957 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) && 00958 !ParamRef->getPointeeType().getQualifiers()) 00959 if (Arg->isLValueReferenceType()) 00960 Param = ParamRef->getPointeeType(); 00961 } 00962 } 00963 } 00964 00965 // C++ [temp.deduct.type]p9: 00966 // A template type argument T, a template template argument TT or a 00967 // template non-type argument i can be deduced if P and A have one of 00968 // the following forms: 00969 // 00970 // T 00971 // cv-list T 00972 if (const TemplateTypeParmType *TemplateTypeParm 00973 = Param->getAs<TemplateTypeParmType>()) { 00974 // Just skip any attempts to deduce from a placeholder type. 00975 if (Arg->isPlaceholderType()) 00976 return Sema::TDK_Success; 00977 00978 unsigned Index = TemplateTypeParm->getIndex(); 00979 bool RecanonicalizeArg = false; 00980 00981 // If the argument type is an array type, move the qualifiers up to the 00982 // top level, so they can be matched with the qualifiers on the parameter. 00983 if (isa<ArrayType>(Arg)) { 00984 Qualifiers Quals; 00985 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals); 00986 if (Quals) { 00987 Arg = S.Context.getQualifiedType(Arg, Quals); 00988 RecanonicalizeArg = true; 00989 } 00990 } 00991 00992 // The argument type can not be less qualified than the parameter 00993 // type. 00994 if (!(TDF & TDF_IgnoreQualifiers) && 00995 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) { 00996 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 00997 Info.FirstArg = TemplateArgument(Param); 00998 Info.SecondArg = TemplateArgument(Arg); 00999 return Sema::TDK_Underqualified; 01000 } 01001 01002 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0"); 01003 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function"); 01004 QualType DeducedType = Arg; 01005 01006 // Remove any qualifiers on the parameter from the deduced type. 01007 // We checked the qualifiers for consistency above. 01008 Qualifiers DeducedQs = DeducedType.getQualifiers(); 01009 Qualifiers ParamQs = Param.getQualifiers(); 01010 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers()); 01011 if (ParamQs.hasObjCGCAttr()) 01012 DeducedQs.removeObjCGCAttr(); 01013 if (ParamQs.hasAddressSpace()) 01014 DeducedQs.removeAddressSpace(); 01015 if (ParamQs.hasObjCLifetime()) 01016 DeducedQs.removeObjCLifetime(); 01017 01018 // Objective-C ARC: 01019 // If template deduction would produce a lifetime qualifier on a type 01020 // that is not a lifetime type, template argument deduction fails. 01021 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() && 01022 !DeducedType->isDependentType()) { 01023 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 01024 Info.FirstArg = TemplateArgument(Param); 01025 Info.SecondArg = TemplateArgument(Arg); 01026 return Sema::TDK_Underqualified; 01027 } 01028 01029 // Objective-C ARC: 01030 // If template deduction would produce an argument type with lifetime type 01031 // but no lifetime qualifier, the __strong lifetime qualifier is inferred. 01032 if (S.getLangOpts().ObjCAutoRefCount && 01033 DeducedType->isObjCLifetimeType() && 01034 !DeducedQs.hasObjCLifetime()) 01035 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong); 01036 01037 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), 01038 DeducedQs); 01039 01040 if (RecanonicalizeArg) 01041 DeducedType = S.Context.getCanonicalType(DeducedType); 01042 01043 DeducedTemplateArgument NewDeduced(DeducedType); 01044 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context, 01045 Deduced[Index], 01046 NewDeduced); 01047 if (Result.isNull()) { 01048 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index)); 01049 Info.FirstArg = Deduced[Index]; 01050 Info.SecondArg = NewDeduced; 01051 return Sema::TDK_Inconsistent; 01052 } 01053 01054 Deduced[Index] = Result; 01055 return Sema::TDK_Success; 01056 } 01057 01058 // Set up the template argument deduction information for a failure. 01059 Info.FirstArg = TemplateArgument(ParamIn); 01060 Info.SecondArg = TemplateArgument(ArgIn); 01061 01062 // If the parameter is an already-substituted template parameter 01063 // pack, do nothing: we don't know which of its arguments to look 01064 // at, so we have to wait until all of the parameter packs in this 01065 // expansion have arguments. 01066 if (isa<SubstTemplateTypeParmPackType>(Param)) 01067 return Sema::TDK_Success; 01068 01069 // Check the cv-qualifiers on the parameter and argument types. 01070 if (!(TDF & TDF_IgnoreQualifiers)) { 01071 if (TDF & TDF_ParamWithReferenceType) { 01072 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg)) 01073 return Sema::TDK_NonDeducedMismatch; 01074 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) { 01075 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers()) 01076 return Sema::TDK_NonDeducedMismatch; 01077 } 01078 01079 // If the parameter type is not dependent, there is nothing to deduce. 01080 if (!Param->isDependentType()) { 01081 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) 01082 return Sema::TDK_NonDeducedMismatch; 01083 01084 return Sema::TDK_Success; 01085 } 01086 } else if (!Param->isDependentType() && 01087 Param.getUnqualifiedType() == Arg.getUnqualifiedType()) { 01088 return Sema::TDK_Success; 01089 } 01090 01091 switch (Param->getTypeClass()) { 01092 // Non-canonical types cannot appear here. 01093 #define NON_CANONICAL_TYPE(Class, Base) \ 01094 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class); 01095 #define TYPE(Class, Base) 01096 #include "clang/AST/TypeNodes.def" 01097 01098 case Type::TemplateTypeParm: 01099 case Type::SubstTemplateTypeParmPack: 01100 llvm_unreachable("Type nodes handled above"); 01101 01102 // These types cannot be dependent, so simply check whether the types are 01103 // the same. 01104 case Type::Builtin: 01105 case Type::VariableArray: 01106 case Type::Vector: 01107 case Type::FunctionNoProto: 01108 case Type::Record: 01109 case Type::Enum: 01110 case Type::ObjCObject: 01111 case Type::ObjCInterface: 01112 case Type::ObjCObjectPointer: { 01113 if (TDF & TDF_SkipNonDependent) 01114 return Sema::TDK_Success; 01115 01116 if (TDF & TDF_IgnoreQualifiers) { 01117 Param = Param.getUnqualifiedType(); 01118 Arg = Arg.getUnqualifiedType(); 01119 } 01120 01121 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch; 01122 } 01123 01124 // _Complex T [placeholder extension] 01125 case Type::Complex: 01126 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>()) 01127 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01128 cast<ComplexType>(Param)->getElementType(), 01129 ComplexArg->getElementType(), 01130 Info, Deduced, TDF); 01131 01132 return Sema::TDK_NonDeducedMismatch; 01133 01134 // _Atomic T [extension] 01135 case Type::Atomic: 01136 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>()) 01137 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01138 cast<AtomicType>(Param)->getValueType(), 01139 AtomicArg->getValueType(), 01140 Info, Deduced, TDF); 01141 01142 return Sema::TDK_NonDeducedMismatch; 01143 01144 // T * 01145 case Type::Pointer: { 01146 QualType PointeeType; 01147 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) { 01148 PointeeType = PointerArg->getPointeeType(); 01149 } else if (const ObjCObjectPointerType *PointerArg 01150 = Arg->getAs<ObjCObjectPointerType>()) { 01151 PointeeType = PointerArg->getPointeeType(); 01152 } else { 01153 return Sema::TDK_NonDeducedMismatch; 01154 } 01155 01156 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass); 01157 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01158 cast<PointerType>(Param)->getPointeeType(), 01159 PointeeType, 01160 Info, Deduced, SubTDF); 01161 } 01162 01163 // T & 01164 case Type::LValueReference: { 01165 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>(); 01166 if (!ReferenceArg) 01167 return Sema::TDK_NonDeducedMismatch; 01168 01169 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01170 cast<LValueReferenceType>(Param)->getPointeeType(), 01171 ReferenceArg->getPointeeType(), Info, Deduced, 0); 01172 } 01173 01174 // T && [C++0x] 01175 case Type::RValueReference: { 01176 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>(); 01177 if (!ReferenceArg) 01178 return Sema::TDK_NonDeducedMismatch; 01179 01180 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01181 cast<RValueReferenceType>(Param)->getPointeeType(), 01182 ReferenceArg->getPointeeType(), 01183 Info, Deduced, 0); 01184 } 01185 01186 // T [] (implied, but not stated explicitly) 01187 case Type::IncompleteArray: { 01188 const IncompleteArrayType *IncompleteArrayArg = 01189 S.Context.getAsIncompleteArrayType(Arg); 01190 if (!IncompleteArrayArg) 01191 return Sema::TDK_NonDeducedMismatch; 01192 01193 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 01194 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01195 S.Context.getAsIncompleteArrayType(Param)->getElementType(), 01196 IncompleteArrayArg->getElementType(), 01197 Info, Deduced, SubTDF); 01198 } 01199 01200 // T [integer-constant] 01201 case Type::ConstantArray: { 01202 const ConstantArrayType *ConstantArrayArg = 01203 S.Context.getAsConstantArrayType(Arg); 01204 if (!ConstantArrayArg) 01205 return Sema::TDK_NonDeducedMismatch; 01206 01207 const ConstantArrayType *ConstantArrayParm = 01208 S.Context.getAsConstantArrayType(Param); 01209 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize()) 01210 return Sema::TDK_NonDeducedMismatch; 01211 01212 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 01213 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01214 ConstantArrayParm->getElementType(), 01215 ConstantArrayArg->getElementType(), 01216 Info, Deduced, SubTDF); 01217 } 01218 01219 // type [i] 01220 case Type::DependentSizedArray: { 01221 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg); 01222 if (!ArrayArg) 01223 return Sema::TDK_NonDeducedMismatch; 01224 01225 unsigned SubTDF = TDF & TDF_IgnoreQualifiers; 01226 01227 // Check the element type of the arrays 01228 const DependentSizedArrayType *DependentArrayParm 01229 = S.Context.getAsDependentSizedArrayType(Param); 01230 if (Sema::TemplateDeductionResult Result 01231 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01232 DependentArrayParm->getElementType(), 01233 ArrayArg->getElementType(), 01234 Info, Deduced, SubTDF)) 01235 return Result; 01236 01237 // Determine the array bound is something we can deduce. 01238 NonTypeTemplateParmDecl *NTTP 01239 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr()); 01240 if (!NTTP) 01241 return Sema::TDK_Success; 01242 01243 // We can perform template argument deduction for the given non-type 01244 // template parameter. 01245 assert(NTTP->getDepth() == 0 && 01246 "Cannot deduce non-type template argument at depth > 0"); 01247 if (const ConstantArrayType *ConstantArrayArg 01248 = dyn_cast<ConstantArrayType>(ArrayArg)) { 01249 llvm::APSInt Size(ConstantArrayArg->getSize()); 01250 return DeduceNonTypeTemplateArgument(S, NTTP, Size, 01251 S.Context.getSizeType(), 01252 /*ArrayBound=*/true, 01253 Info, Deduced); 01254 } 01255 if (const DependentSizedArrayType *DependentArrayArg 01256 = dyn_cast<DependentSizedArrayType>(ArrayArg)) 01257 if (DependentArrayArg->getSizeExpr()) 01258 return DeduceNonTypeTemplateArgument(S, NTTP, 01259 DependentArrayArg->getSizeExpr(), 01260 Info, Deduced); 01261 01262 // Incomplete type does not match a dependently-sized array type 01263 return Sema::TDK_NonDeducedMismatch; 01264 } 01265 01266 // type(*)(T) 01267 // T(*)() 01268 // T(*)(T) 01269 case Type::FunctionProto: { 01270 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList; 01271 const FunctionProtoType *FunctionProtoArg = 01272 dyn_cast<FunctionProtoType>(Arg); 01273 if (!FunctionProtoArg) 01274 return Sema::TDK_NonDeducedMismatch; 01275 01276 const FunctionProtoType *FunctionProtoParam = 01277 cast<FunctionProtoType>(Param); 01278 01279 if (FunctionProtoParam->getTypeQuals() 01280 != FunctionProtoArg->getTypeQuals() || 01281 FunctionProtoParam->getRefQualifier() 01282 != FunctionProtoArg->getRefQualifier() || 01283 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic()) 01284 return Sema::TDK_NonDeducedMismatch; 01285 01286 // Check return types. 01287 if (Sema::TemplateDeductionResult Result 01288 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01289 FunctionProtoParam->getResultType(), 01290 FunctionProtoArg->getResultType(), 01291 Info, Deduced, 0)) 01292 return Result; 01293 01294 return DeduceTemplateArguments(S, TemplateParams, 01295 FunctionProtoParam->arg_type_begin(), 01296 FunctionProtoParam->getNumArgs(), 01297 FunctionProtoArg->arg_type_begin(), 01298 FunctionProtoArg->getNumArgs(), 01299 Info, Deduced, SubTDF); 01300 } 01301 01302 case Type::InjectedClassName: { 01303 // Treat a template's injected-class-name as if the template 01304 // specialization type had been used. 01305 Param = cast<InjectedClassNameType>(Param) 01306 ->getInjectedSpecializationType(); 01307 assert(isa<TemplateSpecializationType>(Param) && 01308 "injected class name is not a template specialization type"); 01309 // fall through 01310 } 01311 01312 // template-name<T> (where template-name refers to a class template) 01313 // template-name<i> 01314 // TT<T> 01315 // TT<i> 01316 // TT<> 01317 case Type::TemplateSpecialization: { 01318 const TemplateSpecializationType *SpecParam 01319 = cast<TemplateSpecializationType>(Param); 01320 01321 // Try to deduce template arguments from the template-id. 01322 Sema::TemplateDeductionResult Result 01323 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, 01324 Info, Deduced); 01325 01326 if (Result && (TDF & TDF_DerivedClass)) { 01327 // C++ [temp.deduct.call]p3b3: 01328 // If P is a class, and P has the form template-id, then A can be a 01329 // derived class of the deduced A. Likewise, if P is a pointer to a 01330 // class of the form template-id, A can be a pointer to a derived 01331 // class pointed to by the deduced A. 01332 // 01333 // More importantly: 01334 // These alternatives are considered only if type deduction would 01335 // otherwise fail. 01336 if (const RecordType *RecordT = Arg->getAs<RecordType>()) { 01337 // We cannot inspect base classes as part of deduction when the type 01338 // is incomplete, so either instantiate any templates necessary to 01339 // complete the type, or skip over it if it cannot be completed. 01340 if (S.RequireCompleteType(Info.getLocation(), Arg, 0)) 01341 return Result; 01342 01343 // Use data recursion to crawl through the list of base classes. 01344 // Visited contains the set of nodes we have already visited, while 01345 // ToVisit is our stack of records that we still need to visit. 01346 llvm::SmallPtrSet<const RecordType *, 8> Visited; 01347 SmallVector<const RecordType *, 8> ToVisit; 01348 ToVisit.push_back(RecordT); 01349 bool Successful = false; 01350 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(), 01351 Deduced.end()); 01352 while (!ToVisit.empty()) { 01353 // Retrieve the next class in the inheritance hierarchy. 01354 const RecordType *NextT = ToVisit.back(); 01355 ToVisit.pop_back(); 01356 01357 // If we have already seen this type, skip it. 01358 if (!Visited.insert(NextT)) 01359 continue; 01360 01361 // If this is a base class, try to perform template argument 01362 // deduction from it. 01363 if (NextT != RecordT) { 01364 Sema::TemplateDeductionResult BaseResult 01365 = DeduceTemplateArguments(S, TemplateParams, SpecParam, 01366 QualType(NextT, 0), Info, Deduced); 01367 01368 // If template argument deduction for this base was successful, 01369 // note that we had some success. Otherwise, ignore any deductions 01370 // from this base class. 01371 if (BaseResult == Sema::TDK_Success) { 01372 Successful = true; 01373 DeducedOrig.clear(); 01374 DeducedOrig.append(Deduced.begin(), Deduced.end()); 01375 } 01376 else 01377 Deduced = DeducedOrig; 01378 } 01379 01380 // Visit base classes 01381 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl()); 01382 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(), 01383 BaseEnd = Next->bases_end(); 01384 Base != BaseEnd; ++Base) { 01385 assert(Base->getType()->isRecordType() && 01386 "Base class that isn't a record?"); 01387 ToVisit.push_back(Base->getType()->getAs<RecordType>()); 01388 } 01389 } 01390 01391 if (Successful) 01392 return Sema::TDK_Success; 01393 } 01394 01395 } 01396 01397 return Result; 01398 } 01399 01400 // T type::* 01401 // T T::* 01402 // T (type::*)() 01403 // type (T::*)() 01404 // type (type::*)(T) 01405 // type (T::*)(T) 01406 // T (type::*)(T) 01407 // T (T::*)() 01408 // T (T::*)(T) 01409 case Type::MemberPointer: { 01410 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param); 01411 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg); 01412 if (!MemPtrArg) 01413 return Sema::TDK_NonDeducedMismatch; 01414 01415 if (Sema::TemplateDeductionResult Result 01416 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01417 MemPtrParam->getPointeeType(), 01418 MemPtrArg->getPointeeType(), 01419 Info, Deduced, 01420 TDF & TDF_IgnoreQualifiers)) 01421 return Result; 01422 01423 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01424 QualType(MemPtrParam->getClass(), 0), 01425 QualType(MemPtrArg->getClass(), 0), 01426 Info, Deduced, 01427 TDF & TDF_IgnoreQualifiers); 01428 } 01429 01430 // (clang extension) 01431 // 01432 // type(^)(T) 01433 // T(^)() 01434 // T(^)(T) 01435 case Type::BlockPointer: { 01436 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param); 01437 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg); 01438 01439 if (!BlockPtrArg) 01440 return Sema::TDK_NonDeducedMismatch; 01441 01442 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01443 BlockPtrParam->getPointeeType(), 01444 BlockPtrArg->getPointeeType(), 01445 Info, Deduced, 0); 01446 } 01447 01448 // (clang extension) 01449 // 01450 // T __attribute__(((ext_vector_type(<integral constant>)))) 01451 case Type::ExtVector: { 01452 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param); 01453 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 01454 // Make sure that the vectors have the same number of elements. 01455 if (VectorParam->getNumElements() != VectorArg->getNumElements()) 01456 return Sema::TDK_NonDeducedMismatch; 01457 01458 // Perform deduction on the element types. 01459 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01460 VectorParam->getElementType(), 01461 VectorArg->getElementType(), 01462 Info, Deduced, TDF); 01463 } 01464 01465 if (const DependentSizedExtVectorType *VectorArg 01466 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 01467 // We can't check the number of elements, since the argument has a 01468 // dependent number of elements. This can only occur during partial 01469 // ordering. 01470 01471 // Perform deduction on the element types. 01472 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01473 VectorParam->getElementType(), 01474 VectorArg->getElementType(), 01475 Info, Deduced, TDF); 01476 } 01477 01478 return Sema::TDK_NonDeducedMismatch; 01479 } 01480 01481 // (clang extension) 01482 // 01483 // T __attribute__(((ext_vector_type(N)))) 01484 case Type::DependentSizedExtVector: { 01485 const DependentSizedExtVectorType *VectorParam 01486 = cast<DependentSizedExtVectorType>(Param); 01487 01488 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) { 01489 // Perform deduction on the element types. 01490 if (Sema::TemplateDeductionResult Result 01491 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01492 VectorParam->getElementType(), 01493 VectorArg->getElementType(), 01494 Info, Deduced, TDF)) 01495 return Result; 01496 01497 // Perform deduction on the vector size, if we can. 01498 NonTypeTemplateParmDecl *NTTP 01499 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 01500 if (!NTTP) 01501 return Sema::TDK_Success; 01502 01503 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false); 01504 ArgSize = VectorArg->getNumElements(); 01505 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy, 01506 false, Info, Deduced); 01507 } 01508 01509 if (const DependentSizedExtVectorType *VectorArg 01510 = dyn_cast<DependentSizedExtVectorType>(Arg)) { 01511 // Perform deduction on the element types. 01512 if (Sema::TemplateDeductionResult Result 01513 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01514 VectorParam->getElementType(), 01515 VectorArg->getElementType(), 01516 Info, Deduced, TDF)) 01517 return Result; 01518 01519 // Perform deduction on the vector size, if we can. 01520 NonTypeTemplateParmDecl *NTTP 01521 = getDeducedParameterFromExpr(VectorParam->getSizeExpr()); 01522 if (!NTTP) 01523 return Sema::TDK_Success; 01524 01525 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(), 01526 Info, Deduced); 01527 } 01528 01529 return Sema::TDK_NonDeducedMismatch; 01530 } 01531 01532 case Type::TypeOfExpr: 01533 case Type::TypeOf: 01534 case Type::DependentName: 01535 case Type::UnresolvedUsing: 01536 case Type::Decltype: 01537 case Type::UnaryTransform: 01538 case Type::Auto: 01539 case Type::DependentTemplateSpecialization: 01540 case Type::PackExpansion: 01541 // No template argument deduction for these types 01542 return Sema::TDK_Success; 01543 } 01544 01545 llvm_unreachable("Invalid Type Class!"); 01546 } 01547 01548 static Sema::TemplateDeductionResult 01549 DeduceTemplateArguments(Sema &S, 01550 TemplateParameterList *TemplateParams, 01551 const TemplateArgument &Param, 01552 TemplateArgument Arg, 01553 TemplateDeductionInfo &Info, 01554 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 01555 // If the template argument is a pack expansion, perform template argument 01556 // deduction against the pattern of that expansion. This only occurs during 01557 // partial ordering. 01558 if (Arg.isPackExpansion()) 01559 Arg = Arg.getPackExpansionPattern(); 01560 01561 switch (Param.getKind()) { 01562 case TemplateArgument::Null: 01563 llvm_unreachable("Null template argument in parameter list"); 01564 01565 case TemplateArgument::Type: 01566 if (Arg.getKind() == TemplateArgument::Type) 01567 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 01568 Param.getAsType(), 01569 Arg.getAsType(), 01570 Info, Deduced, 0); 01571 Info.FirstArg = Param; 01572 Info.SecondArg = Arg; 01573 return Sema::TDK_NonDeducedMismatch; 01574 01575 case TemplateArgument::Template: 01576 if (Arg.getKind() == TemplateArgument::Template) 01577 return DeduceTemplateArguments(S, TemplateParams, 01578 Param.getAsTemplate(), 01579 Arg.getAsTemplate(), Info, Deduced); 01580 Info.FirstArg = Param; 01581 Info.SecondArg = Arg; 01582 return Sema::TDK_NonDeducedMismatch; 01583 01584 case TemplateArgument::TemplateExpansion: 01585 llvm_unreachable("caller should handle pack expansions"); 01586 01587 case TemplateArgument::Declaration: 01588 if (Arg.getKind() == TemplateArgument::Declaration && 01589 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl())) 01590 return Sema::TDK_Success; 01591 01592 Info.FirstArg = Param; 01593 Info.SecondArg = Arg; 01594 return Sema::TDK_NonDeducedMismatch; 01595 01596 case TemplateArgument::Integral: 01597 if (Arg.getKind() == TemplateArgument::Integral) { 01598 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral())) 01599 return Sema::TDK_Success; 01600 01601 Info.FirstArg = Param; 01602 Info.SecondArg = Arg; 01603 return Sema::TDK_NonDeducedMismatch; 01604 } 01605 01606 if (Arg.getKind() == TemplateArgument::Expression) { 01607 Info.FirstArg = Param; 01608 Info.SecondArg = Arg; 01609 return Sema::TDK_NonDeducedMismatch; 01610 } 01611 01612 Info.FirstArg = Param; 01613 Info.SecondArg = Arg; 01614 return Sema::TDK_NonDeducedMismatch; 01615 01616 case TemplateArgument::Expression: { 01617 if (NonTypeTemplateParmDecl *NTTP 01618 = getDeducedParameterFromExpr(Param.getAsExpr())) { 01619 if (Arg.getKind() == TemplateArgument::Integral) 01620 return DeduceNonTypeTemplateArgument(S, NTTP, 01621 *Arg.getAsIntegral(), 01622 Arg.getIntegralType(), 01623 /*ArrayBound=*/false, 01624 Info, Deduced); 01625 if (Arg.getKind() == TemplateArgument::Expression) 01626 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(), 01627 Info, Deduced); 01628 if (Arg.getKind() == TemplateArgument::Declaration) 01629 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(), 01630 Info, Deduced); 01631 01632 Info.FirstArg = Param; 01633 Info.SecondArg = Arg; 01634 return Sema::TDK_NonDeducedMismatch; 01635 } 01636 01637 // Can't deduce anything, but that's okay. 01638 return Sema::TDK_Success; 01639 } 01640 case TemplateArgument::Pack: 01641 llvm_unreachable("Argument packs should be expanded by the caller!"); 01642 } 01643 01644 llvm_unreachable("Invalid TemplateArgument Kind!"); 01645 } 01646 01647 /// \brief Determine whether there is a template argument to be used for 01648 /// deduction. 01649 /// 01650 /// This routine "expands" argument packs in-place, overriding its input 01651 /// parameters so that \c Args[ArgIdx] will be the available template argument. 01652 /// 01653 /// \returns true if there is another template argument (which will be at 01654 /// \c Args[ArgIdx]), false otherwise. 01655 static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args, 01656 unsigned &ArgIdx, 01657 unsigned &NumArgs) { 01658 if (ArgIdx == NumArgs) 01659 return false; 01660 01661 const TemplateArgument &Arg = Args[ArgIdx]; 01662 if (Arg.getKind() != TemplateArgument::Pack) 01663 return true; 01664 01665 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?"); 01666 Args = Arg.pack_begin(); 01667 NumArgs = Arg.pack_size(); 01668 ArgIdx = 0; 01669 return ArgIdx < NumArgs; 01670 } 01671 01672 /// \brief Determine whether the given set of template arguments has a pack 01673 /// expansion that is not the last template argument. 01674 static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args, 01675 unsigned NumArgs) { 01676 unsigned ArgIdx = 0; 01677 while (ArgIdx < NumArgs) { 01678 const TemplateArgument &Arg = Args[ArgIdx]; 01679 01680 // Unwrap argument packs. 01681 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) { 01682 Args = Arg.pack_begin(); 01683 NumArgs = Arg.pack_size(); 01684 ArgIdx = 0; 01685 continue; 01686 } 01687 01688 ++ArgIdx; 01689 if (ArgIdx == NumArgs) 01690 return false; 01691 01692 if (Arg.isPackExpansion()) 01693 return true; 01694 } 01695 01696 return false; 01697 } 01698 01699 static Sema::TemplateDeductionResult 01700 DeduceTemplateArguments(Sema &S, 01701 TemplateParameterList *TemplateParams, 01702 const TemplateArgument *Params, unsigned NumParams, 01703 const TemplateArgument *Args, unsigned NumArgs, 01704 TemplateDeductionInfo &Info, 01705 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 01706 bool NumberOfArgumentsMustMatch) { 01707 // C++0x [temp.deduct.type]p9: 01708 // If the template argument list of P contains a pack expansion that is not 01709 // the last template argument, the entire template argument list is a 01710 // non-deduced context. 01711 if (hasPackExpansionBeforeEnd(Params, NumParams)) 01712 return Sema::TDK_Success; 01713 01714 // C++0x [temp.deduct.type]p9: 01715 // If P has a form that contains <T> or <i>, then each argument Pi of the 01716 // respective template argument list P is compared with the corresponding 01717 // argument Ai of the corresponding template argument list of A. 01718 unsigned ArgIdx = 0, ParamIdx = 0; 01719 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams); 01720 ++ParamIdx) { 01721 if (!Params[ParamIdx].isPackExpansion()) { 01722 // The simple case: deduce template arguments by matching Pi and Ai. 01723 01724 // Check whether we have enough arguments. 01725 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) 01726 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch 01727 : Sema::TDK_Success; 01728 01729 if (Args[ArgIdx].isPackExpansion()) { 01730 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here, 01731 // but applied to pack expansions that are template arguments. 01732 return Sema::TDK_NonDeducedMismatch; 01733 } 01734 01735 // Perform deduction for this Pi/Ai pair. 01736 if (Sema::TemplateDeductionResult Result 01737 = DeduceTemplateArguments(S, TemplateParams, 01738 Params[ParamIdx], Args[ArgIdx], 01739 Info, Deduced)) 01740 return Result; 01741 01742 // Move to the next argument. 01743 ++ArgIdx; 01744 continue; 01745 } 01746 01747 // The parameter is a pack expansion. 01748 01749 // C++0x [temp.deduct.type]p9: 01750 // If Pi is a pack expansion, then the pattern of Pi is compared with 01751 // each remaining argument in the template argument list of A. Each 01752 // comparison deduces template arguments for subsequent positions in the 01753 // template parameter packs expanded by Pi. 01754 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern(); 01755 01756 // Compute the set of template parameter indices that correspond to 01757 // parameter packs expanded by the pack expansion. 01758 SmallVector<unsigned, 2> PackIndices; 01759 { 01760 llvm::SmallBitVector SawIndices(TemplateParams->size()); 01761 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 01762 S.collectUnexpandedParameterPacks(Pattern, Unexpanded); 01763 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 01764 unsigned Depth, Index; 01765 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 01766 if (Depth == 0 && !SawIndices[Index]) { 01767 SawIndices[Index] = true; 01768 PackIndices.push_back(Index); 01769 } 01770 } 01771 } 01772 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?"); 01773 01774 // FIXME: If there are no remaining arguments, we can bail out early 01775 // and set any deduced parameter packs to an empty argument pack. 01776 // The latter part of this is a (minor) correctness issue. 01777 01778 // Save the deduced template arguments for each parameter pack expanded 01779 // by this pack expansion, then clear out the deduction. 01780 SmallVector<DeducedTemplateArgument, 2> 01781 SavedPacks(PackIndices.size()); 01782 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2> 01783 NewlyDeducedPacks(PackIndices.size()); 01784 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks, 01785 NewlyDeducedPacks); 01786 01787 // Keep track of the deduced template arguments for each parameter pack 01788 // expanded by this pack expansion (the outer index) and for each 01789 // template argument (the inner SmallVectors). 01790 bool HasAnyArguments = false; 01791 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) { 01792 HasAnyArguments = true; 01793 01794 // Deduce template arguments from the pattern. 01795 if (Sema::TemplateDeductionResult Result 01796 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx], 01797 Info, Deduced)) 01798 return Result; 01799 01800 // Capture the deduced template arguments for each parameter pack expanded 01801 // by this pack expansion, add them to the list of arguments we've deduced 01802 // for that pack, then clear out the deduced argument. 01803 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 01804 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]]; 01805 if (!DeducedArg.isNull()) { 01806 NewlyDeducedPacks[I].push_back(DeducedArg); 01807 DeducedArg = DeducedTemplateArgument(); 01808 } 01809 } 01810 01811 ++ArgIdx; 01812 } 01813 01814 // Build argument packs for each of the parameter packs expanded by this 01815 // pack expansion. 01816 if (Sema::TemplateDeductionResult Result 01817 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments, 01818 Deduced, PackIndices, SavedPacks, 01819 NewlyDeducedPacks, Info)) 01820 return Result; 01821 } 01822 01823 // If there is an argument remaining, then we had too many arguments. 01824 if (NumberOfArgumentsMustMatch && 01825 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) 01826 return Sema::TDK_NonDeducedMismatch; 01827 01828 return Sema::TDK_Success; 01829 } 01830 01831 static Sema::TemplateDeductionResult 01832 DeduceTemplateArguments(Sema &S, 01833 TemplateParameterList *TemplateParams, 01834 const TemplateArgumentList &ParamList, 01835 const TemplateArgumentList &ArgList, 01836 TemplateDeductionInfo &Info, 01837 SmallVectorImpl<DeducedTemplateArgument> &Deduced) { 01838 return DeduceTemplateArguments(S, TemplateParams, 01839 ParamList.data(), ParamList.size(), 01840 ArgList.data(), ArgList.size(), 01841 Info, Deduced); 01842 } 01843 01844 /// \brief Determine whether two template arguments are the same. 01845 static bool isSameTemplateArg(ASTContext &Context, 01846 const TemplateArgument &X, 01847 const TemplateArgument &Y) { 01848 if (X.getKind() != Y.getKind()) 01849 return false; 01850 01851 switch (X.getKind()) { 01852 case TemplateArgument::Null: 01853 llvm_unreachable("Comparing NULL template argument"); 01854 01855 case TemplateArgument::Type: 01856 return Context.getCanonicalType(X.getAsType()) == 01857 Context.getCanonicalType(Y.getAsType()); 01858 01859 case TemplateArgument::Declaration: 01860 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()); 01861 01862 case TemplateArgument::Template: 01863 case TemplateArgument::TemplateExpansion: 01864 return Context.getCanonicalTemplateName( 01865 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() == 01866 Context.getCanonicalTemplateName( 01867 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer(); 01868 01869 case TemplateArgument::Integral: 01870 return *X.getAsIntegral() == *Y.getAsIntegral(); 01871 01872 case TemplateArgument::Expression: { 01873 llvm::FoldingSetNodeID XID, YID; 01874 X.getAsExpr()->Profile(XID, Context, true); 01875 Y.getAsExpr()->Profile(YID, Context, true); 01876 return XID == YID; 01877 } 01878 01879 case TemplateArgument::Pack: 01880 if (X.pack_size() != Y.pack_size()) 01881 return false; 01882 01883 for (TemplateArgument::pack_iterator XP = X.pack_begin(), 01884 XPEnd = X.pack_end(), 01885 YP = Y.pack_begin(); 01886 XP != XPEnd; ++XP, ++YP) 01887 if (!isSameTemplateArg(Context, *XP, *YP)) 01888 return false; 01889 01890 return true; 01891 } 01892 01893 llvm_unreachable("Invalid TemplateArgument Kind!"); 01894 } 01895 01896 /// \brief Allocate a TemplateArgumentLoc where all locations have 01897 /// been initialized to the given location. 01898 /// 01899 /// \param S The semantic analysis object. 01900 /// 01901 /// \param The template argument we are producing template argument 01902 /// location information for. 01903 /// 01904 /// \param NTTPType For a declaration template argument, the type of 01905 /// the non-type template parameter that corresponds to this template 01906 /// argument. 01907 /// 01908 /// \param Loc The source location to use for the resulting template 01909 /// argument. 01910 static TemplateArgumentLoc 01911 getTrivialTemplateArgumentLoc(Sema &S, 01912 const TemplateArgument &Arg, 01913 QualType NTTPType, 01914 SourceLocation Loc) { 01915 switch (Arg.getKind()) { 01916 case TemplateArgument::Null: 01917 llvm_unreachable("Can't get a NULL template argument here"); 01918 01919 case TemplateArgument::Type: 01920 return TemplateArgumentLoc(Arg, 01921 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc)); 01922 01923 case TemplateArgument::Declaration: { 01924 Expr *E 01925 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc) 01926 .takeAs<Expr>(); 01927 return TemplateArgumentLoc(TemplateArgument(E), E); 01928 } 01929 01930 case TemplateArgument::Integral: { 01931 Expr *E 01932 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>(); 01933 return TemplateArgumentLoc(TemplateArgument(E), E); 01934 } 01935 01936 case TemplateArgument::Template: 01937 case TemplateArgument::TemplateExpansion: { 01938 NestedNameSpecifierLocBuilder Builder; 01939 TemplateName Template = Arg.getAsTemplate(); 01940 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) 01941 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc); 01942 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 01943 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc); 01944 01945 if (Arg.getKind() == TemplateArgument::Template) 01946 return TemplateArgumentLoc(Arg, 01947 Builder.getWithLocInContext(S.Context), 01948 Loc); 01949 01950 01951 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context), 01952 Loc, Loc); 01953 } 01954 01955 case TemplateArgument::Expression: 01956 return TemplateArgumentLoc(Arg, Arg.getAsExpr()); 01957 01958 case TemplateArgument::Pack: 01959 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo()); 01960 } 01961 01962 llvm_unreachable("Invalid TemplateArgument Kind!"); 01963 } 01964 01965 01966 /// \brief Convert the given deduced template argument and add it to the set of 01967 /// fully-converted template arguments. 01968 static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, 01969 DeducedTemplateArgument Arg, 01970 NamedDecl *Template, 01971 QualType NTTPType, 01972 unsigned ArgumentPackIndex, 01973 TemplateDeductionInfo &Info, 01974 bool InFunctionTemplate, 01975 SmallVectorImpl<TemplateArgument> &Output) { 01976 if (Arg.getKind() == TemplateArgument::Pack) { 01977 // This is a template argument pack, so check each of its arguments against 01978 // the template parameter. 01979 SmallVector<TemplateArgument, 2> PackedArgsBuilder; 01980 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(), 01981 PAEnd = Arg.pack_end(); 01982 PA != PAEnd; ++PA) { 01983 // When converting the deduced template argument, append it to the 01984 // general output list. We need to do this so that the template argument 01985 // checking logic has all of the prior template arguments available. 01986 DeducedTemplateArgument InnerArg(*PA); 01987 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound()); 01988 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template, 01989 NTTPType, PackedArgsBuilder.size(), 01990 Info, InFunctionTemplate, Output)) 01991 return true; 01992 01993 // Move the converted template argument into our argument pack. 01994 PackedArgsBuilder.push_back(Output.back()); 01995 Output.pop_back(); 01996 } 01997 01998 // Create the resulting argument pack. 01999 Output.push_back(TemplateArgument::CreatePackCopy(S.Context, 02000 PackedArgsBuilder.data(), 02001 PackedArgsBuilder.size())); 02002 return false; 02003 } 02004 02005 // Convert the deduced template argument into a template 02006 // argument that we can check, almost as if the user had written 02007 // the template argument explicitly. 02008 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType, 02009 Info.getLocation()); 02010 02011 // Check the template argument, converting it as necessary. 02012 return S.CheckTemplateArgument(Param, ArgLoc, 02013 Template, 02014 Template->getLocation(), 02015 Template->getSourceRange().getEnd(), 02016 ArgumentPackIndex, 02017 Output, 02018 InFunctionTemplate 02019 ? (Arg.wasDeducedFromArrayBound() 02020 ? Sema::CTAK_DeducedFromArrayBound 02021 : Sema::CTAK_Deduced) 02022 : Sema::CTAK_Specified); 02023 } 02024 02025 /// Complete template argument deduction for a class template partial 02026 /// specialization. 02027 static Sema::TemplateDeductionResult 02028 FinishTemplateArgumentDeduction(Sema &S, 02029 ClassTemplatePartialSpecializationDecl *Partial, 02030 const TemplateArgumentList &TemplateArgs, 02031 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02032 TemplateDeductionInfo &Info) { 02033 // Unevaluated SFINAE context. 02034 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 02035 Sema::SFINAETrap Trap(S); 02036 02037 Sema::ContextRAII SavedContext(S, Partial); 02038 02039 // C++ [temp.deduct.type]p2: 02040 // [...] or if any template argument remains neither deduced nor 02041 // explicitly specified, template argument deduction fails. 02042 SmallVector<TemplateArgument, 4> Builder; 02043 TemplateParameterList *PartialParams = Partial->getTemplateParameters(); 02044 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) { 02045 NamedDecl *Param = PartialParams->getParam(I); 02046 if (Deduced[I].isNull()) { 02047 Info.Param = makeTemplateParameter(Param); 02048 return Sema::TDK_Incomplete; 02049 } 02050 02051 // We have deduced this argument, so it still needs to be 02052 // checked and converted. 02053 02054 // First, for a non-type template parameter type that is 02055 // initialized by a declaration, we need the type of the 02056 // corresponding non-type template parameter. 02057 QualType NTTPType; 02058 if (NonTypeTemplateParmDecl *NTTP 02059 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 02060 NTTPType = NTTP->getType(); 02061 if (NTTPType->isDependentType()) { 02062 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 02063 Builder.data(), Builder.size()); 02064 NTTPType = S.SubstType(NTTPType, 02065 MultiLevelTemplateArgumentList(TemplateArgs), 02066 NTTP->getLocation(), 02067 NTTP->getDeclName()); 02068 if (NTTPType.isNull()) { 02069 Info.Param = makeTemplateParameter(Param); 02070 // FIXME: These template arguments are temporary. Free them! 02071 Info.reset(TemplateArgumentList::CreateCopy(S.Context, 02072 Builder.data(), 02073 Builder.size())); 02074 return Sema::TDK_SubstitutionFailure; 02075 } 02076 } 02077 } 02078 02079 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], 02080 Partial, NTTPType, 0, Info, false, 02081 Builder)) { 02082 Info.Param = makeTemplateParameter(Param); 02083 // FIXME: These template arguments are temporary. Free them! 02084 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 02085 Builder.size())); 02086 return Sema::TDK_SubstitutionFailure; 02087 } 02088 } 02089 02090 // Form the template argument list from the deduced template arguments. 02091 TemplateArgumentList *DeducedArgumentList 02092 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(), 02093 Builder.size()); 02094 02095 Info.reset(DeducedArgumentList); 02096 02097 // Substitute the deduced template arguments into the template 02098 // arguments of the class template partial specialization, and 02099 // verify that the instantiated template arguments are both valid 02100 // and are equivalent to the template arguments originally provided 02101 // to the class template. 02102 LocalInstantiationScope InstScope(S); 02103 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate(); 02104 const TemplateArgumentLoc *PartialTemplateArgs 02105 = Partial->getTemplateArgsAsWritten(); 02106 02107 // Note that we don't provide the langle and rangle locations. 02108 TemplateArgumentListInfo InstArgs; 02109 02110 if (S.Subst(PartialTemplateArgs, 02111 Partial->getNumTemplateArgsAsWritten(), 02112 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) { 02113 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx; 02114 if (ParamIdx >= Partial->getTemplateParameters()->size()) 02115 ParamIdx = Partial->getTemplateParameters()->size() - 1; 02116 02117 Decl *Param 02118 = const_cast<NamedDecl *>( 02119 Partial->getTemplateParameters()->getParam(ParamIdx)); 02120 Info.Param = makeTemplateParameter(Param); 02121 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument(); 02122 return Sema::TDK_SubstitutionFailure; 02123 } 02124 02125 SmallVector<TemplateArgument, 4> ConvertedInstArgs; 02126 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(), 02127 InstArgs, false, ConvertedInstArgs)) 02128 return Sema::TDK_SubstitutionFailure; 02129 02130 TemplateParameterList *TemplateParams 02131 = ClassTemplate->getTemplateParameters(); 02132 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) { 02133 TemplateArgument InstArg = ConvertedInstArgs.data()[I]; 02134 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) { 02135 Info.Param = makeTemplateParameter(TemplateParams->getParam(I)); 02136 Info.FirstArg = TemplateArgs[I]; 02137 Info.SecondArg = InstArg; 02138 return Sema::TDK_NonDeducedMismatch; 02139 } 02140 } 02141 02142 if (Trap.hasErrorOccurred()) 02143 return Sema::TDK_SubstitutionFailure; 02144 02145 return Sema::TDK_Success; 02146 } 02147 02148 /// \brief Perform template argument deduction to determine whether 02149 /// the given template arguments match the given class template 02150 /// partial specialization per C++ [temp.class.spec.match]. 02151 Sema::TemplateDeductionResult 02152 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 02153 const TemplateArgumentList &TemplateArgs, 02154 TemplateDeductionInfo &Info) { 02155 // C++ [temp.class.spec.match]p2: 02156 // A partial specialization matches a given actual template 02157 // argument list if the template arguments of the partial 02158 // specialization can be deduced from the actual template argument 02159 // list (14.8.2). 02160 02161 // Unevaluated SFINAE context. 02162 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02163 SFINAETrap Trap(*this); 02164 02165 SmallVector<DeducedTemplateArgument, 4> Deduced; 02166 Deduced.resize(Partial->getTemplateParameters()->size()); 02167 if (TemplateDeductionResult Result 02168 = ::DeduceTemplateArguments(*this, 02169 Partial->getTemplateParameters(), 02170 Partial->getTemplateArgs(), 02171 TemplateArgs, Info, Deduced)) 02172 return Result; 02173 02174 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial, 02175 Deduced.data(), Deduced.size(), Info); 02176 if (Inst) 02177 return TDK_InstantiationDepth; 02178 02179 if (Trap.hasErrorOccurred()) 02180 return Sema::TDK_SubstitutionFailure; 02181 02182 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs, 02183 Deduced, Info); 02184 } 02185 02186 /// \brief Determine whether the given type T is a simple-template-id type. 02187 static bool isSimpleTemplateIdType(QualType T) { 02188 if (const TemplateSpecializationType *Spec 02189 = T->getAs<TemplateSpecializationType>()) 02190 return Spec->getTemplateName().getAsTemplateDecl() != 0; 02191 02192 return false; 02193 } 02194 02195 /// \brief Substitute the explicitly-provided template arguments into the 02196 /// given function template according to C++ [temp.arg.explicit]. 02197 /// 02198 /// \param FunctionTemplate the function template into which the explicit 02199 /// template arguments will be substituted. 02200 /// 02201 /// \param ExplicitTemplateArguments the explicitly-specified template 02202 /// arguments. 02203 /// 02204 /// \param Deduced the deduced template arguments, which will be populated 02205 /// with the converted and checked explicit template arguments. 02206 /// 02207 /// \param ParamTypes will be populated with the instantiated function 02208 /// parameters. 02209 /// 02210 /// \param FunctionType if non-NULL, the result type of the function template 02211 /// will also be instantiated and the pointed-to value will be updated with 02212 /// the instantiated function type. 02213 /// 02214 /// \param Info if substitution fails for any reason, this object will be 02215 /// populated with more information about the failure. 02216 /// 02217 /// \returns TDK_Success if substitution was successful, or some failure 02218 /// condition. 02219 Sema::TemplateDeductionResult 02220 Sema::SubstituteExplicitTemplateArguments( 02221 FunctionTemplateDecl *FunctionTemplate, 02222 TemplateArgumentListInfo &ExplicitTemplateArgs, 02223 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02224 SmallVectorImpl<QualType> &ParamTypes, 02225 QualType *FunctionType, 02226 TemplateDeductionInfo &Info) { 02227 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 02228 TemplateParameterList *TemplateParams 02229 = FunctionTemplate->getTemplateParameters(); 02230 02231 if (ExplicitTemplateArgs.size() == 0) { 02232 // No arguments to substitute; just copy over the parameter types and 02233 // fill in the function type. 02234 for (FunctionDecl::param_iterator P = Function->param_begin(), 02235 PEnd = Function->param_end(); 02236 P != PEnd; 02237 ++P) 02238 ParamTypes.push_back((*P)->getType()); 02239 02240 if (FunctionType) 02241 *FunctionType = Function->getType(); 02242 return TDK_Success; 02243 } 02244 02245 // Unevaluated SFINAE context. 02246 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02247 SFINAETrap Trap(*this); 02248 02249 // C++ [temp.arg.explicit]p3: 02250 // Template arguments that are present shall be specified in the 02251 // declaration order of their corresponding template-parameters. The 02252 // template argument list shall not specify more template-arguments than 02253 // there are corresponding template-parameters. 02254 SmallVector<TemplateArgument, 4> Builder; 02255 02256 // Enter a new template instantiation context where we check the 02257 // explicitly-specified template arguments against this function template, 02258 // and then substitute them into the function parameter types. 02259 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(), 02260 FunctionTemplate, Deduced.data(), Deduced.size(), 02261 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution, 02262 Info); 02263 if (Inst) 02264 return TDK_InstantiationDepth; 02265 02266 if (CheckTemplateArgumentList(FunctionTemplate, 02267 SourceLocation(), 02268 ExplicitTemplateArgs, 02269 true, 02270 Builder) || Trap.hasErrorOccurred()) { 02271 unsigned Index = Builder.size(); 02272 if (Index >= TemplateParams->size()) 02273 Index = TemplateParams->size() - 1; 02274 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index)); 02275 return TDK_InvalidExplicitArguments; 02276 } 02277 02278 // Form the template argument list from the explicitly-specified 02279 // template arguments. 02280 TemplateArgumentList *ExplicitArgumentList 02281 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 02282 Info.reset(ExplicitArgumentList); 02283 02284 // Template argument deduction and the final substitution should be 02285 // done in the context of the templated declaration. Explicit 02286 // argument substitution, on the other hand, needs to happen in the 02287 // calling context. 02288 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 02289 02290 // If we deduced template arguments for a template parameter pack, 02291 // note that the template argument pack is partially substituted and record 02292 // the explicit template arguments. They'll be used as part of deduction 02293 // for this template parameter pack. 02294 for (unsigned I = 0, N = Builder.size(); I != N; ++I) { 02295 const TemplateArgument &Arg = Builder[I]; 02296 if (Arg.getKind() == TemplateArgument::Pack) { 02297 CurrentInstantiationScope->SetPartiallySubstitutedPack( 02298 TemplateParams->getParam(I), 02299 Arg.pack_begin(), 02300 Arg.pack_size()); 02301 break; 02302 } 02303 } 02304 02305 const FunctionProtoType *Proto 02306 = Function->getType()->getAs<FunctionProtoType>(); 02307 assert(Proto && "Function template does not have a prototype?"); 02308 02309 // Instantiate the types of each of the function parameters given the 02310 // explicitly-specified template arguments. If the function has a trailing 02311 // return type, substitute it after the arguments to ensure we substitute 02312 // in lexical order. 02313 if (Proto->hasTrailingReturn()) { 02314 if (SubstParmTypes(Function->getLocation(), 02315 Function->param_begin(), Function->getNumParams(), 02316 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 02317 ParamTypes)) 02318 return TDK_SubstitutionFailure; 02319 } 02320 02321 // Instantiate the return type. 02322 // FIXME: exception-specifications? 02323 QualType ResultType; 02324 { 02325 // C++11 [expr.prim.general]p3: 02326 // If a declaration declares a member function or member function 02327 // template of a class X, the expression this is a prvalue of type 02328 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 02329 // and the end of the function-definition, member-declarator, or 02330 // declarator. 02331 unsigned ThisTypeQuals = 0; 02332 CXXRecordDecl *ThisContext = 0; 02333 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 02334 ThisContext = Method->getParent(); 02335 ThisTypeQuals = Method->getTypeQualifiers(); 02336 } 02337 02338 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals, 02339 getLangOpts().CPlusPlus0x); 02340 02341 ResultType = SubstType(Proto->getResultType(), 02342 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 02343 Function->getTypeSpecStartLoc(), 02344 Function->getDeclName()); 02345 if (ResultType.isNull() || Trap.hasErrorOccurred()) 02346 return TDK_SubstitutionFailure; 02347 } 02348 02349 // Instantiate the types of each of the function parameters given the 02350 // explicitly-specified template arguments if we didn't do so earlier. 02351 if (!Proto->hasTrailingReturn() && 02352 SubstParmTypes(Function->getLocation(), 02353 Function->param_begin(), Function->getNumParams(), 02354 MultiLevelTemplateArgumentList(*ExplicitArgumentList), 02355 ParamTypes)) 02356 return TDK_SubstitutionFailure; 02357 02358 if (FunctionType) { 02359 *FunctionType = BuildFunctionType(ResultType, 02360 ParamTypes.data(), ParamTypes.size(), 02361 Proto->isVariadic(), 02362 Proto->hasTrailingReturn(), 02363 Proto->getTypeQuals(), 02364 Proto->getRefQualifier(), 02365 Function->getLocation(), 02366 Function->getDeclName(), 02367 Proto->getExtInfo()); 02368 if (FunctionType->isNull() || Trap.hasErrorOccurred()) 02369 return TDK_SubstitutionFailure; 02370 } 02371 02372 // C++ [temp.arg.explicit]p2: 02373 // Trailing template arguments that can be deduced (14.8.2) may be 02374 // omitted from the list of explicit template-arguments. If all of the 02375 // template arguments can be deduced, they may all be omitted; in this 02376 // case, the empty template argument list <> itself may also be omitted. 02377 // 02378 // Take all of the explicitly-specified arguments and put them into 02379 // the set of deduced template arguments. Explicitly-specified 02380 // parameter packs, however, will be set to NULL since the deduction 02381 // mechanisms handle explicitly-specified argument packs directly. 02382 Deduced.reserve(TemplateParams->size()); 02383 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) { 02384 const TemplateArgument &Arg = ExplicitArgumentList->get(I); 02385 if (Arg.getKind() == TemplateArgument::Pack) 02386 Deduced.push_back(DeducedTemplateArgument()); 02387 else 02388 Deduced.push_back(Arg); 02389 } 02390 02391 return TDK_Success; 02392 } 02393 02394 /// \brief Check whether the deduced argument type for a call to a function 02395 /// template matches the actual argument type per C++ [temp.deduct.call]p4. 02396 static bool 02397 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg, 02398 QualType DeducedA) { 02399 ASTContext &Context = S.Context; 02400 02401 QualType A = OriginalArg.OriginalArgType; 02402 QualType OriginalParamType = OriginalArg.OriginalParamType; 02403 02404 // Check for type equality (top-level cv-qualifiers are ignored). 02405 if (Context.hasSameUnqualifiedType(A, DeducedA)) 02406 return false; 02407 02408 // Strip off references on the argument types; they aren't needed for 02409 // the following checks. 02410 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>()) 02411 DeducedA = DeducedARef->getPointeeType(); 02412 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 02413 A = ARef->getPointeeType(); 02414 02415 // C++ [temp.deduct.call]p4: 02416 // [...] However, there are three cases that allow a difference: 02417 // - If the original P is a reference type, the deduced A (i.e., the 02418 // type referred to by the reference) can be more cv-qualified than 02419 // the transformed A. 02420 if (const ReferenceType *OriginalParamRef 02421 = OriginalParamType->getAs<ReferenceType>()) { 02422 // We don't want to keep the reference around any more. 02423 OriginalParamType = OriginalParamRef->getPointeeType(); 02424 02425 Qualifiers AQuals = A.getQualifiers(); 02426 Qualifiers DeducedAQuals = DeducedA.getQualifiers(); 02427 if (AQuals == DeducedAQuals) { 02428 // Qualifiers match; there's nothing to do. 02429 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) { 02430 return true; 02431 } else { 02432 // Qualifiers are compatible, so have the argument type adopt the 02433 // deduced argument type's qualifiers as if we had performed the 02434 // qualification conversion. 02435 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals); 02436 } 02437 } 02438 02439 // - The transformed A can be another pointer or pointer to member 02440 // type that can be converted to the deduced A via a qualification 02441 // conversion. 02442 // 02443 // Also allow conversions which merely strip [[noreturn]] from function types 02444 // (recursively) as an extension. 02445 // FIXME: Currently, this doesn't place nicely with qualfication conversions. 02446 bool ObjCLifetimeConversion = false; 02447 QualType ResultTy; 02448 if ((A->isAnyPointerType() || A->isMemberPointerType()) && 02449 (S.IsQualificationConversion(A, DeducedA, false, 02450 ObjCLifetimeConversion) || 02451 S.IsNoReturnConversion(A, DeducedA, ResultTy))) 02452 return false; 02453 02454 02455 // - If P is a class and P has the form simple-template-id, then the 02456 // transformed A can be a derived class of the deduced A. [...] 02457 // [...] Likewise, if P is a pointer to a class of the form 02458 // simple-template-id, the transformed A can be a pointer to a 02459 // derived class pointed to by the deduced A. 02460 if (const PointerType *OriginalParamPtr 02461 = OriginalParamType->getAs<PointerType>()) { 02462 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) { 02463 if (const PointerType *APtr = A->getAs<PointerType>()) { 02464 if (A->getPointeeType()->isRecordType()) { 02465 OriginalParamType = OriginalParamPtr->getPointeeType(); 02466 DeducedA = DeducedAPtr->getPointeeType(); 02467 A = APtr->getPointeeType(); 02468 } 02469 } 02470 } 02471 } 02472 02473 if (Context.hasSameUnqualifiedType(A, DeducedA)) 02474 return false; 02475 02476 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) && 02477 S.IsDerivedFrom(A, DeducedA)) 02478 return false; 02479 02480 return true; 02481 } 02482 02483 /// \brief Finish template argument deduction for a function template, 02484 /// checking the deduced template arguments for completeness and forming 02485 /// the function template specialization. 02486 /// 02487 /// \param OriginalCallArgs If non-NULL, the original call arguments against 02488 /// which the deduced argument types should be compared. 02489 Sema::TemplateDeductionResult 02490 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 02491 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02492 unsigned NumExplicitlySpecified, 02493 FunctionDecl *&Specialization, 02494 TemplateDeductionInfo &Info, 02495 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) { 02496 TemplateParameterList *TemplateParams 02497 = FunctionTemplate->getTemplateParameters(); 02498 02499 // Unevaluated SFINAE context. 02500 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 02501 SFINAETrap Trap(*this); 02502 02503 // Enter a new template instantiation context while we instantiate the 02504 // actual function declaration. 02505 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(), 02506 FunctionTemplate, Deduced.data(), Deduced.size(), 02507 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution, 02508 Info); 02509 if (Inst) 02510 return TDK_InstantiationDepth; 02511 02512 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl()); 02513 02514 // C++ [temp.deduct.type]p2: 02515 // [...] or if any template argument remains neither deduced nor 02516 // explicitly specified, template argument deduction fails. 02517 SmallVector<TemplateArgument, 4> Builder; 02518 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 02519 NamedDecl *Param = TemplateParams->getParam(I); 02520 02521 if (!Deduced[I].isNull()) { 02522 if (I < NumExplicitlySpecified) { 02523 // We have already fully type-checked and converted this 02524 // argument, because it was explicitly-specified. Just record the 02525 // presence of this argument. 02526 Builder.push_back(Deduced[I]); 02527 continue; 02528 } 02529 02530 // We have deduced this argument, so it still needs to be 02531 // checked and converted. 02532 02533 // First, for a non-type template parameter type that is 02534 // initialized by a declaration, we need the type of the 02535 // corresponding non-type template parameter. 02536 QualType NTTPType; 02537 if (NonTypeTemplateParmDecl *NTTP 02538 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 02539 NTTPType = NTTP->getType(); 02540 if (NTTPType->isDependentType()) { 02541 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 02542 Builder.data(), Builder.size()); 02543 NTTPType = SubstType(NTTPType, 02544 MultiLevelTemplateArgumentList(TemplateArgs), 02545 NTTP->getLocation(), 02546 NTTP->getDeclName()); 02547 if (NTTPType.isNull()) { 02548 Info.Param = makeTemplateParameter(Param); 02549 // FIXME: These template arguments are temporary. Free them! 02550 Info.reset(TemplateArgumentList::CreateCopy(Context, 02551 Builder.data(), 02552 Builder.size())); 02553 return TDK_SubstitutionFailure; 02554 } 02555 } 02556 } 02557 02558 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I], 02559 FunctionTemplate, NTTPType, 0, Info, 02560 true, Builder)) { 02561 Info.Param = makeTemplateParameter(Param); 02562 // FIXME: These template arguments are temporary. Free them! 02563 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 02564 Builder.size())); 02565 return TDK_SubstitutionFailure; 02566 } 02567 02568 continue; 02569 } 02570 02571 // C++0x [temp.arg.explicit]p3: 02572 // A trailing template parameter pack (14.5.3) not otherwise deduced will 02573 // be deduced to an empty sequence of template arguments. 02574 // FIXME: Where did the word "trailing" come from? 02575 if (Param->isTemplateParameterPack()) { 02576 // We may have had explicitly-specified template arguments for this 02577 // template parameter pack. If so, our empty deduction extends the 02578 // explicitly-specified set (C++0x [temp.arg.explicit]p9). 02579 const TemplateArgument *ExplicitArgs; 02580 unsigned NumExplicitArgs; 02581 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs, 02582 &NumExplicitArgs) 02583 == Param) 02584 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs)); 02585 else 02586 Builder.push_back(TemplateArgument(0, 0)); 02587 02588 continue; 02589 } 02590 02591 // Substitute into the default template argument, if available. 02592 TemplateArgumentLoc DefArg 02593 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate, 02594 FunctionTemplate->getLocation(), 02595 FunctionTemplate->getSourceRange().getEnd(), 02596 Param, 02597 Builder); 02598 02599 // If there was no default argument, deduction is incomplete. 02600 if (DefArg.getArgument().isNull()) { 02601 Info.Param = makeTemplateParameter( 02602 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 02603 return TDK_Incomplete; 02604 } 02605 02606 // Check whether we can actually use the default argument. 02607 if (CheckTemplateArgument(Param, DefArg, 02608 FunctionTemplate, 02609 FunctionTemplate->getLocation(), 02610 FunctionTemplate->getSourceRange().getEnd(), 02611 0, Builder, 02612 CTAK_Specified)) { 02613 Info.Param = makeTemplateParameter( 02614 const_cast<NamedDecl *>(TemplateParams->getParam(I))); 02615 // FIXME: These template arguments are temporary. Free them! 02616 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(), 02617 Builder.size())); 02618 return TDK_SubstitutionFailure; 02619 } 02620 02621 // If we get here, we successfully used the default template argument. 02622 } 02623 02624 // Form the template argument list from the deduced template arguments. 02625 TemplateArgumentList *DeducedArgumentList 02626 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size()); 02627 Info.reset(DeducedArgumentList); 02628 02629 // Substitute the deduced template arguments into the function template 02630 // declaration to produce the function template specialization. 02631 DeclContext *Owner = FunctionTemplate->getDeclContext(); 02632 if (FunctionTemplate->getFriendObjectKind()) 02633 Owner = FunctionTemplate->getLexicalDeclContext(); 02634 Specialization = cast_or_null<FunctionDecl>( 02635 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, 02636 MultiLevelTemplateArgumentList(*DeducedArgumentList))); 02637 if (!Specialization || Specialization->isInvalidDecl()) 02638 return TDK_SubstitutionFailure; 02639 02640 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() == 02641 FunctionTemplate->getCanonicalDecl()); 02642 02643 // If the template argument list is owned by the function template 02644 // specialization, release it. 02645 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList && 02646 !Trap.hasErrorOccurred()) 02647 Info.take(); 02648 02649 // There may have been an error that did not prevent us from constructing a 02650 // declaration. Mark the declaration invalid and return with a substitution 02651 // failure. 02652 if (Trap.hasErrorOccurred()) { 02653 Specialization->setInvalidDecl(true); 02654 return TDK_SubstitutionFailure; 02655 } 02656 02657 if (OriginalCallArgs) { 02658 // C++ [temp.deduct.call]p4: 02659 // In general, the deduction process attempts to find template argument 02660 // values that will make the deduced A identical to A (after the type A 02661 // is transformed as described above). [...] 02662 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) { 02663 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I]; 02664 unsigned ParamIdx = OriginalArg.ArgIdx; 02665 02666 if (ParamIdx >= Specialization->getNumParams()) 02667 continue; 02668 02669 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType(); 02670 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) 02671 return Sema::TDK_SubstitutionFailure; 02672 } 02673 } 02674 02675 // If we suppressed any diagnostics while performing template argument 02676 // deduction, and if we haven't already instantiated this declaration, 02677 // keep track of these diagnostics. They'll be emitted if this specialization 02678 // is actually used. 02679 if (Info.diag_begin() != Info.diag_end()) { 02680 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 02681 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl()); 02682 if (Pos == SuppressedDiagnostics.end()) 02683 SuppressedDiagnostics[Specialization->getCanonicalDecl()] 02684 .append(Info.diag_begin(), Info.diag_end()); 02685 } 02686 02687 return TDK_Success; 02688 } 02689 02690 /// Gets the type of a function for template-argument-deducton 02691 /// purposes when it's considered as part of an overload set. 02692 static QualType GetTypeOfFunction(ASTContext &Context, 02693 const OverloadExpr::FindResult &R, 02694 FunctionDecl *Fn) { 02695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 02696 if (Method->isInstance()) { 02697 // An instance method that's referenced in a form that doesn't 02698 // look like a member pointer is just invalid. 02699 if (!R.HasFormOfMemberPointer) return QualType(); 02700 02701 return Context.getMemberPointerType(Fn->getType(), 02702 Context.getTypeDeclType(Method->getParent()).getTypePtr()); 02703 } 02704 02705 if (!R.IsAddressOfOperand) return Fn->getType(); 02706 return Context.getPointerType(Fn->getType()); 02707 } 02708 02709 /// Apply the deduction rules for overload sets. 02710 /// 02711 /// \return the null type if this argument should be treated as an 02712 /// undeduced context 02713 static QualType 02714 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, 02715 Expr *Arg, QualType ParamType, 02716 bool ParamWasReference) { 02717 02718 OverloadExpr::FindResult R = OverloadExpr::find(Arg); 02719 02720 OverloadExpr *Ovl = R.Expression; 02721 02722 // C++0x [temp.deduct.call]p4 02723 unsigned TDF = 0; 02724 if (ParamWasReference) 02725 TDF |= TDF_ParamWithReferenceType; 02726 if (R.IsAddressOfOperand) 02727 TDF |= TDF_IgnoreQualifiers; 02728 02729 // C++0x [temp.deduct.call]p6: 02730 // When P is a function type, pointer to function type, or pointer 02731 // to member function type: 02732 02733 if (!ParamType->isFunctionType() && 02734 !ParamType->isFunctionPointerType() && 02735 !ParamType->isMemberFunctionPointerType()) { 02736 if (Ovl->hasExplicitTemplateArgs()) { 02737 // But we can still look for an explicit specialization. 02738 if (FunctionDecl *ExplicitSpec 02739 = S.ResolveSingleFunctionTemplateSpecialization(Ovl)) 02740 return GetTypeOfFunction(S.Context, R, ExplicitSpec); 02741 } 02742 02743 return QualType(); 02744 } 02745 02746 // Gather the explicit template arguments, if any. 02747 TemplateArgumentListInfo ExplicitTemplateArgs; 02748 if (Ovl->hasExplicitTemplateArgs()) 02749 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 02750 QualType Match; 02751 for (UnresolvedSetIterator I = Ovl->decls_begin(), 02752 E = Ovl->decls_end(); I != E; ++I) { 02753 NamedDecl *D = (*I)->getUnderlyingDecl(); 02754 02755 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) { 02756 // - If the argument is an overload set containing one or more 02757 // function templates, the parameter is treated as a 02758 // non-deduced context. 02759 if (!Ovl->hasExplicitTemplateArgs()) 02760 return QualType(); 02761 02762 // Otherwise, see if we can resolve a function type 02763 FunctionDecl *Specialization = 0; 02764 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc()); 02765 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs, 02766 Specialization, Info)) 02767 continue; 02768 02769 D = Specialization; 02770 } 02771 02772 FunctionDecl *Fn = cast<FunctionDecl>(D); 02773 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn); 02774 if (ArgType.isNull()) continue; 02775 02776 // Function-to-pointer conversion. 02777 if (!ParamWasReference && ParamType->isPointerType() && 02778 ArgType->isFunctionType()) 02779 ArgType = S.Context.getPointerType(ArgType); 02780 02781 // - If the argument is an overload set (not containing function 02782 // templates), trial argument deduction is attempted using each 02783 // of the members of the set. If deduction succeeds for only one 02784 // of the overload set members, that member is used as the 02785 // argument value for the deduction. If deduction succeeds for 02786 // more than one member of the overload set the parameter is 02787 // treated as a non-deduced context. 02788 02789 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2: 02790 // Type deduction is done independently for each P/A pair, and 02791 // the deduced template argument values are then combined. 02792 // So we do not reject deductions which were made elsewhere. 02793 SmallVector<DeducedTemplateArgument, 8> 02794 Deduced(TemplateParams->size()); 02795 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc()); 02796 Sema::TemplateDeductionResult Result 02797 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 02798 ArgType, Info, Deduced, TDF); 02799 if (Result) continue; 02800 if (!Match.isNull()) return QualType(); 02801 Match = ArgType; 02802 } 02803 02804 return Match; 02805 } 02806 02807 /// \brief Perform the adjustments to the parameter and argument types 02808 /// described in C++ [temp.deduct.call]. 02809 /// 02810 /// \returns true if the caller should not attempt to perform any template 02811 /// argument deduction based on this P/A pair. 02812 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, 02813 TemplateParameterList *TemplateParams, 02814 QualType &ParamType, 02815 QualType &ArgType, 02816 Expr *Arg, 02817 unsigned &TDF) { 02818 // C++0x [temp.deduct.call]p3: 02819 // If P is a cv-qualified type, the top level cv-qualifiers of P's type 02820 // are ignored for type deduction. 02821 if (ParamType.hasQualifiers()) 02822 ParamType = ParamType.getUnqualifiedType(); 02823 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>(); 02824 if (ParamRefType) { 02825 QualType PointeeType = ParamRefType->getPointeeType(); 02826 02827 // If the argument has incomplete array type, try to complete it's type. 02828 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0)) 02829 ArgType = Arg->getType(); 02830 02831 // [C++0x] If P is an rvalue reference to a cv-unqualified 02832 // template parameter and the argument is an lvalue, the type 02833 // "lvalue reference to A" is used in place of A for type 02834 // deduction. 02835 if (isa<RValueReferenceType>(ParamType)) { 02836 if (!PointeeType.getQualifiers() && 02837 isa<TemplateTypeParmType>(PointeeType) && 02838 Arg->Classify(S.Context).isLValue() && 02839 Arg->getType() != S.Context.OverloadTy && 02840 Arg->getType() != S.Context.BoundMemberTy) 02841 ArgType = S.Context.getLValueReferenceType(ArgType); 02842 } 02843 02844 // [...] If P is a reference type, the type referred to by P is used 02845 // for type deduction. 02846 ParamType = PointeeType; 02847 } 02848 02849 // Overload sets usually make this parameter an undeduced 02850 // context, but there are sometimes special circumstances. 02851 if (ArgType == S.Context.OverloadTy) { 02852 ArgType = ResolveOverloadForDeduction(S, TemplateParams, 02853 Arg, ParamType, 02854 ParamRefType != 0); 02855 if (ArgType.isNull()) 02856 return true; 02857 } 02858 02859 if (ParamRefType) { 02860 // C++0x [temp.deduct.call]p3: 02861 // [...] If P is of the form T&&, where T is a template parameter, and 02862 // the argument is an lvalue, the type A& is used in place of A for 02863 // type deduction. 02864 if (ParamRefType->isRValueReferenceType() && 02865 ParamRefType->getAs<TemplateTypeParmType>() && 02866 Arg->isLValue()) 02867 ArgType = S.Context.getLValueReferenceType(ArgType); 02868 } else { 02869 // C++ [temp.deduct.call]p2: 02870 // If P is not a reference type: 02871 // - If A is an array type, the pointer type produced by the 02872 // array-to-pointer standard conversion (4.2) is used in place of 02873 // A for type deduction; otherwise, 02874 if (ArgType->isArrayType()) 02875 ArgType = S.Context.getArrayDecayedType(ArgType); 02876 // - If A is a function type, the pointer type produced by the 02877 // function-to-pointer standard conversion (4.3) is used in place 02878 // of A for type deduction; otherwise, 02879 else if (ArgType->isFunctionType()) 02880 ArgType = S.Context.getPointerType(ArgType); 02881 else { 02882 // - If A is a cv-qualified type, the top level cv-qualifiers of A's 02883 // type are ignored for type deduction. 02884 ArgType = ArgType.getUnqualifiedType(); 02885 } 02886 } 02887 02888 // C++0x [temp.deduct.call]p4: 02889 // In general, the deduction process attempts to find template argument 02890 // values that will make the deduced A identical to A (after the type A 02891 // is transformed as described above). [...] 02892 TDF = TDF_SkipNonDependent; 02893 02894 // - If the original P is a reference type, the deduced A (i.e., the 02895 // type referred to by the reference) can be more cv-qualified than 02896 // the transformed A. 02897 if (ParamRefType) 02898 TDF |= TDF_ParamWithReferenceType; 02899 // - The transformed A can be another pointer or pointer to member 02900 // type that can be converted to the deduced A via a qualification 02901 // conversion (4.4). 02902 if (ArgType->isPointerType() || ArgType->isMemberPointerType() || 02903 ArgType->isObjCObjectPointerType()) 02904 TDF |= TDF_IgnoreQualifiers; 02905 // - If P is a class and P has the form simple-template-id, then the 02906 // transformed A can be a derived class of the deduced A. Likewise, 02907 // if P is a pointer to a class of the form simple-template-id, the 02908 // transformed A can be a pointer to a derived class pointed to by 02909 // the deduced A. 02910 if (isSimpleTemplateIdType(ParamType) || 02911 (isa<PointerType>(ParamType) && 02912 isSimpleTemplateIdType( 02913 ParamType->getAs<PointerType>()->getPointeeType()))) 02914 TDF |= TDF_DerivedClass; 02915 02916 return false; 02917 } 02918 02919 static bool hasDeducibleTemplateParameters(Sema &S, 02920 FunctionTemplateDecl *FunctionTemplate, 02921 QualType T); 02922 02923 /// \brief Perform template argument deduction by matching a parameter type 02924 /// against a single expression, where the expression is an element of 02925 /// an initializer list that was originally matched against the argument 02926 /// type. 02927 static Sema::TemplateDeductionResult 02928 DeduceTemplateArgumentByListElement(Sema &S, 02929 TemplateParameterList *TemplateParams, 02930 QualType ParamType, Expr *Arg, 02931 TemplateDeductionInfo &Info, 02932 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 02933 unsigned TDF) { 02934 // Handle the case where an init list contains another init list as the 02935 // element. 02936 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 02937 QualType X; 02938 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X)) 02939 return Sema::TDK_Success; // Just ignore this expression. 02940 02941 // Recurse down into the init list. 02942 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 02943 if (Sema::TemplateDeductionResult Result = 02944 DeduceTemplateArgumentByListElement(S, TemplateParams, X, 02945 ILE->getInit(i), 02946 Info, Deduced, TDF)) 02947 return Result; 02948 } 02949 return Sema::TDK_Success; 02950 } 02951 02952 // For all other cases, just match by type. 02953 QualType ArgType = Arg->getType(); 02954 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType, 02955 ArgType, Arg, TDF)) 02956 return Sema::TDK_FailedOverloadResolution; 02957 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType, 02958 ArgType, Info, Deduced, TDF); 02959 } 02960 02961 /// \brief Perform template argument deduction from a function call 02962 /// (C++ [temp.deduct.call]). 02963 /// 02964 /// \param FunctionTemplate the function template for which we are performing 02965 /// template argument deduction. 02966 /// 02967 /// \param ExplicitTemplateArguments the explicit template arguments provided 02968 /// for this call. 02969 /// 02970 /// \param Args the function call arguments 02971 /// 02972 /// \param NumArgs the number of arguments in Args 02973 /// 02974 /// \param Name the name of the function being called. This is only significant 02975 /// when the function template is a conversion function template, in which 02976 /// case this routine will also perform template argument deduction based on 02977 /// the function to which 02978 /// 02979 /// \param Specialization if template argument deduction was successful, 02980 /// this will be set to the function template specialization produced by 02981 /// template argument deduction. 02982 /// 02983 /// \param Info the argument will be updated to provide additional information 02984 /// about template argument deduction. 02985 /// 02986 /// \returns the result of template argument deduction. 02987 Sema::TemplateDeductionResult 02988 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 02989 TemplateArgumentListInfo *ExplicitTemplateArgs, 02990 llvm::ArrayRef<Expr *> Args, 02991 FunctionDecl *&Specialization, 02992 TemplateDeductionInfo &Info) { 02993 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 02994 02995 // C++ [temp.deduct.call]p1: 02996 // Template argument deduction is done by comparing each function template 02997 // parameter type (call it P) with the type of the corresponding argument 02998 // of the call (call it A) as described below. 02999 unsigned CheckArgs = Args.size(); 03000 if (Args.size() < Function->getMinRequiredArguments()) 03001 return TDK_TooFewArguments; 03002 else if (Args.size() > Function->getNumParams()) { 03003 const FunctionProtoType *Proto 03004 = Function->getType()->getAs<FunctionProtoType>(); 03005 if (Proto->isTemplateVariadic()) 03006 /* Do nothing */; 03007 else if (Proto->isVariadic()) 03008 CheckArgs = Function->getNumParams(); 03009 else 03010 return TDK_TooManyArguments; 03011 } 03012 03013 // The types of the parameters from which we will perform template argument 03014 // deduction. 03015 LocalInstantiationScope InstScope(*this); 03016 TemplateParameterList *TemplateParams 03017 = FunctionTemplate->getTemplateParameters(); 03018 SmallVector<DeducedTemplateArgument, 4> Deduced; 03019 SmallVector<QualType, 4> ParamTypes; 03020 unsigned NumExplicitlySpecified = 0; 03021 if (ExplicitTemplateArgs) { 03022 TemplateDeductionResult Result = 03023 SubstituteExplicitTemplateArguments(FunctionTemplate, 03024 *ExplicitTemplateArgs, 03025 Deduced, 03026 ParamTypes, 03027 0, 03028 Info); 03029 if (Result) 03030 return Result; 03031 03032 NumExplicitlySpecified = Deduced.size(); 03033 } else { 03034 // Just fill in the parameter types from the function declaration. 03035 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 03036 ParamTypes.push_back(Function->getParamDecl(I)->getType()); 03037 } 03038 03039 // Deduce template arguments from the function parameters. 03040 Deduced.resize(TemplateParams->size()); 03041 unsigned ArgIdx = 0; 03042 SmallVector<OriginalCallArg, 4> OriginalCallArgs; 03043 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size(); 03044 ParamIdx != NumParams; ++ParamIdx) { 03045 QualType OrigParamType = ParamTypes[ParamIdx]; 03046 QualType ParamType = OrigParamType; 03047 03048 const PackExpansionType *ParamExpansion 03049 = dyn_cast<PackExpansionType>(ParamType); 03050 if (!ParamExpansion) { 03051 // Simple case: matching a function parameter to a function argument. 03052 if (ArgIdx >= CheckArgs) 03053 break; 03054 03055 Expr *Arg = Args[ArgIdx++]; 03056 QualType ArgType = Arg->getType(); 03057 03058 unsigned TDF = 0; 03059 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 03060 ParamType, ArgType, Arg, 03061 TDF)) 03062 continue; 03063 03064 // If we have nothing to deduce, we're done. 03065 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 03066 continue; 03067 03068 // If the argument is an initializer list ... 03069 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 03070 // ... then the parameter is an undeduced context, unless the parameter 03071 // type is (reference to cv) std::initializer_list<P'>, in which case 03072 // deduction is done for each element of the initializer list, and the 03073 // result is the deduced type if it's the same for all elements. 03074 QualType X; 03075 // Removing references was already done. 03076 if (!isStdInitializerList(ParamType, &X)) 03077 continue; 03078 03079 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 03080 if (TemplateDeductionResult Result = 03081 DeduceTemplateArgumentByListElement(*this, TemplateParams, X, 03082 ILE->getInit(i), 03083 Info, Deduced, TDF)) 03084 return Result; 03085 } 03086 // Don't track the argument type, since an initializer list has none. 03087 continue; 03088 } 03089 03090 // Keep track of the argument type and corresponding parameter index, 03091 // so we can check for compatibility between the deduced A and A. 03092 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1, 03093 ArgType)); 03094 03095 if (TemplateDeductionResult Result 03096 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03097 ParamType, ArgType, 03098 Info, Deduced, TDF)) 03099 return Result; 03100 03101 continue; 03102 } 03103 03104 // C++0x [temp.deduct.call]p1: 03105 // For a function parameter pack that occurs at the end of the 03106 // parameter-declaration-list, the type A of each remaining argument of 03107 // the call is compared with the type P of the declarator-id of the 03108 // function parameter pack. Each comparison deduces template arguments 03109 // for subsequent positions in the template parameter packs expanded by 03110 // the function parameter pack. For a function parameter pack that does 03111 // not occur at the end of the parameter-declaration-list, the type of 03112 // the parameter pack is a non-deduced context. 03113 if (ParamIdx + 1 < NumParams) 03114 break; 03115 03116 QualType ParamPattern = ParamExpansion->getPattern(); 03117 SmallVector<unsigned, 2> PackIndices; 03118 { 03119 llvm::SmallBitVector SawIndices(TemplateParams->size()); 03120 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 03121 collectUnexpandedParameterPacks(ParamPattern, Unexpanded); 03122 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) { 03123 unsigned Depth, Index; 03124 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]); 03125 if (Depth == 0 && !SawIndices[Index]) { 03126 SawIndices[Index] = true; 03127 PackIndices.push_back(Index); 03128 } 03129 } 03130 } 03131 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?"); 03132 03133 // Keep track of the deduced template arguments for each parameter pack 03134 // expanded by this pack expansion (the outer index) and for each 03135 // template argument (the inner SmallVectors). 03136 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2> 03137 NewlyDeducedPacks(PackIndices.size()); 03138 SmallVector<DeducedTemplateArgument, 2> 03139 SavedPacks(PackIndices.size()); 03140 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks, 03141 NewlyDeducedPacks); 03142 bool HasAnyArguments = false; 03143 for (; ArgIdx < Args.size(); ++ArgIdx) { 03144 HasAnyArguments = true; 03145 03146 QualType OrigParamType = ParamPattern; 03147 ParamType = OrigParamType; 03148 Expr *Arg = Args[ArgIdx]; 03149 QualType ArgType = Arg->getType(); 03150 03151 unsigned TDF = 0; 03152 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams, 03153 ParamType, ArgType, Arg, 03154 TDF)) { 03155 // We can't actually perform any deduction for this argument, so stop 03156 // deduction at this point. 03157 ++ArgIdx; 03158 break; 03159 } 03160 03161 // As above, initializer lists need special handling. 03162 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) { 03163 QualType X; 03164 if (!isStdInitializerList(ParamType, &X)) { 03165 ++ArgIdx; 03166 break; 03167 } 03168 03169 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) { 03170 if (TemplateDeductionResult Result = 03171 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X, 03172 ILE->getInit(i)->getType(), 03173 Info, Deduced, TDF)) 03174 return Result; 03175 } 03176 } else { 03177 03178 // Keep track of the argument type and corresponding argument index, 03179 // so we can check for compatibility between the deduced A and A. 03180 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType)) 03181 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx, 03182 ArgType)); 03183 03184 if (TemplateDeductionResult Result 03185 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03186 ParamType, ArgType, Info, 03187 Deduced, TDF)) 03188 return Result; 03189 } 03190 03191 // Capture the deduced template arguments for each parameter pack expanded 03192 // by this pack expansion, add them to the list of arguments we've deduced 03193 // for that pack, then clear out the deduced argument. 03194 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) { 03195 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]]; 03196 if (!DeducedArg.isNull()) { 03197 NewlyDeducedPacks[I].push_back(DeducedArg); 03198 DeducedArg = DeducedTemplateArgument(); 03199 } 03200 } 03201 } 03202 03203 // Build argument packs for each of the parameter packs expanded by this 03204 // pack expansion. 03205 if (Sema::TemplateDeductionResult Result 03206 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments, 03207 Deduced, PackIndices, SavedPacks, 03208 NewlyDeducedPacks, Info)) 03209 return Result; 03210 03211 // After we've matching against a parameter pack, we're done. 03212 break; 03213 } 03214 03215 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 03216 NumExplicitlySpecified, 03217 Specialization, Info, &OriginalCallArgs); 03218 } 03219 03220 /// \brief Deduce template arguments when taking the address of a function 03221 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 03222 /// a template. 03223 /// 03224 /// \param FunctionTemplate the function template for which we are performing 03225 /// template argument deduction. 03226 /// 03227 /// \param ExplicitTemplateArguments the explicitly-specified template 03228 /// arguments. 03229 /// 03230 /// \param ArgFunctionType the function type that will be used as the 03231 /// "argument" type (A) when performing template argument deduction from the 03232 /// function template's function type. This type may be NULL, if there is no 03233 /// argument type to compare against, in C++0x [temp.arg.explicit]p3. 03234 /// 03235 /// \param Specialization if template argument deduction was successful, 03236 /// this will be set to the function template specialization produced by 03237 /// template argument deduction. 03238 /// 03239 /// \param Info the argument will be updated to provide additional information 03240 /// about template argument deduction. 03241 /// 03242 /// \returns the result of template argument deduction. 03243 Sema::TemplateDeductionResult 03244 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 03245 TemplateArgumentListInfo *ExplicitTemplateArgs, 03246 QualType ArgFunctionType, 03247 FunctionDecl *&Specialization, 03248 TemplateDeductionInfo &Info) { 03249 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 03250 TemplateParameterList *TemplateParams 03251 = FunctionTemplate->getTemplateParameters(); 03252 QualType FunctionType = Function->getType(); 03253 03254 // Substitute any explicit template arguments. 03255 LocalInstantiationScope InstScope(*this); 03256 SmallVector<DeducedTemplateArgument, 4> Deduced; 03257 unsigned NumExplicitlySpecified = 0; 03258 SmallVector<QualType, 4> ParamTypes; 03259 if (ExplicitTemplateArgs) { 03260 if (TemplateDeductionResult Result 03261 = SubstituteExplicitTemplateArguments(FunctionTemplate, 03262 *ExplicitTemplateArgs, 03263 Deduced, ParamTypes, 03264 &FunctionType, Info)) 03265 return Result; 03266 03267 NumExplicitlySpecified = Deduced.size(); 03268 } 03269 03270 // Unevaluated SFINAE context. 03271 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 03272 SFINAETrap Trap(*this); 03273 03274 Deduced.resize(TemplateParams->size()); 03275 03276 if (!ArgFunctionType.isNull()) { 03277 // Deduce template arguments from the function type. 03278 if (TemplateDeductionResult Result 03279 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03280 FunctionType, ArgFunctionType, Info, 03281 Deduced, TDF_TopLevelParameterTypeList)) 03282 return Result; 03283 } 03284 03285 if (TemplateDeductionResult Result 03286 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 03287 NumExplicitlySpecified, 03288 Specialization, Info)) 03289 return Result; 03290 03291 // If the requested function type does not match the actual type of the 03292 // specialization, template argument deduction fails. 03293 if (!ArgFunctionType.isNull() && 03294 !Context.hasSameType(ArgFunctionType, Specialization->getType())) 03295 return TDK_NonDeducedMismatch; 03296 03297 return TDK_Success; 03298 } 03299 03300 /// \brief Deduce template arguments for a templated conversion 03301 /// function (C++ [temp.deduct.conv]) and, if successful, produce a 03302 /// conversion function template specialization. 03303 Sema::TemplateDeductionResult 03304 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 03305 QualType ToType, 03306 CXXConversionDecl *&Specialization, 03307 TemplateDeductionInfo &Info) { 03308 CXXConversionDecl *Conv 03309 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()); 03310 QualType FromType = Conv->getConversionType(); 03311 03312 // Canonicalize the types for deduction. 03313 QualType P = Context.getCanonicalType(FromType); 03314 QualType A = Context.getCanonicalType(ToType); 03315 03316 // C++0x [temp.deduct.conv]p2: 03317 // If P is a reference type, the type referred to by P is used for 03318 // type deduction. 03319 if (const ReferenceType *PRef = P->getAs<ReferenceType>()) 03320 P = PRef->getPointeeType(); 03321 03322 // C++0x [temp.deduct.conv]p4: 03323 // [...] If A is a reference type, the type referred to by A is used 03324 // for type deduction. 03325 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) 03326 A = ARef->getPointeeType().getUnqualifiedType(); 03327 // C++ [temp.deduct.conv]p3: 03328 // 03329 // If A is not a reference type: 03330 else { 03331 assert(!A->isReferenceType() && "Reference types were handled above"); 03332 03333 // - If P is an array type, the pointer type produced by the 03334 // array-to-pointer standard conversion (4.2) is used in place 03335 // of P for type deduction; otherwise, 03336 if (P->isArrayType()) 03337 P = Context.getArrayDecayedType(P); 03338 // - If P is a function type, the pointer type produced by the 03339 // function-to-pointer standard conversion (4.3) is used in 03340 // place of P for type deduction; otherwise, 03341 else if (P->isFunctionType()) 03342 P = Context.getPointerType(P); 03343 // - If P is a cv-qualified type, the top level cv-qualifiers of 03344 // P's type are ignored for type deduction. 03345 else 03346 P = P.getUnqualifiedType(); 03347 03348 // C++0x [temp.deduct.conv]p4: 03349 // If A is a cv-qualified type, the top level cv-qualifiers of A's 03350 // type are ignored for type deduction. If A is a reference type, the type 03351 // referred to by A is used for type deduction. 03352 A = A.getUnqualifiedType(); 03353 } 03354 03355 // Unevaluated SFINAE context. 03356 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 03357 SFINAETrap Trap(*this); 03358 03359 // C++ [temp.deduct.conv]p1: 03360 // Template argument deduction is done by comparing the return 03361 // type of the template conversion function (call it P) with the 03362 // type that is required as the result of the conversion (call it 03363 // A) as described in 14.8.2.4. 03364 TemplateParameterList *TemplateParams 03365 = FunctionTemplate->getTemplateParameters(); 03366 SmallVector<DeducedTemplateArgument, 4> Deduced; 03367 Deduced.resize(TemplateParams->size()); 03368 03369 // C++0x [temp.deduct.conv]p4: 03370 // In general, the deduction process attempts to find template 03371 // argument values that will make the deduced A identical to 03372 // A. However, there are two cases that allow a difference: 03373 unsigned TDF = 0; 03374 // - If the original A is a reference type, A can be more 03375 // cv-qualified than the deduced A (i.e., the type referred to 03376 // by the reference) 03377 if (ToType->isReferenceType()) 03378 TDF |= TDF_ParamWithReferenceType; 03379 // - The deduced A can be another pointer or pointer to member 03380 // type that can be converted to A via a qualification 03381 // conversion. 03382 // 03383 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when 03384 // both P and A are pointers or member pointers. In this case, we 03385 // just ignore cv-qualifiers completely). 03386 if ((P->isPointerType() && A->isPointerType()) || 03387 (P->isMemberPointerType() && A->isMemberPointerType())) 03388 TDF |= TDF_IgnoreQualifiers; 03389 if (TemplateDeductionResult Result 03390 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, 03391 P, A, Info, Deduced, TDF)) 03392 return Result; 03393 03394 // Finish template argument deduction. 03395 LocalInstantiationScope InstScope(*this); 03396 FunctionDecl *Spec = 0; 03397 TemplateDeductionResult Result 03398 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec, 03399 Info); 03400 Specialization = cast_or_null<CXXConversionDecl>(Spec); 03401 return Result; 03402 } 03403 03404 /// \brief Deduce template arguments for a function template when there is 03405 /// nothing to deduce against (C++0x [temp.arg.explicit]p3). 03406 /// 03407 /// \param FunctionTemplate the function template for which we are performing 03408 /// template argument deduction. 03409 /// 03410 /// \param ExplicitTemplateArguments the explicitly-specified template 03411 /// arguments. 03412 /// 03413 /// \param Specialization if template argument deduction was successful, 03414 /// this will be set to the function template specialization produced by 03415 /// template argument deduction. 03416 /// 03417 /// \param Info the argument will be updated to provide additional information 03418 /// about template argument deduction. 03419 /// 03420 /// \returns the result of template argument deduction. 03421 Sema::TemplateDeductionResult 03422 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 03423 TemplateArgumentListInfo *ExplicitTemplateArgs, 03424 FunctionDecl *&Specialization, 03425 TemplateDeductionInfo &Info) { 03426 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, 03427 QualType(), Specialization, Info); 03428 } 03429 03430 namespace { 03431 /// Substitute the 'auto' type specifier within a type for a given replacement 03432 /// type. 03433 class SubstituteAutoTransform : 03434 public TreeTransform<SubstituteAutoTransform> { 03435 QualType Replacement; 03436 public: 03437 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) : 03438 TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) { 03439 } 03440 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) { 03441 // If we're building the type pattern to deduce against, don't wrap the 03442 // substituted type in an AutoType. Certain template deduction rules 03443 // apply only when a template type parameter appears directly (and not if 03444 // the parameter is found through desugaring). For instance: 03445 // auto &&lref = lvalue; 03446 // must transform into "rvalue reference to T" not "rvalue reference to 03447 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply. 03448 if (isa<TemplateTypeParmType>(Replacement)) { 03449 QualType Result = Replacement; 03450 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result); 03451 NewTL.setNameLoc(TL.getNameLoc()); 03452 return Result; 03453 } else { 03454 QualType Result = RebuildAutoType(Replacement); 03455 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result); 03456 NewTL.setNameLoc(TL.getNameLoc()); 03457 return Result; 03458 } 03459 } 03460 03461 ExprResult TransformLambdaExpr(LambdaExpr *E) { 03462 // Lambdas never need to be transformed. 03463 return E; 03464 } 03465 }; 03466 } 03467 03468 /// \brief Deduce the type for an auto type-specifier (C++0x [dcl.spec.auto]p6) 03469 /// 03470 /// \param Type the type pattern using the auto type-specifier. 03471 /// 03472 /// \param Init the initializer for the variable whose type is to be deduced. 03473 /// 03474 /// \param Result if type deduction was successful, this will be set to the 03475 /// deduced type. This may still contain undeduced autos if the type is 03476 /// dependent. This will be set to null if deduction succeeded, but auto 03477 /// substitution failed; the appropriate diagnostic will already have been 03478 /// produced in that case. 03479 Sema::DeduceAutoResult 03480 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, 03481 TypeSourceInfo *&Result) { 03482 if (Init->getType()->isNonOverloadPlaceholderType()) { 03483 ExprResult result = CheckPlaceholderExpr(Init); 03484 if (result.isInvalid()) return DAR_FailedAlreadyDiagnosed; 03485 Init = result.take(); 03486 } 03487 03488 if (Init->isTypeDependent()) { 03489 Result = Type; 03490 return DAR_Succeeded; 03491 } 03492 03493 SourceLocation Loc = Init->getExprLoc(); 03494 03495 LocalInstantiationScope InstScope(*this); 03496 03497 // Build template<class TemplParam> void Func(FuncParam); 03498 TemplateTypeParmDecl *TemplParam = 03499 TemplateTypeParmDecl::Create(Context, 0, SourceLocation(), Loc, 0, 0, 0, 03500 false, false); 03501 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0); 03502 NamedDecl *TemplParamPtr = TemplParam; 03503 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr, 03504 Loc); 03505 03506 TypeSourceInfo *FuncParamInfo = 03507 SubstituteAutoTransform(*this, TemplArg).TransformType(Type); 03508 assert(FuncParamInfo && "substituting template parameter for 'auto' failed"); 03509 QualType FuncParam = FuncParamInfo->getType(); 03510 03511 // Deduce type of TemplParam in Func(Init) 03512 SmallVector<DeducedTemplateArgument, 1> Deduced; 03513 Deduced.resize(1); 03514 QualType InitType = Init->getType(); 03515 unsigned TDF = 0; 03516 03517 TemplateDeductionInfo Info(Context, Loc); 03518 03519 InitListExpr * InitList = dyn_cast<InitListExpr>(Init); 03520 if (InitList) { 03521 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) { 03522 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams, 03523 TemplArg, 03524 InitList->getInit(i), 03525 Info, Deduced, TDF)) 03526 return DAR_Failed; 03527 } 03528 } else { 03529 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams, 03530 FuncParam, InitType, Init, 03531 TDF)) 03532 return DAR_Failed; 03533 03534 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam, 03535 InitType, Info, Deduced, TDF)) 03536 return DAR_Failed; 03537 } 03538 03539 QualType DeducedType = Deduced[0].getAsType(); 03540 if (DeducedType.isNull()) 03541 return DAR_Failed; 03542 03543 if (InitList) { 03544 DeducedType = BuildStdInitializerList(DeducedType, Loc); 03545 if (DeducedType.isNull()) 03546 return DAR_FailedAlreadyDiagnosed; 03547 } 03548 03549 Result = SubstituteAutoTransform(*this, DeducedType).TransformType(Type); 03550 03551 // Check that the deduced argument type is compatible with the original 03552 // argument type per C++ [temp.deduct.call]p4. 03553 if (!InitList && Result && 03554 CheckOriginalCallArgDeduction(*this, 03555 Sema::OriginalCallArg(FuncParam,0,InitType), 03556 Result->getType())) { 03557 Result = 0; 03558 return DAR_Failed; 03559 } 03560 03561 return DAR_Succeeded; 03562 } 03563 03564 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) { 03565 if (isa<InitListExpr>(Init)) 03566 Diag(VDecl->getLocation(), 03567 diag::err_auto_var_deduction_failure_from_init_list) 03568 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(); 03569 else 03570 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 03571 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 03572 << Init->getSourceRange(); 03573 } 03574 03575 static void 03576 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 03577 bool OnlyDeduced, 03578 unsigned Level, 03579 llvm::SmallBitVector &Deduced); 03580 03581 /// \brief If this is a non-static member function, 03582 static void MaybeAddImplicitObjectParameterType(ASTContext &Context, 03583 CXXMethodDecl *Method, 03584 SmallVectorImpl<QualType> &ArgTypes) { 03585 if (Method->isStatic()) 03586 return; 03587 03588 // C++ [over.match.funcs]p4: 03589 // 03590 // For non-static member functions, the type of the implicit 03591 // object parameter is 03592 // - "lvalue reference to cv X" for functions declared without a 03593 // ref-qualifier or with the & ref-qualifier 03594 // - "rvalue reference to cv X" for functions declared with the 03595 // && ref-qualifier 03596 // 03597 // FIXME: We don't have ref-qualifiers yet, so we don't do that part. 03598 QualType ArgTy = Context.getTypeDeclType(Method->getParent()); 03599 ArgTy = Context.getQualifiedType(ArgTy, 03600 Qualifiers::fromCVRMask(Method->getTypeQualifiers())); 03601 ArgTy = Context.getLValueReferenceType(ArgTy); 03602 ArgTypes.push_back(ArgTy); 03603 } 03604 03605 /// \brief Determine whether the function template \p FT1 is at least as 03606 /// specialized as \p FT2. 03607 static bool isAtLeastAsSpecializedAs(Sema &S, 03608 SourceLocation Loc, 03609 FunctionTemplateDecl *FT1, 03610 FunctionTemplateDecl *FT2, 03611 TemplatePartialOrderingContext TPOC, 03612 unsigned NumCallArguments, 03613 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) { 03614 FunctionDecl *FD1 = FT1->getTemplatedDecl(); 03615 FunctionDecl *FD2 = FT2->getTemplatedDecl(); 03616 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>(); 03617 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>(); 03618 03619 assert(Proto1 && Proto2 && "Function templates must have prototypes"); 03620 TemplateParameterList *TemplateParams = FT2->getTemplateParameters(); 03621 SmallVector<DeducedTemplateArgument, 4> Deduced; 03622 Deduced.resize(TemplateParams->size()); 03623 03624 // C++0x [temp.deduct.partial]p3: 03625 // The types used to determine the ordering depend on the context in which 03626 // the partial ordering is done: 03627 TemplateDeductionInfo Info(S.Context, Loc); 03628 CXXMethodDecl *Method1 = 0; 03629 CXXMethodDecl *Method2 = 0; 03630 bool IsNonStatic2 = false; 03631 bool IsNonStatic1 = false; 03632 unsigned Skip2 = 0; 03633 switch (TPOC) { 03634 case TPOC_Call: { 03635 // - In the context of a function call, the function parameter types are 03636 // used. 03637 Method1 = dyn_cast<CXXMethodDecl>(FD1); 03638 Method2 = dyn_cast<CXXMethodDecl>(FD2); 03639 IsNonStatic1 = Method1 && !Method1->isStatic(); 03640 IsNonStatic2 = Method2 && !Method2->isStatic(); 03641 03642 // C++0x [temp.func.order]p3: 03643 // [...] If only one of the function templates is a non-static 03644 // member, that function template is considered to have a new 03645 // first parameter inserted in its function parameter list. The 03646 // new parameter is of type "reference to cv A," where cv are 03647 // the cv-qualifiers of the function template (if any) and A is 03648 // the class of which the function template is a member. 03649 // 03650 // C++98/03 doesn't have this provision, so instead we drop the 03651 // first argument of the free function or static member, which 03652 // seems to match existing practice. 03653 SmallVector<QualType, 4> Args1; 03654 unsigned Skip1 = !S.getLangOpts().CPlusPlus0x && 03655 IsNonStatic2 && !IsNonStatic1; 03656 if (S.getLangOpts().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2) 03657 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1); 03658 Args1.insert(Args1.end(), 03659 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end()); 03660 03661 SmallVector<QualType, 4> Args2; 03662 Skip2 = !S.getLangOpts().CPlusPlus0x && 03663 IsNonStatic1 && !IsNonStatic2; 03664 if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1) 03665 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2); 03666 Args2.insert(Args2.end(), 03667 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end()); 03668 03669 // C++ [temp.func.order]p5: 03670 // The presence of unused ellipsis and default arguments has no effect on 03671 // the partial ordering of function templates. 03672 if (Args1.size() > NumCallArguments) 03673 Args1.resize(NumCallArguments); 03674 if (Args2.size() > NumCallArguments) 03675 Args2.resize(NumCallArguments); 03676 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(), 03677 Args1.data(), Args1.size(), Info, Deduced, 03678 TDF_None, /*PartialOrdering=*/true, 03679 RefParamComparisons)) 03680 return false; 03681 03682 break; 03683 } 03684 03685 case TPOC_Conversion: 03686 // - In the context of a call to a conversion operator, the return types 03687 // of the conversion function templates are used. 03688 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 03689 Proto2->getResultType(), 03690 Proto1->getResultType(), 03691 Info, Deduced, TDF_None, 03692 /*PartialOrdering=*/true, 03693 RefParamComparisons)) 03694 return false; 03695 break; 03696 03697 case TPOC_Other: 03698 // - In other contexts (14.6.6.2) the function template's function type 03699 // is used. 03700 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, 03701 FD2->getType(), FD1->getType(), 03702 Info, Deduced, TDF_None, 03703 /*PartialOrdering=*/true, 03704 RefParamComparisons)) 03705 return false; 03706 break; 03707 } 03708 03709 // C++0x [temp.deduct.partial]p11: 03710 // In most cases, all template parameters must have values in order for 03711 // deduction to succeed, but for partial ordering purposes a template 03712 // parameter may remain without a value provided it is not used in the 03713 // types being used for partial ordering. [ Note: a template parameter used 03714 // in a non-deduced context is considered used. -end note] 03715 unsigned ArgIdx = 0, NumArgs = Deduced.size(); 03716 for (; ArgIdx != NumArgs; ++ArgIdx) 03717 if (Deduced[ArgIdx].isNull()) 03718 break; 03719 03720 if (ArgIdx == NumArgs) { 03721 // All template arguments were deduced. FT1 is at least as specialized 03722 // as FT2. 03723 return true; 03724 } 03725 03726 // Figure out which template parameters were used. 03727 llvm::SmallBitVector UsedParameters(TemplateParams->size()); 03728 switch (TPOC) { 03729 case TPOC_Call: { 03730 unsigned NumParams = std::min(NumCallArguments, 03731 std::min(Proto1->getNumArgs(), 03732 Proto2->getNumArgs())); 03733 if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1) 03734 ::MarkUsedTemplateParameters(S.Context, Method2->getThisType(S.Context), 03735 false, 03736 TemplateParams->getDepth(), UsedParameters); 03737 for (unsigned I = Skip2; I < NumParams; ++I) 03738 ::MarkUsedTemplateParameters(S.Context, Proto2->getArgType(I), false, 03739 TemplateParams->getDepth(), 03740 UsedParameters); 03741 break; 03742 } 03743 03744 case TPOC_Conversion: 03745 ::MarkUsedTemplateParameters(S.Context, Proto2->getResultType(), false, 03746 TemplateParams->getDepth(), 03747 UsedParameters); 03748 break; 03749 03750 case TPOC_Other: 03751 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false, 03752 TemplateParams->getDepth(), 03753 UsedParameters); 03754 break; 03755 } 03756 03757 for (; ArgIdx != NumArgs; ++ArgIdx) 03758 // If this argument had no value deduced but was used in one of the types 03759 // used for partial ordering, then deduction fails. 03760 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx]) 03761 return false; 03762 03763 return true; 03764 } 03765 03766 /// \brief Determine whether this a function template whose parameter-type-list 03767 /// ends with a function parameter pack. 03768 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) { 03769 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 03770 unsigned NumParams = Function->getNumParams(); 03771 if (NumParams == 0) 03772 return false; 03773 03774 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1); 03775 if (!Last->isParameterPack()) 03776 return false; 03777 03778 // Make sure that no previous parameter is a parameter pack. 03779 while (--NumParams > 0) { 03780 if (Function->getParamDecl(NumParams - 1)->isParameterPack()) 03781 return false; 03782 } 03783 03784 return true; 03785 } 03786 03787 /// \brief Returns the more specialized function template according 03788 /// to the rules of function template partial ordering (C++ [temp.func.order]). 03789 /// 03790 /// \param FT1 the first function template 03791 /// 03792 /// \param FT2 the second function template 03793 /// 03794 /// \param TPOC the context in which we are performing partial ordering of 03795 /// function templates. 03796 /// 03797 /// \param NumCallArguments The number of arguments in a call, used only 03798 /// when \c TPOC is \c TPOC_Call. 03799 /// 03800 /// \returns the more specialized function template. If neither 03801 /// template is more specialized, returns NULL. 03802 FunctionTemplateDecl * 03803 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 03804 FunctionTemplateDecl *FT2, 03805 SourceLocation Loc, 03806 TemplatePartialOrderingContext TPOC, 03807 unsigned NumCallArguments) { 03808 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons; 03809 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 03810 NumCallArguments, 0); 03811 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, 03812 NumCallArguments, 03813 &RefParamComparisons); 03814 03815 if (Better1 != Better2) // We have a clear winner 03816 return Better1? FT1 : FT2; 03817 03818 if (!Better1 && !Better2) // Neither is better than the other 03819 return 0; 03820 03821 // C++0x [temp.deduct.partial]p10: 03822 // If for each type being considered a given template is at least as 03823 // specialized for all types and more specialized for some set of types and 03824 // the other template is not more specialized for any types or is not at 03825 // least as specialized for any types, then the given template is more 03826 // specialized than the other template. Otherwise, neither template is more 03827 // specialized than the other. 03828 Better1 = false; 03829 Better2 = false; 03830 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) { 03831 // C++0x [temp.deduct.partial]p9: 03832 // If, for a given type, deduction succeeds in both directions (i.e., the 03833 // types are identical after the transformations above) and both P and A 03834 // were reference types (before being replaced with the type referred to 03835 // above): 03836 03837 // -- if the type from the argument template was an lvalue reference 03838 // and the type from the parameter template was not, the argument 03839 // type is considered to be more specialized than the other; 03840 // otherwise, 03841 if (!RefParamComparisons[I].ArgIsRvalueRef && 03842 RefParamComparisons[I].ParamIsRvalueRef) { 03843 Better2 = true; 03844 if (Better1) 03845 return 0; 03846 continue; 03847 } else if (!RefParamComparisons[I].ParamIsRvalueRef && 03848 RefParamComparisons[I].ArgIsRvalueRef) { 03849 Better1 = true; 03850 if (Better2) 03851 return 0; 03852 continue; 03853 } 03854 03855 // -- if the type from the argument template is more cv-qualified than 03856 // the type from the parameter template (as described above), the 03857 // argument type is considered to be more specialized than the 03858 // other; otherwise, 03859 switch (RefParamComparisons[I].Qualifiers) { 03860 case NeitherMoreQualified: 03861 break; 03862 03863 case ParamMoreQualified: 03864 Better1 = true; 03865 if (Better2) 03866 return 0; 03867 continue; 03868 03869 case ArgMoreQualified: 03870 Better2 = true; 03871 if (Better1) 03872 return 0; 03873 continue; 03874 } 03875 03876 // -- neither type is more specialized than the other. 03877 } 03878 03879 assert(!(Better1 && Better2) && "Should have broken out in the loop above"); 03880 if (Better1) 03881 return FT1; 03882 else if (Better2) 03883 return FT2; 03884 03885 // FIXME: This mimics what GCC implements, but doesn't match up with the 03886 // proposed resolution for core issue 692. This area needs to be sorted out, 03887 // but for now we attempt to maintain compatibility. 03888 bool Variadic1 = isVariadicFunctionTemplate(FT1); 03889 bool Variadic2 = isVariadicFunctionTemplate(FT2); 03890 if (Variadic1 != Variadic2) 03891 return Variadic1? FT2 : FT1; 03892 03893 return 0; 03894 } 03895 03896 /// \brief Determine if the two templates are equivalent. 03897 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) { 03898 if (T1 == T2) 03899 return true; 03900 03901 if (!T1 || !T2) 03902 return false; 03903 03904 return T1->getCanonicalDecl() == T2->getCanonicalDecl(); 03905 } 03906 03907 /// \brief Retrieve the most specialized of the given function template 03908 /// specializations. 03909 /// 03910 /// \param SpecBegin the start iterator of the function template 03911 /// specializations that we will be comparing. 03912 /// 03913 /// \param SpecEnd the end iterator of the function template 03914 /// specializations, paired with \p SpecBegin. 03915 /// 03916 /// \param TPOC the partial ordering context to use to compare the function 03917 /// template specializations. 03918 /// 03919 /// \param NumCallArguments The number of arguments in a call, used only 03920 /// when \c TPOC is \c TPOC_Call. 03921 /// 03922 /// \param Loc the location where the ambiguity or no-specializations 03923 /// diagnostic should occur. 03924 /// 03925 /// \param NoneDiag partial diagnostic used to diagnose cases where there are 03926 /// no matching candidates. 03927 /// 03928 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 03929 /// occurs. 03930 /// 03931 /// \param CandidateDiag partial diagnostic used for each function template 03932 /// specialization that is a candidate in the ambiguous ordering. One parameter 03933 /// in this diagnostic should be unbound, which will correspond to the string 03934 /// describing the template arguments for the function template specialization. 03935 /// 03936 /// \param Index if non-NULL and the result of this function is non-nULL, 03937 /// receives the index corresponding to the resulting function template 03938 /// specialization. 03939 /// 03940 /// \returns the most specialized function template specialization, if 03941 /// found. Otherwise, returns SpecEnd. 03942 /// 03943 /// \todo FIXME: Consider passing in the "also-ran" candidates that failed 03944 /// template argument deduction. 03945 UnresolvedSetIterator 03946 Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin, 03947 UnresolvedSetIterator SpecEnd, 03948 TemplatePartialOrderingContext TPOC, 03949 unsigned NumCallArguments, 03950 SourceLocation Loc, 03951 const PartialDiagnostic &NoneDiag, 03952 const PartialDiagnostic &AmbigDiag, 03953 const PartialDiagnostic &CandidateDiag, 03954 bool Complain, 03955 QualType TargetType) { 03956 if (SpecBegin == SpecEnd) { 03957 if (Complain) 03958 Diag(Loc, NoneDiag); 03959 return SpecEnd; 03960 } 03961 03962 if (SpecBegin + 1 == SpecEnd) 03963 return SpecBegin; 03964 03965 // Find the function template that is better than all of the templates it 03966 // has been compared to. 03967 UnresolvedSetIterator Best = SpecBegin; 03968 FunctionTemplateDecl *BestTemplate 03969 = cast<FunctionDecl>(*Best)->getPrimaryTemplate(); 03970 assert(BestTemplate && "Not a function template specialization?"); 03971 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) { 03972 FunctionTemplateDecl *Challenger 03973 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 03974 assert(Challenger && "Not a function template specialization?"); 03975 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 03976 Loc, TPOC, NumCallArguments), 03977 Challenger)) { 03978 Best = I; 03979 BestTemplate = Challenger; 03980 } 03981 } 03982 03983 // Make sure that the "best" function template is more specialized than all 03984 // of the others. 03985 bool Ambiguous = false; 03986 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 03987 FunctionTemplateDecl *Challenger 03988 = cast<FunctionDecl>(*I)->getPrimaryTemplate(); 03989 if (I != Best && 03990 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, 03991 Loc, TPOC, NumCallArguments), 03992 BestTemplate)) { 03993 Ambiguous = true; 03994 break; 03995 } 03996 } 03997 03998 if (!Ambiguous) { 03999 // We found an answer. Return it. 04000 return Best; 04001 } 04002 04003 // Diagnose the ambiguity. 04004 if (Complain) 04005 Diag(Loc, AmbigDiag); 04006 04007 if (Complain) 04008 // FIXME: Can we order the candidates in some sane way? 04009 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) { 04010 PartialDiagnostic PD = CandidateDiag; 04011 PD << getTemplateArgumentBindingsText( 04012 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(), 04013 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs()); 04014 if (!TargetType.isNull()) 04015 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(), 04016 TargetType); 04017 Diag((*I)->getLocation(), PD); 04018 } 04019 04020 return SpecEnd; 04021 } 04022 04023 /// \brief Returns the more specialized class template partial specialization 04024 /// according to the rules of partial ordering of class template partial 04025 /// specializations (C++ [temp.class.order]). 04026 /// 04027 /// \param PS1 the first class template partial specialization 04028 /// 04029 /// \param PS2 the second class template partial specialization 04030 /// 04031 /// \returns the more specialized class template partial specialization. If 04032 /// neither partial specialization is more specialized, returns NULL. 04033 ClassTemplatePartialSpecializationDecl * 04034 Sema::getMoreSpecializedPartialSpecialization( 04035 ClassTemplatePartialSpecializationDecl *PS1, 04036 ClassTemplatePartialSpecializationDecl *PS2, 04037 SourceLocation Loc) { 04038 // C++ [temp.class.order]p1: 04039 // For two class template partial specializations, the first is at least as 04040 // specialized as the second if, given the following rewrite to two 04041 // function templates, the first function template is at least as 04042 // specialized as the second according to the ordering rules for function 04043 // templates (14.6.6.2): 04044 // - the first function template has the same template parameters as the 04045 // first partial specialization and has a single function parameter 04046 // whose type is a class template specialization with the template 04047 // arguments of the first partial specialization, and 04048 // - the second function template has the same template parameters as the 04049 // second partial specialization and has a single function parameter 04050 // whose type is a class template specialization with the template 04051 // arguments of the second partial specialization. 04052 // 04053 // Rather than synthesize function templates, we merely perform the 04054 // equivalent partial ordering by performing deduction directly on 04055 // the template arguments of the class template partial 04056 // specializations. This computation is slightly simpler than the 04057 // general problem of function template partial ordering, because 04058 // class template partial specializations are more constrained. We 04059 // know that every template parameter is deducible from the class 04060 // template partial specialization's template arguments, for 04061 // example. 04062 SmallVector<DeducedTemplateArgument, 4> Deduced; 04063 TemplateDeductionInfo Info(Context, Loc); 04064 04065 QualType PT1 = PS1->getInjectedSpecializationType(); 04066 QualType PT2 = PS2->getInjectedSpecializationType(); 04067 04068 // Determine whether PS1 is at least as specialized as PS2 04069 Deduced.resize(PS2->getTemplateParameters()->size()); 04070 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this, 04071 PS2->getTemplateParameters(), 04072 PT2, PT1, Info, Deduced, TDF_None, 04073 /*PartialOrdering=*/true, 04074 /*RefParamComparisons=*/0); 04075 if (Better1) { 04076 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2, 04077 Deduced.data(), Deduced.size(), Info); 04078 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2, 04079 PS1->getTemplateArgs(), 04080 Deduced, Info); 04081 } 04082 04083 // Determine whether PS2 is at least as specialized as PS1 04084 Deduced.clear(); 04085 Deduced.resize(PS1->getTemplateParameters()->size()); 04086 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this, 04087 PS1->getTemplateParameters(), 04088 PT1, PT2, Info, Deduced, TDF_None, 04089 /*PartialOrdering=*/true, 04090 /*RefParamComparisons=*/0); 04091 if (Better2) { 04092 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1, 04093 Deduced.data(), Deduced.size(), Info); 04094 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1, 04095 PS2->getTemplateArgs(), 04096 Deduced, Info); 04097 } 04098 04099 if (Better1 == Better2) 04100 return 0; 04101 04102 return Better1? PS1 : PS2; 04103 } 04104 04105 static void 04106 MarkUsedTemplateParameters(ASTContext &Ctx, 04107 const TemplateArgument &TemplateArg, 04108 bool OnlyDeduced, 04109 unsigned Depth, 04110 llvm::SmallBitVector &Used); 04111 04112 /// \brief Mark the template parameters that are used by the given 04113 /// expression. 04114 static void 04115 MarkUsedTemplateParameters(ASTContext &Ctx, 04116 const Expr *E, 04117 bool OnlyDeduced, 04118 unsigned Depth, 04119 llvm::SmallBitVector &Used) { 04120 // We can deduce from a pack expansion. 04121 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E)) 04122 E = Expansion->getPattern(); 04123 04124 // Skip through any implicit casts we added while type-checking. 04125 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 04126 E = ICE->getSubExpr(); 04127 04128 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to 04129 // find other occurrences of template parameters. 04130 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 04131 if (!DRE) 04132 return; 04133 04134 const NonTypeTemplateParmDecl *NTTP 04135 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 04136 if (!NTTP) 04137 return; 04138 04139 if (NTTP->getDepth() == Depth) 04140 Used[NTTP->getIndex()] = true; 04141 } 04142 04143 /// \brief Mark the template parameters that are used by the given 04144 /// nested name specifier. 04145 static void 04146 MarkUsedTemplateParameters(ASTContext &Ctx, 04147 NestedNameSpecifier *NNS, 04148 bool OnlyDeduced, 04149 unsigned Depth, 04150 llvm::SmallBitVector &Used) { 04151 if (!NNS) 04152 return; 04153 04154 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth, 04155 Used); 04156 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0), 04157 OnlyDeduced, Depth, Used); 04158 } 04159 04160 /// \brief Mark the template parameters that are used by the given 04161 /// template name. 04162 static void 04163 MarkUsedTemplateParameters(ASTContext &Ctx, 04164 TemplateName Name, 04165 bool OnlyDeduced, 04166 unsigned Depth, 04167 llvm::SmallBitVector &Used) { 04168 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 04169 if (TemplateTemplateParmDecl *TTP 04170 = dyn_cast<TemplateTemplateParmDecl>(Template)) { 04171 if (TTP->getDepth() == Depth) 04172 Used[TTP->getIndex()] = true; 04173 } 04174 return; 04175 } 04176 04177 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) 04178 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced, 04179 Depth, Used); 04180 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) 04181 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced, 04182 Depth, Used); 04183 } 04184 04185 /// \brief Mark the template parameters that are used by the given 04186 /// type. 04187 static void 04188 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, 04189 bool OnlyDeduced, 04190 unsigned Depth, 04191 llvm::SmallBitVector &Used) { 04192 if (T.isNull()) 04193 return; 04194 04195 // Non-dependent types have nothing deducible 04196 if (!T->isDependentType()) 04197 return; 04198 04199 T = Ctx.getCanonicalType(T); 04200 switch (T->getTypeClass()) { 04201 case Type::Pointer: 04202 MarkUsedTemplateParameters(Ctx, 04203 cast<PointerType>(T)->getPointeeType(), 04204 OnlyDeduced, 04205 Depth, 04206 Used); 04207 break; 04208 04209 case Type::BlockPointer: 04210 MarkUsedTemplateParameters(Ctx, 04211 cast<BlockPointerType>(T)->getPointeeType(), 04212 OnlyDeduced, 04213 Depth, 04214 Used); 04215 break; 04216 04217 case Type::LValueReference: 04218 case Type::RValueReference: 04219 MarkUsedTemplateParameters(Ctx, 04220 cast<ReferenceType>(T)->getPointeeType(), 04221 OnlyDeduced, 04222 Depth, 04223 Used); 04224 break; 04225 04226 case Type::MemberPointer: { 04227 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr()); 04228 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced, 04229 Depth, Used); 04230 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0), 04231 OnlyDeduced, Depth, Used); 04232 break; 04233 } 04234 04235 case Type::DependentSizedArray: 04236 MarkUsedTemplateParameters(Ctx, 04237 cast<DependentSizedArrayType>(T)->getSizeExpr(), 04238 OnlyDeduced, Depth, Used); 04239 // Fall through to check the element type 04240 04241 case Type::ConstantArray: 04242 case Type::IncompleteArray: 04243 MarkUsedTemplateParameters(Ctx, 04244 cast<ArrayType>(T)->getElementType(), 04245 OnlyDeduced, Depth, Used); 04246 break; 04247 04248 case Type::Vector: 04249 case Type::ExtVector: 04250 MarkUsedTemplateParameters(Ctx, 04251 cast<VectorType>(T)->getElementType(), 04252 OnlyDeduced, Depth, Used); 04253 break; 04254 04255 case Type::DependentSizedExtVector: { 04256 const DependentSizedExtVectorType *VecType 04257 = cast<DependentSizedExtVectorType>(T); 04258 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced, 04259 Depth, Used); 04260 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, 04261 Depth, Used); 04262 break; 04263 } 04264 04265 case Type::FunctionProto: { 04266 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 04267 MarkUsedTemplateParameters(Ctx, Proto->getResultType(), OnlyDeduced, 04268 Depth, Used); 04269 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I) 04270 MarkUsedTemplateParameters(Ctx, Proto->getArgType(I), OnlyDeduced, 04271 Depth, Used); 04272 break; 04273 } 04274 04275 case Type::TemplateTypeParm: { 04276 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T); 04277 if (TTP->getDepth() == Depth) 04278 Used[TTP->getIndex()] = true; 04279 break; 04280 } 04281 04282 case Type::SubstTemplateTypeParmPack: { 04283 const SubstTemplateTypeParmPackType *Subst 04284 = cast<SubstTemplateTypeParmPackType>(T); 04285 MarkUsedTemplateParameters(Ctx, 04286 QualType(Subst->getReplacedParameter(), 0), 04287 OnlyDeduced, Depth, Used); 04288 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), 04289 OnlyDeduced, Depth, Used); 04290 break; 04291 } 04292 04293 case Type::InjectedClassName: 04294 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 04295 // fall through 04296 04297 case Type::TemplateSpecialization: { 04298 const TemplateSpecializationType *Spec 04299 = cast<TemplateSpecializationType>(T); 04300 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced, 04301 Depth, Used); 04302 04303 // C++0x [temp.deduct.type]p9: 04304 // If the template argument list of P contains a pack expansion that is not 04305 // the last template argument, the entire template argument list is a 04306 // non-deduced context. 04307 if (OnlyDeduced && 04308 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 04309 break; 04310 04311 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 04312 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 04313 Used); 04314 break; 04315 } 04316 04317 case Type::Complex: 04318 if (!OnlyDeduced) 04319 MarkUsedTemplateParameters(Ctx, 04320 cast<ComplexType>(T)->getElementType(), 04321 OnlyDeduced, Depth, Used); 04322 break; 04323 04324 case Type::Atomic: 04325 if (!OnlyDeduced) 04326 MarkUsedTemplateParameters(Ctx, 04327 cast<AtomicType>(T)->getValueType(), 04328 OnlyDeduced, Depth, Used); 04329 break; 04330 04331 case Type::DependentName: 04332 if (!OnlyDeduced) 04333 MarkUsedTemplateParameters(Ctx, 04334 cast<DependentNameType>(T)->getQualifier(), 04335 OnlyDeduced, Depth, Used); 04336 break; 04337 04338 case Type::DependentTemplateSpecialization: { 04339 const DependentTemplateSpecializationType *Spec 04340 = cast<DependentTemplateSpecializationType>(T); 04341 if (!OnlyDeduced) 04342 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(), 04343 OnlyDeduced, Depth, Used); 04344 04345 // C++0x [temp.deduct.type]p9: 04346 // If the template argument list of P contains a pack expansion that is not 04347 // the last template argument, the entire template argument list is a 04348 // non-deduced context. 04349 if (OnlyDeduced && 04350 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs())) 04351 break; 04352 04353 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I) 04354 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth, 04355 Used); 04356 break; 04357 } 04358 04359 case Type::TypeOf: 04360 if (!OnlyDeduced) 04361 MarkUsedTemplateParameters(Ctx, 04362 cast<TypeOfType>(T)->getUnderlyingType(), 04363 OnlyDeduced, Depth, Used); 04364 break; 04365 04366 case Type::TypeOfExpr: 04367 if (!OnlyDeduced) 04368 MarkUsedTemplateParameters(Ctx, 04369 cast<TypeOfExprType>(T)->getUnderlyingExpr(), 04370 OnlyDeduced, Depth, Used); 04371 break; 04372 04373 case Type::Decltype: 04374 if (!OnlyDeduced) 04375 MarkUsedTemplateParameters(Ctx, 04376 cast<DecltypeType>(T)->getUnderlyingExpr(), 04377 OnlyDeduced, Depth, Used); 04378 break; 04379 04380 case Type::UnaryTransform: 04381 if (!OnlyDeduced) 04382 MarkUsedTemplateParameters(Ctx, 04383 cast<UnaryTransformType>(T)->getUnderlyingType(), 04384 OnlyDeduced, Depth, Used); 04385 break; 04386 04387 case Type::PackExpansion: 04388 MarkUsedTemplateParameters(Ctx, 04389 cast<PackExpansionType>(T)->getPattern(), 04390 OnlyDeduced, Depth, Used); 04391 break; 04392 04393 case Type::Auto: 04394 MarkUsedTemplateParameters(Ctx, 04395 cast<AutoType>(T)->getDeducedType(), 04396 OnlyDeduced, Depth, Used); 04397 04398 // None of these types have any template parameters in them. 04399 case Type::Builtin: 04400 case Type::VariableArray: 04401 case Type::FunctionNoProto: 04402 case Type::Record: 04403 case Type::Enum: 04404 case Type::ObjCInterface: 04405 case Type::ObjCObject: 04406 case Type::ObjCObjectPointer: 04407 case Type::UnresolvedUsing: 04408 #define TYPE(Class, Base) 04409 #define ABSTRACT_TYPE(Class, Base) 04410 #define DEPENDENT_TYPE(Class, Base) 04411 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 04412 #include "clang/AST/TypeNodes.def" 04413 break; 04414 } 04415 } 04416 04417 /// \brief Mark the template parameters that are used by this 04418 /// template argument. 04419 static void 04420 MarkUsedTemplateParameters(ASTContext &Ctx, 04421 const TemplateArgument &TemplateArg, 04422 bool OnlyDeduced, 04423 unsigned Depth, 04424 llvm::SmallBitVector &Used) { 04425 switch (TemplateArg.getKind()) { 04426 case TemplateArgument::Null: 04427 case TemplateArgument::Integral: 04428 case TemplateArgument::Declaration: 04429 break; 04430 04431 case TemplateArgument::Type: 04432 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced, 04433 Depth, Used); 04434 break; 04435 04436 case TemplateArgument::Template: 04437 case TemplateArgument::TemplateExpansion: 04438 MarkUsedTemplateParameters(Ctx, 04439 TemplateArg.getAsTemplateOrTemplatePattern(), 04440 OnlyDeduced, Depth, Used); 04441 break; 04442 04443 case TemplateArgument::Expression: 04444 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced, 04445 Depth, Used); 04446 break; 04447 04448 case TemplateArgument::Pack: 04449 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(), 04450 PEnd = TemplateArg.pack_end(); 04451 P != PEnd; ++P) 04452 MarkUsedTemplateParameters(Ctx, *P, OnlyDeduced, Depth, Used); 04453 break; 04454 } 04455 } 04456 04457 /// \brief Mark the template parameters can be deduced by the given 04458 /// template argument list. 04459 /// 04460 /// \param TemplateArgs the template argument list from which template 04461 /// parameters will be deduced. 04462 /// 04463 /// \param Deduced a bit vector whose elements will be set to \c true 04464 /// to indicate when the corresponding template parameter will be 04465 /// deduced. 04466 void 04467 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 04468 bool OnlyDeduced, unsigned Depth, 04469 llvm::SmallBitVector &Used) { 04470 // C++0x [temp.deduct.type]p9: 04471 // If the template argument list of P contains a pack expansion that is not 04472 // the last template argument, the entire template argument list is a 04473 // non-deduced context. 04474 if (OnlyDeduced && 04475 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size())) 04476 return; 04477 04478 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 04479 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, 04480 Depth, Used); 04481 } 04482 04483 /// \brief Marks all of the template parameters that will be deduced by a 04484 /// call to the given function template. 04485 void 04486 Sema::MarkDeducedTemplateParameters(ASTContext &Ctx, 04487 FunctionTemplateDecl *FunctionTemplate, 04488 llvm::SmallBitVector &Deduced) { 04489 TemplateParameterList *TemplateParams 04490 = FunctionTemplate->getTemplateParameters(); 04491 Deduced.clear(); 04492 Deduced.resize(TemplateParams->size()); 04493 04494 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl(); 04495 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) 04496 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(), 04497 true, TemplateParams->getDepth(), Deduced); 04498 } 04499 04500 bool hasDeducibleTemplateParameters(Sema &S, 04501 FunctionTemplateDecl *FunctionTemplate, 04502 QualType T) { 04503 if (!T->isDependentType()) 04504 return false; 04505 04506 TemplateParameterList *TemplateParams 04507 = FunctionTemplate->getTemplateParameters(); 04508 llvm::SmallBitVector Deduced(TemplateParams->size()); 04509 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(), 04510 Deduced); 04511 04512 return Deduced.any(); 04513 }