1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/OperationKinds.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 using llvm::RoundingMode; 54 55 /// Determine whether the use of this declaration is valid, without 56 /// emitting diagnostics. 57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 58 // See if this is an auto-typed variable whose initializer we are parsing. 59 if (ParsingInitForAutoVars.count(D)) 60 return false; 61 62 // See if this is a deleted function. 63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 64 if (FD->isDeleted()) 65 return false; 66 67 // If the function has a deduced return type, and we can't deduce it, 68 // then we can't use it either. 69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 71 return false; 72 73 // See if this is an aligned allocation/deallocation function that is 74 // unavailable. 75 if (TreatUnavailableAsInvalid && 76 isUnavailableAlignedAllocationFunction(*FD)) 77 return false; 78 } 79 80 // See if this function is unavailable. 81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 83 return false; 84 85 return true; 86 } 87 88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 89 // Warn if this is used but marked unused. 90 if (const auto *A = D->getAttr<UnusedAttr>()) { 91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 92 // should diagnose them. 93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 96 if (DC && !DC->hasAttr<UnusedAttr>()) 97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 98 } 99 } 100 } 101 102 /// Emit a note explaining that this function is deleted. 103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 104 assert(Decl && Decl->isDeleted()); 105 106 if (Decl->isDefaulted()) { 107 // If the method was explicitly defaulted, point at that declaration. 108 if (!Decl->isImplicit()) 109 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 110 111 // Try to diagnose why this special member function was implicitly 112 // deleted. This might fail, if that reason no longer applies. 113 DiagnoseDeletedDefaultedFunction(Decl); 114 return; 115 } 116 117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 118 if (Ctor && Ctor->isInheritingConstructor()) 119 return NoteDeletedInheritingConstructor(Ctor); 120 121 Diag(Decl->getLocation(), diag::note_availability_specified_here) 122 << Decl << 1; 123 } 124 125 /// Determine whether a FunctionDecl was ever declared with an 126 /// explicit storage class. 127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 128 for (auto I : D->redecls()) { 129 if (I->getStorageClass() != SC_None) 130 return true; 131 } 132 return false; 133 } 134 135 /// Check whether we're in an extern inline function and referring to a 136 /// variable or function with internal linkage (C11 6.7.4p3). 137 /// 138 /// This is only a warning because we used to silently accept this code, but 139 /// in many cases it will not behave correctly. This is not enabled in C++ mode 140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 141 /// and so while there may still be user mistakes, most of the time we can't 142 /// prove that there are errors. 143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 144 const NamedDecl *D, 145 SourceLocation Loc) { 146 // This is disabled under C++; there are too many ways for this to fire in 147 // contexts where the warning is a false positive, or where it is technically 148 // correct but benign. 149 if (S.getLangOpts().CPlusPlus) 150 return; 151 152 // Check if this is an inlined function or method. 153 FunctionDecl *Current = S.getCurFunctionDecl(); 154 if (!Current) 155 return; 156 if (!Current->isInlined()) 157 return; 158 if (!Current->isExternallyVisible()) 159 return; 160 161 // Check if the decl has internal linkage. 162 if (D->getFormalLinkage() != InternalLinkage) 163 return; 164 165 // Downgrade from ExtWarn to Extension if 166 // (1) the supposedly external inline function is in the main file, 167 // and probably won't be included anywhere else. 168 // (2) the thing we're referencing is a pure function. 169 // (3) the thing we're referencing is another inline function. 170 // This last can give us false negatives, but it's better than warning on 171 // wrappers for simple C library functions. 172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 174 if (!DowngradeWarning && UsedFn) 175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 176 177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 178 : diag::ext_internal_in_extern_inline) 179 << /*IsVar=*/!UsedFn << D; 180 181 S.MaybeSuggestAddingStaticToDecl(Current); 182 183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 184 << D; 185 } 186 187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 188 const FunctionDecl *First = Cur->getFirstDecl(); 189 190 // Suggest "static" on the function, if possible. 191 if (!hasAnyExplicitStorageClass(First)) { 192 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 193 Diag(DeclBegin, diag::note_convert_inline_to_static) 194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 195 } 196 } 197 198 /// Determine whether the use of this declaration is valid, and 199 /// emit any corresponding diagnostics. 200 /// 201 /// This routine diagnoses various problems with referencing 202 /// declarations that can occur when using a declaration. For example, 203 /// it might warn if a deprecated or unavailable declaration is being 204 /// used, or produce an error (and return true) if a C++0x deleted 205 /// function is being used. 206 /// 207 /// \returns true if there was an error (this declaration cannot be 208 /// referenced), false otherwise. 209 /// 210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 211 const ObjCInterfaceDecl *UnknownObjCClass, 212 bool ObjCPropertyAccess, 213 bool AvoidPartialAvailabilityChecks, 214 ObjCInterfaceDecl *ClassReceiver) { 215 SourceLocation Loc = Locs.front(); 216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 217 // If there were any diagnostics suppressed by template argument deduction, 218 // emit them now. 219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 220 if (Pos != SuppressedDiagnostics.end()) { 221 for (const PartialDiagnosticAt &Suppressed : Pos->second) 222 Diag(Suppressed.first, Suppressed.second); 223 224 // Clear out the list of suppressed diagnostics, so that we don't emit 225 // them again for this specialization. However, we don't obsolete this 226 // entry from the table, because we want to avoid ever emitting these 227 // diagnostics again. 228 Pos->second.clear(); 229 } 230 231 // C++ [basic.start.main]p3: 232 // The function 'main' shall not be used within a program. 233 if (cast<FunctionDecl>(D)->isMain()) 234 Diag(Loc, diag::ext_main_used); 235 236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 237 } 238 239 // See if this is an auto-typed variable whose initializer we are parsing. 240 if (ParsingInitForAutoVars.count(D)) { 241 if (isa<BindingDecl>(D)) { 242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 243 << D->getDeclName(); 244 } else { 245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 246 << D->getDeclName() << cast<VarDecl>(D)->getType(); 247 } 248 return true; 249 } 250 251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 252 // See if this is a deleted function. 253 if (FD->isDeleted()) { 254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 255 if (Ctor && Ctor->isInheritingConstructor()) 256 Diag(Loc, diag::err_deleted_inherited_ctor_use) 257 << Ctor->getParent() 258 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 259 else 260 Diag(Loc, diag::err_deleted_function_use); 261 NoteDeletedFunction(FD); 262 return true; 263 } 264 265 // [expr.prim.id]p4 266 // A program that refers explicitly or implicitly to a function with a 267 // trailing requires-clause whose constraint-expression is not satisfied, 268 // other than to declare it, is ill-formed. [...] 269 // 270 // See if this is a function with constraints that need to be satisfied. 271 // Check this before deducing the return type, as it might instantiate the 272 // definition. 273 if (FD->getTrailingRequiresClause()) { 274 ConstraintSatisfaction Satisfaction; 275 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 276 // A diagnostic will have already been generated (non-constant 277 // constraint expression, for example) 278 return true; 279 if (!Satisfaction.IsSatisfied) { 280 Diag(Loc, 281 diag::err_reference_to_function_with_unsatisfied_constraints) 282 << D; 283 DiagnoseUnsatisfiedConstraint(Satisfaction); 284 return true; 285 } 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 295 return true; 296 297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 298 return true; 299 } 300 301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 302 // Lambdas are only default-constructible or assignable in C++2a onwards. 303 if (MD->getParent()->isLambda() && 304 ((isa<CXXConstructorDecl>(MD) && 305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 308 << !isa<CXXConstructorDecl>(MD); 309 } 310 } 311 312 auto getReferencedObjCProp = [](const NamedDecl *D) -> 313 const ObjCPropertyDecl * { 314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 315 return MD->findPropertyDecl(); 316 return nullptr; 317 }; 318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 320 return true; 321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 322 return true; 323 } 324 325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 326 // Only the variables omp_in and omp_out are allowed in the combiner. 327 // Only the variables omp_priv and omp_orig are allowed in the 328 // initializer-clause. 329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 331 isa<VarDecl>(D)) { 332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 333 << getCurFunction()->HasOMPDeclareReductionCombiner; 334 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 335 return true; 336 } 337 338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 339 // List-items in map clauses on this construct may only refer to the declared 340 // variable var and entities that could be referenced by a procedure defined 341 // at the same location 342 if (LangOpts.OpenMP && isa<VarDecl>(D) && 343 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 344 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 345 << getOpenMPDeclareMapperVarName(); 346 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 347 return true; 348 } 349 350 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 351 AvoidPartialAvailabilityChecks, ClassReceiver); 352 353 DiagnoseUnusedOfDecl(*this, D, Loc); 354 355 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 356 357 // CUDA/HIP: Diagnose invalid references of host global variables in device 358 // functions. Reference of device global variables in host functions is 359 // allowed through shadow variables therefore it is not diagnosed. 360 if (LangOpts.CUDAIsDevice) { 361 auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); 362 auto Target = IdentifyCUDATarget(FD); 363 if (FD && Target != CFT_Host) { 364 const auto *VD = dyn_cast<VarDecl>(D); 365 if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && 366 !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && 367 !VD->getType()->isCUDADeviceBuiltinSurfaceType() && 368 !VD->getType()->isCUDADeviceBuiltinTextureType() && 369 !VD->isConstexpr() && !VD->getType().isConstQualified()) 370 targetDiag(*Locs.begin(), diag::err_ref_bad_target) 371 << /*host*/ 2 << /*variable*/ 1 << VD << Target; 372 } 373 } 374 375 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 376 if (const auto *VD = dyn_cast<ValueDecl>(D)) 377 checkDeviceDecl(VD, Loc); 378 379 if (!Context.getTargetInfo().isTLSSupported()) 380 if (const auto *VD = dyn_cast<VarDecl>(D)) 381 if (VD->getTLSKind() != VarDecl::TLS_None) 382 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 383 } 384 385 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 386 !isUnevaluatedContext()) { 387 // C++ [expr.prim.req.nested] p3 388 // A local parameter shall only appear as an unevaluated operand 389 // (Clause 8) within the constraint-expression. 390 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 391 << D; 392 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 393 return true; 394 } 395 396 return false; 397 } 398 399 /// DiagnoseSentinelCalls - This routine checks whether a call or 400 /// message-send is to a declaration with the sentinel attribute, and 401 /// if so, it checks that the requirements of the sentinel are 402 /// satisfied. 403 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 404 ArrayRef<Expr *> Args) { 405 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 406 if (!attr) 407 return; 408 409 // The number of formal parameters of the declaration. 410 unsigned numFormalParams; 411 412 // The kind of declaration. This is also an index into a %select in 413 // the diagnostic. 414 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 415 416 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 417 numFormalParams = MD->param_size(); 418 calleeType = CT_Method; 419 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 420 numFormalParams = FD->param_size(); 421 calleeType = CT_Function; 422 } else if (isa<VarDecl>(D)) { 423 QualType type = cast<ValueDecl>(D)->getType(); 424 const FunctionType *fn = nullptr; 425 if (const PointerType *ptr = type->getAs<PointerType>()) { 426 fn = ptr->getPointeeType()->getAs<FunctionType>(); 427 if (!fn) return; 428 calleeType = CT_Function; 429 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 430 fn = ptr->getPointeeType()->castAs<FunctionType>(); 431 calleeType = CT_Block; 432 } else { 433 return; 434 } 435 436 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 437 numFormalParams = proto->getNumParams(); 438 } else { 439 numFormalParams = 0; 440 } 441 } else { 442 return; 443 } 444 445 // "nullPos" is the number of formal parameters at the end which 446 // effectively count as part of the variadic arguments. This is 447 // useful if you would prefer to not have *any* formal parameters, 448 // but the language forces you to have at least one. 449 unsigned nullPos = attr->getNullPos(); 450 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 451 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 452 453 // The number of arguments which should follow the sentinel. 454 unsigned numArgsAfterSentinel = attr->getSentinel(); 455 456 // If there aren't enough arguments for all the formal parameters, 457 // the sentinel, and the args after the sentinel, complain. 458 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 459 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 460 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 461 return; 462 } 463 464 // Otherwise, find the sentinel expression. 465 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 466 if (!sentinelExpr) return; 467 if (sentinelExpr->isValueDependent()) return; 468 if (Context.isSentinelNullExpr(sentinelExpr)) return; 469 470 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 471 // or 'NULL' if those are actually defined in the context. Only use 472 // 'nil' for ObjC methods, where it's much more likely that the 473 // variadic arguments form a list of object pointers. 474 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 475 std::string NullValue; 476 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 477 NullValue = "nil"; 478 else if (getLangOpts().CPlusPlus11) 479 NullValue = "nullptr"; 480 else if (PP.isMacroDefined("NULL")) 481 NullValue = "NULL"; 482 else 483 NullValue = "(void*) 0"; 484 485 if (MissingNilLoc.isInvalid()) 486 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 487 else 488 Diag(MissingNilLoc, diag::warn_missing_sentinel) 489 << int(calleeType) 490 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 491 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 492 } 493 494 SourceRange Sema::getExprRange(Expr *E) const { 495 return E ? E->getSourceRange() : SourceRange(); 496 } 497 498 //===----------------------------------------------------------------------===// 499 // Standard Promotions and Conversions 500 //===----------------------------------------------------------------------===// 501 502 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 503 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 504 // Handle any placeholder expressions which made it here. 505 if (E->getType()->isPlaceholderType()) { 506 ExprResult result = CheckPlaceholderExpr(E); 507 if (result.isInvalid()) return ExprError(); 508 E = result.get(); 509 } 510 511 QualType Ty = E->getType(); 512 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 513 514 if (Ty->isFunctionType()) { 515 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 516 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 517 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 518 return ExprError(); 519 520 E = ImpCastExprToType(E, Context.getPointerType(Ty), 521 CK_FunctionToPointerDecay).get(); 522 } else if (Ty->isArrayType()) { 523 // In C90 mode, arrays only promote to pointers if the array expression is 524 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 525 // type 'array of type' is converted to an expression that has type 'pointer 526 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 527 // that has type 'array of type' ...". The relevant change is "an lvalue" 528 // (C90) to "an expression" (C99). 529 // 530 // C++ 4.2p1: 531 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 532 // T" can be converted to an rvalue of type "pointer to T". 533 // 534 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 535 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 536 CK_ArrayToPointerDecay).get(); 537 } 538 return E; 539 } 540 541 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 542 // Check to see if we are dereferencing a null pointer. If so, 543 // and if not volatile-qualified, this is undefined behavior that the 544 // optimizer will delete, so warn about it. People sometimes try to use this 545 // to get a deterministic trap and are surprised by clang's behavior. This 546 // only handles the pattern "*null", which is a very syntactic check. 547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 548 if (UO && UO->getOpcode() == UO_Deref && 549 UO->getSubExpr()->getType()->isPointerType()) { 550 const LangAS AS = 551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 552 if ((!isTargetAddressSpace(AS) || 553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 555 S.Context, Expr::NPC_ValueDependentIsNotNull) && 556 !UO->getType().isVolatileQualified()) { 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::warn_indirection_through_null) 559 << UO->getSubExpr()->getSourceRange()); 560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 561 S.PDiag(diag::note_indirection_through_null)); 562 } 563 } 564 } 565 566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 567 SourceLocation AssignLoc, 568 const Expr* RHS) { 569 const ObjCIvarDecl *IV = OIRE->getDecl(); 570 if (!IV) 571 return; 572 573 DeclarationName MemberName = IV->getDeclName(); 574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 575 if (!Member || !Member->isStr("isa")) 576 return; 577 578 const Expr *Base = OIRE->getBase(); 579 QualType BaseType = Base->getType(); 580 if (OIRE->isArrow()) 581 BaseType = BaseType->getPointeeType(); 582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 584 ObjCInterfaceDecl *ClassDeclared = nullptr; 585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 586 if (!ClassDeclared->getSuperClass() 587 && (*ClassDeclared->ivar_begin()) == IV) { 588 if (RHS) { 589 NamedDecl *ObjectSetClass = 590 S.LookupSingleName(S.TUScope, 591 &S.Context.Idents.get("object_setClass"), 592 SourceLocation(), S.LookupOrdinaryName); 593 if (ObjectSetClass) { 594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 597 "object_setClass(") 598 << FixItHint::CreateReplacement( 599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 600 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 601 } 602 else 603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 604 } else { 605 NamedDecl *ObjectGetClass = 606 S.LookupSingleName(S.TUScope, 607 &S.Context.Idents.get("object_getClass"), 608 SourceLocation(), S.LookupOrdinaryName); 609 if (ObjectGetClass) 610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 612 "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 615 else 616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 617 } 618 S.Diag(IV->getLocation(), diag::note_ivar_decl); 619 } 620 } 621 } 622 623 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 624 // Handle any placeholder expressions which made it here. 625 if (E->getType()->isPlaceholderType()) { 626 ExprResult result = CheckPlaceholderExpr(E); 627 if (result.isInvalid()) return ExprError(); 628 E = result.get(); 629 } 630 631 // C++ [conv.lval]p1: 632 // A glvalue of a non-function, non-array type T can be 633 // converted to a prvalue. 634 if (!E->isGLValue()) return E; 635 636 QualType T = E->getType(); 637 assert(!T.isNull() && "r-value conversion on typeless expression?"); 638 639 // lvalue-to-rvalue conversion cannot be applied to function or array types. 640 if (T->isFunctionType() || T->isArrayType()) 641 return E; 642 643 // We don't want to throw lvalue-to-rvalue casts on top of 644 // expressions of certain types in C++. 645 if (getLangOpts().CPlusPlus && 646 (E->getType() == Context.OverloadTy || 647 T->isDependentType() || 648 T->isRecordType())) 649 return E; 650 651 // The C standard is actually really unclear on this point, and 652 // DR106 tells us what the result should be but not why. It's 653 // generally best to say that void types just doesn't undergo 654 // lvalue-to-rvalue at all. Note that expressions of unqualified 655 // 'void' type are never l-values, but qualified void can be. 656 if (T->isVoidType()) 657 return E; 658 659 // OpenCL usually rejects direct accesses to values of 'half' type. 660 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 661 T->isHalfType()) { 662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 663 << 0 << T; 664 return ExprError(); 665 } 666 667 CheckForNullPointerDereference(*this, E); 668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 670 &Context.Idents.get("object_getClass"), 671 SourceLocation(), LookupOrdinaryName); 672 if (ObjectGetClass) 673 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 675 << FixItHint::CreateReplacement( 676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 677 else 678 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 679 } 680 else if (const ObjCIvarRefExpr *OIRE = 681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 683 684 // C++ [conv.lval]p1: 685 // [...] If T is a non-class type, the type of the prvalue is the 686 // cv-unqualified version of T. Otherwise, the type of the 687 // rvalue is T. 688 // 689 // C99 6.3.2.1p2: 690 // If the lvalue has qualified type, the value has the unqualified 691 // version of the type of the lvalue; otherwise, the value has the 692 // type of the lvalue. 693 if (T.hasQualifiers()) 694 T = T.getUnqualifiedType(); 695 696 // Under the MS ABI, lock down the inheritance model now. 697 if (T->isMemberPointerType() && 698 Context.getTargetInfo().getCXXABI().isMicrosoft()) 699 (void)isCompleteType(E->getExprLoc(), T); 700 701 ExprResult Res = CheckLValueToRValueConversionOperand(E); 702 if (Res.isInvalid()) 703 return Res; 704 E = Res.get(); 705 706 // Loading a __weak object implicitly retains the value, so we need a cleanup to 707 // balance that. 708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 709 Cleanup.setExprNeedsCleanups(true); 710 711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 712 Cleanup.setExprNeedsCleanups(true); 713 714 // C++ [conv.lval]p3: 715 // If T is cv std::nullptr_t, the result is a null pointer constant. 716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 718 CurFPFeatureOverrides()); 719 720 // C11 6.3.2.1p2: 721 // ... if the lvalue has atomic type, the value has the non-atomic version 722 // of the type of the lvalue ... 723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 724 T = Atomic->getValueType().getUnqualifiedType(); 725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 726 nullptr, VK_RValue, FPOptionsOverride()); 727 } 728 729 return Res; 730 } 731 732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 734 if (Res.isInvalid()) 735 return ExprError(); 736 Res = DefaultLvalueConversion(Res.get()); 737 if (Res.isInvalid()) 738 return ExprError(); 739 return Res; 740 } 741 742 /// CallExprUnaryConversions - a special case of an unary conversion 743 /// performed on a function designator of a call expression. 744 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 745 QualType Ty = E->getType(); 746 ExprResult Res = E; 747 // Only do implicit cast for a function type, but not for a pointer 748 // to function type. 749 if (Ty->isFunctionType()) { 750 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 751 CK_FunctionToPointerDecay); 752 if (Res.isInvalid()) 753 return ExprError(); 754 } 755 Res = DefaultLvalueConversion(Res.get()); 756 if (Res.isInvalid()) 757 return ExprError(); 758 return Res.get(); 759 } 760 761 /// UsualUnaryConversions - Performs various conversions that are common to most 762 /// operators (C99 6.3). The conversions of array and function types are 763 /// sometimes suppressed. For example, the array->pointer conversion doesn't 764 /// apply if the array is an argument to the sizeof or address (&) operators. 765 /// In these instances, this routine should *not* be called. 766 ExprResult Sema::UsualUnaryConversions(Expr *E) { 767 // First, convert to an r-value. 768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 769 if (Res.isInvalid()) 770 return ExprError(); 771 E = Res.get(); 772 773 QualType Ty = E->getType(); 774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 775 776 // Half FP have to be promoted to float unless it is natively supported 777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 779 780 // Try to perform integral promotions if the object has a theoretically 781 // promotable type. 782 if (Ty->isIntegralOrUnscopedEnumerationType()) { 783 // C99 6.3.1.1p2: 784 // 785 // The following may be used in an expression wherever an int or 786 // unsigned int may be used: 787 // - an object or expression with an integer type whose integer 788 // conversion rank is less than or equal to the rank of int 789 // and unsigned int. 790 // - A bit-field of type _Bool, int, signed int, or unsigned int. 791 // 792 // If an int can represent all values of the original type, the 793 // value is converted to an int; otherwise, it is converted to an 794 // unsigned int. These are called the integer promotions. All 795 // other types are unchanged by the integer promotions. 796 797 QualType PTy = Context.isPromotableBitField(E); 798 if (!PTy.isNull()) { 799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 800 return E; 801 } 802 if (Ty->isPromotableIntegerType()) { 803 QualType PT = Context.getPromotedIntegerType(Ty); 804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 805 return E; 806 } 807 } 808 return E; 809 } 810 811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 812 /// do not have a prototype. Arguments that have type float or __fp16 813 /// are promoted to double. All other argument types are converted by 814 /// UsualUnaryConversions(). 815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 816 QualType Ty = E->getType(); 817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 818 819 ExprResult Res = UsualUnaryConversions(E); 820 if (Res.isInvalid()) 821 return ExprError(); 822 E = Res.get(); 823 824 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 825 // promote to double. 826 // Note that default argument promotion applies only to float (and 827 // half/fp16); it does not apply to _Float16. 828 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 829 if (BTy && (BTy->getKind() == BuiltinType::Half || 830 BTy->getKind() == BuiltinType::Float)) { 831 if (getLangOpts().OpenCL && 832 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 833 if (BTy->getKind() == BuiltinType::Half) { 834 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 835 } 836 } else { 837 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 838 } 839 } 840 841 // C++ performs lvalue-to-rvalue conversion as a default argument 842 // promotion, even on class types, but note: 843 // C++11 [conv.lval]p2: 844 // When an lvalue-to-rvalue conversion occurs in an unevaluated 845 // operand or a subexpression thereof the value contained in the 846 // referenced object is not accessed. Otherwise, if the glvalue 847 // has a class type, the conversion copy-initializes a temporary 848 // of type T from the glvalue and the result of the conversion 849 // is a prvalue for the temporary. 850 // FIXME: add some way to gate this entire thing for correctness in 851 // potentially potentially evaluated contexts. 852 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 853 ExprResult Temp = PerformCopyInitialization( 854 InitializedEntity::InitializeTemporary(E->getType()), 855 E->getExprLoc(), E); 856 if (Temp.isInvalid()) 857 return ExprError(); 858 E = Temp.get(); 859 } 860 861 return E; 862 } 863 864 /// Determine the degree of POD-ness for an expression. 865 /// Incomplete types are considered POD, since this check can be performed 866 /// when we're in an unevaluated context. 867 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 868 if (Ty->isIncompleteType()) { 869 // C++11 [expr.call]p7: 870 // After these conversions, if the argument does not have arithmetic, 871 // enumeration, pointer, pointer to member, or class type, the program 872 // is ill-formed. 873 // 874 // Since we've already performed array-to-pointer and function-to-pointer 875 // decay, the only such type in C++ is cv void. This also handles 876 // initializer lists as variadic arguments. 877 if (Ty->isVoidType()) 878 return VAK_Invalid; 879 880 if (Ty->isObjCObjectType()) 881 return VAK_Invalid; 882 return VAK_Valid; 883 } 884 885 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 886 return VAK_Invalid; 887 888 if (Ty.isCXX98PODType(Context)) 889 return VAK_Valid; 890 891 // C++11 [expr.call]p7: 892 // Passing a potentially-evaluated argument of class type (Clause 9) 893 // having a non-trivial copy constructor, a non-trivial move constructor, 894 // or a non-trivial destructor, with no corresponding parameter, 895 // is conditionally-supported with implementation-defined semantics. 896 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 897 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 898 if (!Record->hasNonTrivialCopyConstructor() && 899 !Record->hasNonTrivialMoveConstructor() && 900 !Record->hasNonTrivialDestructor()) 901 return VAK_ValidInCXX11; 902 903 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 904 return VAK_Valid; 905 906 if (Ty->isObjCObjectType()) 907 return VAK_Invalid; 908 909 if (getLangOpts().MSVCCompat) 910 return VAK_MSVCUndefined; 911 912 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 913 // permitted to reject them. We should consider doing so. 914 return VAK_Undefined; 915 } 916 917 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 918 // Don't allow one to pass an Objective-C interface to a vararg. 919 const QualType &Ty = E->getType(); 920 VarArgKind VAK = isValidVarArgType(Ty); 921 922 // Complain about passing non-POD types through varargs. 923 switch (VAK) { 924 case VAK_ValidInCXX11: 925 DiagRuntimeBehavior( 926 E->getBeginLoc(), nullptr, 927 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 928 LLVM_FALLTHROUGH; 929 case VAK_Valid: 930 if (Ty->isRecordType()) { 931 // This is unlikely to be what the user intended. If the class has a 932 // 'c_str' member function, the user probably meant to call that. 933 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 934 PDiag(diag::warn_pass_class_arg_to_vararg) 935 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 936 } 937 break; 938 939 case VAK_Undefined: 940 case VAK_MSVCUndefined: 941 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 942 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 943 << getLangOpts().CPlusPlus11 << Ty << CT); 944 break; 945 946 case VAK_Invalid: 947 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 948 Diag(E->getBeginLoc(), 949 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 950 << Ty << CT; 951 else if (Ty->isObjCObjectType()) 952 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 953 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 954 << Ty << CT); 955 else 956 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 957 << isa<InitListExpr>(E) << Ty << CT; 958 break; 959 } 960 } 961 962 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 963 /// will create a trap if the resulting type is not a POD type. 964 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 965 FunctionDecl *FDecl) { 966 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 967 // Strip the unbridged-cast placeholder expression off, if applicable. 968 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 969 (CT == VariadicMethod || 970 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 971 E = stripARCUnbridgedCast(E); 972 973 // Otherwise, do normal placeholder checking. 974 } else { 975 ExprResult ExprRes = CheckPlaceholderExpr(E); 976 if (ExprRes.isInvalid()) 977 return ExprError(); 978 E = ExprRes.get(); 979 } 980 } 981 982 ExprResult ExprRes = DefaultArgumentPromotion(E); 983 if (ExprRes.isInvalid()) 984 return ExprError(); 985 986 // Copy blocks to the heap. 987 if (ExprRes.get()->getType()->isBlockPointerType()) 988 maybeExtendBlockObject(ExprRes); 989 990 E = ExprRes.get(); 991 992 // Diagnostics regarding non-POD argument types are 993 // emitted along with format string checking in Sema::CheckFunctionCall(). 994 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 995 // Turn this into a trap. 996 CXXScopeSpec SS; 997 SourceLocation TemplateKWLoc; 998 UnqualifiedId Name; 999 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1000 E->getBeginLoc()); 1001 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1002 /*HasTrailingLParen=*/true, 1003 /*IsAddressOfOperand=*/false); 1004 if (TrapFn.isInvalid()) 1005 return ExprError(); 1006 1007 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1008 None, E->getEndLoc()); 1009 if (Call.isInvalid()) 1010 return ExprError(); 1011 1012 ExprResult Comma = 1013 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1014 if (Comma.isInvalid()) 1015 return ExprError(); 1016 return Comma.get(); 1017 } 1018 1019 if (!getLangOpts().CPlusPlus && 1020 RequireCompleteType(E->getExprLoc(), E->getType(), 1021 diag::err_call_incomplete_argument)) 1022 return ExprError(); 1023 1024 return E; 1025 } 1026 1027 /// Converts an integer to complex float type. Helper function of 1028 /// UsualArithmeticConversions() 1029 /// 1030 /// \return false if the integer expression is an integer type and is 1031 /// successfully converted to the complex type. 1032 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1033 ExprResult &ComplexExpr, 1034 QualType IntTy, 1035 QualType ComplexTy, 1036 bool SkipCast) { 1037 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1038 if (SkipCast) return false; 1039 if (IntTy->isIntegerType()) { 1040 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1041 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1042 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1043 CK_FloatingRealToComplex); 1044 } else { 1045 assert(IntTy->isComplexIntegerType()); 1046 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1047 CK_IntegralComplexToFloatingComplex); 1048 } 1049 return false; 1050 } 1051 1052 /// Handle arithmetic conversion with complex types. Helper function of 1053 /// UsualArithmeticConversions() 1054 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1055 ExprResult &RHS, QualType LHSType, 1056 QualType RHSType, 1057 bool IsCompAssign) { 1058 // if we have an integer operand, the result is the complex type. 1059 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1060 /*skipCast*/false)) 1061 return LHSType; 1062 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1063 /*skipCast*/IsCompAssign)) 1064 return RHSType; 1065 1066 // This handles complex/complex, complex/float, or float/complex. 1067 // When both operands are complex, the shorter operand is converted to the 1068 // type of the longer, and that is the type of the result. This corresponds 1069 // to what is done when combining two real floating-point operands. 1070 // The fun begins when size promotion occur across type domains. 1071 // From H&S 6.3.4: When one operand is complex and the other is a real 1072 // floating-point type, the less precise type is converted, within it's 1073 // real or complex domain, to the precision of the other type. For example, 1074 // when combining a "long double" with a "double _Complex", the 1075 // "double _Complex" is promoted to "long double _Complex". 1076 1077 // Compute the rank of the two types, regardless of whether they are complex. 1078 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1079 1080 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1081 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1082 QualType LHSElementType = 1083 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1084 QualType RHSElementType = 1085 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1086 1087 QualType ResultType = S.Context.getComplexType(LHSElementType); 1088 if (Order < 0) { 1089 // Promote the precision of the LHS if not an assignment. 1090 ResultType = S.Context.getComplexType(RHSElementType); 1091 if (!IsCompAssign) { 1092 if (LHSComplexType) 1093 LHS = 1094 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1095 else 1096 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1097 } 1098 } else if (Order > 0) { 1099 // Promote the precision of the RHS. 1100 if (RHSComplexType) 1101 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1102 else 1103 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1104 } 1105 return ResultType; 1106 } 1107 1108 /// Handle arithmetic conversion from integer to float. Helper function 1109 /// of UsualArithmeticConversions() 1110 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1111 ExprResult &IntExpr, 1112 QualType FloatTy, QualType IntTy, 1113 bool ConvertFloat, bool ConvertInt) { 1114 if (IntTy->isIntegerType()) { 1115 if (ConvertInt) 1116 // Convert intExpr to the lhs floating point type. 1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1118 CK_IntegralToFloating); 1119 return FloatTy; 1120 } 1121 1122 // Convert both sides to the appropriate complex float. 1123 assert(IntTy->isComplexIntegerType()); 1124 QualType result = S.Context.getComplexType(FloatTy); 1125 1126 // _Complex int -> _Complex float 1127 if (ConvertInt) 1128 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1129 CK_IntegralComplexToFloatingComplex); 1130 1131 // float -> _Complex float 1132 if (ConvertFloat) 1133 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1134 CK_FloatingRealToComplex); 1135 1136 return result; 1137 } 1138 1139 /// Handle arithmethic conversion with floating point types. Helper 1140 /// function of UsualArithmeticConversions() 1141 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1142 ExprResult &RHS, QualType LHSType, 1143 QualType RHSType, bool IsCompAssign) { 1144 bool LHSFloat = LHSType->isRealFloatingType(); 1145 bool RHSFloat = RHSType->isRealFloatingType(); 1146 1147 // N1169 4.1.4: If one of the operands has a floating type and the other 1148 // operand has a fixed-point type, the fixed-point operand 1149 // is converted to the floating type [...] 1150 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1151 if (LHSFloat) 1152 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1153 else if (!IsCompAssign) 1154 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1155 return LHSFloat ? LHSType : RHSType; 1156 } 1157 1158 // If we have two real floating types, convert the smaller operand 1159 // to the bigger result. 1160 if (LHSFloat && RHSFloat) { 1161 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1162 if (order > 0) { 1163 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1164 return LHSType; 1165 } 1166 1167 assert(order < 0 && "illegal float comparison"); 1168 if (!IsCompAssign) 1169 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1170 return RHSType; 1171 } 1172 1173 if (LHSFloat) { 1174 // Half FP has to be promoted to float unless it is natively supported 1175 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1176 LHSType = S.Context.FloatTy; 1177 1178 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1179 /*ConvertFloat=*/!IsCompAssign, 1180 /*ConvertInt=*/ true); 1181 } 1182 assert(RHSFloat); 1183 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1184 /*ConvertFloat=*/ true, 1185 /*ConvertInt=*/!IsCompAssign); 1186 } 1187 1188 /// Diagnose attempts to convert between __float128 and long double if 1189 /// there is no support for such conversion. Helper function of 1190 /// UsualArithmeticConversions(). 1191 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1192 QualType RHSType) { 1193 /* No issue converting if at least one of the types is not a floating point 1194 type or the two types have the same rank. 1195 */ 1196 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1197 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1198 return false; 1199 1200 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1201 "The remaining types must be floating point types."); 1202 1203 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1204 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1205 1206 QualType LHSElemType = LHSComplex ? 1207 LHSComplex->getElementType() : LHSType; 1208 QualType RHSElemType = RHSComplex ? 1209 RHSComplex->getElementType() : RHSType; 1210 1211 // No issue if the two types have the same representation 1212 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1213 &S.Context.getFloatTypeSemantics(RHSElemType)) 1214 return false; 1215 1216 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1217 RHSElemType == S.Context.LongDoubleTy); 1218 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1219 RHSElemType == S.Context.Float128Ty); 1220 1221 // We've handled the situation where __float128 and long double have the same 1222 // representation. We allow all conversions for all possible long double types 1223 // except PPC's double double. 1224 return Float128AndLongDouble && 1225 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1226 &llvm::APFloat::PPCDoubleDouble()); 1227 } 1228 1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1230 1231 namespace { 1232 /// These helper callbacks are placed in an anonymous namespace to 1233 /// permit their use as function template parameters. 1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1235 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1236 } 1237 1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1239 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1240 CK_IntegralComplexCast); 1241 } 1242 } 1243 1244 /// Handle integer arithmetic conversions. Helper function of 1245 /// UsualArithmeticConversions() 1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1248 ExprResult &RHS, QualType LHSType, 1249 QualType RHSType, bool IsCompAssign) { 1250 // The rules for this case are in C99 6.3.1.8 1251 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1252 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1253 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1254 if (LHSSigned == RHSSigned) { 1255 // Same signedness; use the higher-ranked type 1256 if (order >= 0) { 1257 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1258 return LHSType; 1259 } else if (!IsCompAssign) 1260 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1261 return RHSType; 1262 } else if (order != (LHSSigned ? 1 : -1)) { 1263 // The unsigned type has greater than or equal rank to the 1264 // signed type, so use the unsigned type 1265 if (RHSSigned) { 1266 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1267 return LHSType; 1268 } else if (!IsCompAssign) 1269 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1270 return RHSType; 1271 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1272 // The two types are different widths; if we are here, that 1273 // means the signed type is larger than the unsigned type, so 1274 // use the signed type. 1275 if (LHSSigned) { 1276 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1277 return LHSType; 1278 } else if (!IsCompAssign) 1279 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1280 return RHSType; 1281 } else { 1282 // The signed type is higher-ranked than the unsigned type, 1283 // but isn't actually any bigger (like unsigned int and long 1284 // on most 32-bit systems). Use the unsigned type corresponding 1285 // to the signed type. 1286 QualType result = 1287 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1288 RHS = (*doRHSCast)(S, RHS.get(), result); 1289 if (!IsCompAssign) 1290 LHS = (*doLHSCast)(S, LHS.get(), result); 1291 return result; 1292 } 1293 } 1294 1295 /// Handle conversions with GCC complex int extension. Helper function 1296 /// of UsualArithmeticConversions() 1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1298 ExprResult &RHS, QualType LHSType, 1299 QualType RHSType, 1300 bool IsCompAssign) { 1301 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1302 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1303 1304 if (LHSComplexInt && RHSComplexInt) { 1305 QualType LHSEltType = LHSComplexInt->getElementType(); 1306 QualType RHSEltType = RHSComplexInt->getElementType(); 1307 QualType ScalarType = 1308 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1309 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1310 1311 return S.Context.getComplexType(ScalarType); 1312 } 1313 1314 if (LHSComplexInt) { 1315 QualType LHSEltType = LHSComplexInt->getElementType(); 1316 QualType ScalarType = 1317 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1318 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1319 QualType ComplexType = S.Context.getComplexType(ScalarType); 1320 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1321 CK_IntegralRealToComplex); 1322 1323 return ComplexType; 1324 } 1325 1326 assert(RHSComplexInt); 1327 1328 QualType RHSEltType = RHSComplexInt->getElementType(); 1329 QualType ScalarType = 1330 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1331 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1332 QualType ComplexType = S.Context.getComplexType(ScalarType); 1333 1334 if (!IsCompAssign) 1335 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1336 CK_IntegralRealToComplex); 1337 return ComplexType; 1338 } 1339 1340 /// Return the rank of a given fixed point or integer type. The value itself 1341 /// doesn't matter, but the values must be increasing with proper increasing 1342 /// rank as described in N1169 4.1.1. 1343 static unsigned GetFixedPointRank(QualType Ty) { 1344 const auto *BTy = Ty->getAs<BuiltinType>(); 1345 assert(BTy && "Expected a builtin type."); 1346 1347 switch (BTy->getKind()) { 1348 case BuiltinType::ShortFract: 1349 case BuiltinType::UShortFract: 1350 case BuiltinType::SatShortFract: 1351 case BuiltinType::SatUShortFract: 1352 return 1; 1353 case BuiltinType::Fract: 1354 case BuiltinType::UFract: 1355 case BuiltinType::SatFract: 1356 case BuiltinType::SatUFract: 1357 return 2; 1358 case BuiltinType::LongFract: 1359 case BuiltinType::ULongFract: 1360 case BuiltinType::SatLongFract: 1361 case BuiltinType::SatULongFract: 1362 return 3; 1363 case BuiltinType::ShortAccum: 1364 case BuiltinType::UShortAccum: 1365 case BuiltinType::SatShortAccum: 1366 case BuiltinType::SatUShortAccum: 1367 return 4; 1368 case BuiltinType::Accum: 1369 case BuiltinType::UAccum: 1370 case BuiltinType::SatAccum: 1371 case BuiltinType::SatUAccum: 1372 return 5; 1373 case BuiltinType::LongAccum: 1374 case BuiltinType::ULongAccum: 1375 case BuiltinType::SatLongAccum: 1376 case BuiltinType::SatULongAccum: 1377 return 6; 1378 default: 1379 if (BTy->isInteger()) 1380 return 0; 1381 llvm_unreachable("Unexpected fixed point or integer type"); 1382 } 1383 } 1384 1385 /// handleFixedPointConversion - Fixed point operations between fixed 1386 /// point types and integers or other fixed point types do not fall under 1387 /// usual arithmetic conversion since these conversions could result in loss 1388 /// of precsision (N1169 4.1.4). These operations should be calculated with 1389 /// the full precision of their result type (N1169 4.1.6.2.1). 1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1391 QualType RHSTy) { 1392 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1393 "Expected at least one of the operands to be a fixed point type"); 1394 assert((LHSTy->isFixedPointOrIntegerType() || 1395 RHSTy->isFixedPointOrIntegerType()) && 1396 "Special fixed point arithmetic operation conversions are only " 1397 "applied to ints or other fixed point types"); 1398 1399 // If one operand has signed fixed-point type and the other operand has 1400 // unsigned fixed-point type, then the unsigned fixed-point operand is 1401 // converted to its corresponding signed fixed-point type and the resulting 1402 // type is the type of the converted operand. 1403 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1404 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1405 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1406 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1407 1408 // The result type is the type with the highest rank, whereby a fixed-point 1409 // conversion rank is always greater than an integer conversion rank; if the 1410 // type of either of the operands is a saturating fixedpoint type, the result 1411 // type shall be the saturating fixed-point type corresponding to the type 1412 // with the highest rank; the resulting value is converted (taking into 1413 // account rounding and overflow) to the precision of the resulting type. 1414 // Same ranks between signed and unsigned types are resolved earlier, so both 1415 // types are either signed or both unsigned at this point. 1416 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1417 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1418 1419 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1420 1421 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1422 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1423 1424 return ResultTy; 1425 } 1426 1427 /// Check that the usual arithmetic conversions can be performed on this pair of 1428 /// expressions that might be of enumeration type. 1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1430 SourceLocation Loc, 1431 Sema::ArithConvKind ACK) { 1432 // C++2a [expr.arith.conv]p1: 1433 // If one operand is of enumeration type and the other operand is of a 1434 // different enumeration type or a floating-point type, this behavior is 1435 // deprecated ([depr.arith.conv.enum]). 1436 // 1437 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1438 // Eventually we will presumably reject these cases (in C++23 onwards?). 1439 QualType L = LHS->getType(), R = RHS->getType(); 1440 bool LEnum = L->isUnscopedEnumerationType(), 1441 REnum = R->isUnscopedEnumerationType(); 1442 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1443 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1444 (REnum && L->isFloatingType())) { 1445 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1446 ? diag::warn_arith_conv_enum_float_cxx20 1447 : diag::warn_arith_conv_enum_float) 1448 << LHS->getSourceRange() << RHS->getSourceRange() 1449 << (int)ACK << LEnum << L << R; 1450 } else if (!IsCompAssign && LEnum && REnum && 1451 !S.Context.hasSameUnqualifiedType(L, R)) { 1452 unsigned DiagID; 1453 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1454 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1455 // If either enumeration type is unnamed, it's less likely that the 1456 // user cares about this, but this situation is still deprecated in 1457 // C++2a. Use a different warning group. 1458 DiagID = S.getLangOpts().CPlusPlus20 1459 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1460 : diag::warn_arith_conv_mixed_anon_enum_types; 1461 } else if (ACK == Sema::ACK_Conditional) { 1462 // Conditional expressions are separated out because they have 1463 // historically had a different warning flag. 1464 DiagID = S.getLangOpts().CPlusPlus20 1465 ? diag::warn_conditional_mixed_enum_types_cxx20 1466 : diag::warn_conditional_mixed_enum_types; 1467 } else if (ACK == Sema::ACK_Comparison) { 1468 // Comparison expressions are separated out because they have 1469 // historically had a different warning flag. 1470 DiagID = S.getLangOpts().CPlusPlus20 1471 ? diag::warn_comparison_mixed_enum_types_cxx20 1472 : diag::warn_comparison_mixed_enum_types; 1473 } else { 1474 DiagID = S.getLangOpts().CPlusPlus20 1475 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1476 : diag::warn_arith_conv_mixed_enum_types; 1477 } 1478 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1479 << (int)ACK << L << R; 1480 } 1481 } 1482 1483 /// UsualArithmeticConversions - Performs various conversions that are common to 1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1485 /// routine returns the first non-arithmetic type found. The client is 1486 /// responsible for emitting appropriate error diagnostics. 1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1488 SourceLocation Loc, 1489 ArithConvKind ACK) { 1490 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1491 1492 if (ACK != ACK_CompAssign) { 1493 LHS = UsualUnaryConversions(LHS.get()); 1494 if (LHS.isInvalid()) 1495 return QualType(); 1496 } 1497 1498 RHS = UsualUnaryConversions(RHS.get()); 1499 if (RHS.isInvalid()) 1500 return QualType(); 1501 1502 // For conversion purposes, we ignore any qualifiers. 1503 // For example, "const float" and "float" are equivalent. 1504 QualType LHSType = 1505 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1506 QualType RHSType = 1507 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1508 1509 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1510 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1511 LHSType = AtomicLHS->getValueType(); 1512 1513 // If both types are identical, no conversion is needed. 1514 if (LHSType == RHSType) 1515 return LHSType; 1516 1517 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1518 // The caller can deal with this (e.g. pointer + int). 1519 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1520 return QualType(); 1521 1522 // Apply unary and bitfield promotions to the LHS's type. 1523 QualType LHSUnpromotedType = LHSType; 1524 if (LHSType->isPromotableIntegerType()) 1525 LHSType = Context.getPromotedIntegerType(LHSType); 1526 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1527 if (!LHSBitfieldPromoteTy.isNull()) 1528 LHSType = LHSBitfieldPromoteTy; 1529 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1530 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1531 1532 // If both types are identical, no conversion is needed. 1533 if (LHSType == RHSType) 1534 return LHSType; 1535 1536 // ExtInt types aren't subject to conversions between them or normal integers, 1537 // so this fails. 1538 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1539 return QualType(); 1540 1541 // At this point, we have two different arithmetic types. 1542 1543 // Diagnose attempts to convert between __float128 and long double where 1544 // such conversions currently can't be handled. 1545 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1546 return QualType(); 1547 1548 // Handle complex types first (C99 6.3.1.8p1). 1549 if (LHSType->isComplexType() || RHSType->isComplexType()) 1550 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1551 ACK == ACK_CompAssign); 1552 1553 // Now handle "real" floating types (i.e. float, double, long double). 1554 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1555 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1556 ACK == ACK_CompAssign); 1557 1558 // Handle GCC complex int extension. 1559 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1560 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1561 ACK == ACK_CompAssign); 1562 1563 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1564 return handleFixedPointConversion(*this, LHSType, RHSType); 1565 1566 // Finally, we have two differing integer types. 1567 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1568 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1569 } 1570 1571 //===----------------------------------------------------------------------===// 1572 // Semantic Analysis for various Expression Types 1573 //===----------------------------------------------------------------------===// 1574 1575 1576 ExprResult 1577 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1578 SourceLocation DefaultLoc, 1579 SourceLocation RParenLoc, 1580 Expr *ControllingExpr, 1581 ArrayRef<ParsedType> ArgTypes, 1582 ArrayRef<Expr *> ArgExprs) { 1583 unsigned NumAssocs = ArgTypes.size(); 1584 assert(NumAssocs == ArgExprs.size()); 1585 1586 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1587 for (unsigned i = 0; i < NumAssocs; ++i) { 1588 if (ArgTypes[i]) 1589 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1590 else 1591 Types[i] = nullptr; 1592 } 1593 1594 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1595 ControllingExpr, 1596 llvm::makeArrayRef(Types, NumAssocs), 1597 ArgExprs); 1598 delete [] Types; 1599 return ER; 1600 } 1601 1602 ExprResult 1603 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1604 SourceLocation DefaultLoc, 1605 SourceLocation RParenLoc, 1606 Expr *ControllingExpr, 1607 ArrayRef<TypeSourceInfo *> Types, 1608 ArrayRef<Expr *> Exprs) { 1609 unsigned NumAssocs = Types.size(); 1610 assert(NumAssocs == Exprs.size()); 1611 1612 // Decay and strip qualifiers for the controlling expression type, and handle 1613 // placeholder type replacement. See committee discussion from WG14 DR423. 1614 { 1615 EnterExpressionEvaluationContext Unevaluated( 1616 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1617 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1618 if (R.isInvalid()) 1619 return ExprError(); 1620 ControllingExpr = R.get(); 1621 } 1622 1623 // The controlling expression is an unevaluated operand, so side effects are 1624 // likely unintended. 1625 if (!inTemplateInstantiation() && 1626 ControllingExpr->HasSideEffects(Context, false)) 1627 Diag(ControllingExpr->getExprLoc(), 1628 diag::warn_side_effects_unevaluated_context); 1629 1630 bool TypeErrorFound = false, 1631 IsResultDependent = ControllingExpr->isTypeDependent(), 1632 ContainsUnexpandedParameterPack 1633 = ControllingExpr->containsUnexpandedParameterPack(); 1634 1635 for (unsigned i = 0; i < NumAssocs; ++i) { 1636 if (Exprs[i]->containsUnexpandedParameterPack()) 1637 ContainsUnexpandedParameterPack = true; 1638 1639 if (Types[i]) { 1640 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1641 ContainsUnexpandedParameterPack = true; 1642 1643 if (Types[i]->getType()->isDependentType()) { 1644 IsResultDependent = true; 1645 } else { 1646 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1647 // complete object type other than a variably modified type." 1648 unsigned D = 0; 1649 if (Types[i]->getType()->isIncompleteType()) 1650 D = diag::err_assoc_type_incomplete; 1651 else if (!Types[i]->getType()->isObjectType()) 1652 D = diag::err_assoc_type_nonobject; 1653 else if (Types[i]->getType()->isVariablyModifiedType()) 1654 D = diag::err_assoc_type_variably_modified; 1655 1656 if (D != 0) { 1657 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1658 << Types[i]->getTypeLoc().getSourceRange() 1659 << Types[i]->getType(); 1660 TypeErrorFound = true; 1661 } 1662 1663 // C11 6.5.1.1p2 "No two generic associations in the same generic 1664 // selection shall specify compatible types." 1665 for (unsigned j = i+1; j < NumAssocs; ++j) 1666 if (Types[j] && !Types[j]->getType()->isDependentType() && 1667 Context.typesAreCompatible(Types[i]->getType(), 1668 Types[j]->getType())) { 1669 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1670 diag::err_assoc_compatible_types) 1671 << Types[j]->getTypeLoc().getSourceRange() 1672 << Types[j]->getType() 1673 << Types[i]->getType(); 1674 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1675 diag::note_compat_assoc) 1676 << Types[i]->getTypeLoc().getSourceRange() 1677 << Types[i]->getType(); 1678 TypeErrorFound = true; 1679 } 1680 } 1681 } 1682 } 1683 if (TypeErrorFound) 1684 return ExprError(); 1685 1686 // If we determined that the generic selection is result-dependent, don't 1687 // try to compute the result expression. 1688 if (IsResultDependent) 1689 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1690 Exprs, DefaultLoc, RParenLoc, 1691 ContainsUnexpandedParameterPack); 1692 1693 SmallVector<unsigned, 1> CompatIndices; 1694 unsigned DefaultIndex = -1U; 1695 for (unsigned i = 0; i < NumAssocs; ++i) { 1696 if (!Types[i]) 1697 DefaultIndex = i; 1698 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1699 Types[i]->getType())) 1700 CompatIndices.push_back(i); 1701 } 1702 1703 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1704 // type compatible with at most one of the types named in its generic 1705 // association list." 1706 if (CompatIndices.size() > 1) { 1707 // We strip parens here because the controlling expression is typically 1708 // parenthesized in macro definitions. 1709 ControllingExpr = ControllingExpr->IgnoreParens(); 1710 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1711 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1712 << (unsigned)CompatIndices.size(); 1713 for (unsigned I : CompatIndices) { 1714 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1715 diag::note_compat_assoc) 1716 << Types[I]->getTypeLoc().getSourceRange() 1717 << Types[I]->getType(); 1718 } 1719 return ExprError(); 1720 } 1721 1722 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1723 // its controlling expression shall have type compatible with exactly one of 1724 // the types named in its generic association list." 1725 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1726 // We strip parens here because the controlling expression is typically 1727 // parenthesized in macro definitions. 1728 ControllingExpr = ControllingExpr->IgnoreParens(); 1729 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1730 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1731 return ExprError(); 1732 } 1733 1734 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1735 // type name that is compatible with the type of the controlling expression, 1736 // then the result expression of the generic selection is the expression 1737 // in that generic association. Otherwise, the result expression of the 1738 // generic selection is the expression in the default generic association." 1739 unsigned ResultIndex = 1740 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1741 1742 return GenericSelectionExpr::Create( 1743 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1744 ContainsUnexpandedParameterPack, ResultIndex); 1745 } 1746 1747 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1748 /// location of the token and the offset of the ud-suffix within it. 1749 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1750 unsigned Offset) { 1751 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1752 S.getLangOpts()); 1753 } 1754 1755 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1756 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1757 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1758 IdentifierInfo *UDSuffix, 1759 SourceLocation UDSuffixLoc, 1760 ArrayRef<Expr*> Args, 1761 SourceLocation LitEndLoc) { 1762 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1763 1764 QualType ArgTy[2]; 1765 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1766 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1767 if (ArgTy[ArgIdx]->isArrayType()) 1768 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1769 } 1770 1771 DeclarationName OpName = 1772 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1773 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1774 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1775 1776 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1777 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1778 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1779 /*AllowStringTemplatePack*/ false, 1780 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1781 return ExprError(); 1782 1783 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1784 } 1785 1786 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1787 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1788 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1789 /// multiple tokens. However, the common case is that StringToks points to one 1790 /// string. 1791 /// 1792 ExprResult 1793 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1794 assert(!StringToks.empty() && "Must have at least one string!"); 1795 1796 StringLiteralParser Literal(StringToks, PP); 1797 if (Literal.hadError) 1798 return ExprError(); 1799 1800 SmallVector<SourceLocation, 4> StringTokLocs; 1801 for (const Token &Tok : StringToks) 1802 StringTokLocs.push_back(Tok.getLocation()); 1803 1804 QualType CharTy = Context.CharTy; 1805 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1806 if (Literal.isWide()) { 1807 CharTy = Context.getWideCharType(); 1808 Kind = StringLiteral::Wide; 1809 } else if (Literal.isUTF8()) { 1810 if (getLangOpts().Char8) 1811 CharTy = Context.Char8Ty; 1812 Kind = StringLiteral::UTF8; 1813 } else if (Literal.isUTF16()) { 1814 CharTy = Context.Char16Ty; 1815 Kind = StringLiteral::UTF16; 1816 } else if (Literal.isUTF32()) { 1817 CharTy = Context.Char32Ty; 1818 Kind = StringLiteral::UTF32; 1819 } else if (Literal.isPascal()) { 1820 CharTy = Context.UnsignedCharTy; 1821 } 1822 1823 // Warn on initializing an array of char from a u8 string literal; this 1824 // becomes ill-formed in C++2a. 1825 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1826 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1827 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1828 1829 // Create removals for all 'u8' prefixes in the string literal(s). This 1830 // ensures C++2a compatibility (but may change the program behavior when 1831 // built by non-Clang compilers for which the execution character set is 1832 // not always UTF-8). 1833 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1834 SourceLocation RemovalDiagLoc; 1835 for (const Token &Tok : StringToks) { 1836 if (Tok.getKind() == tok::utf8_string_literal) { 1837 if (RemovalDiagLoc.isInvalid()) 1838 RemovalDiagLoc = Tok.getLocation(); 1839 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1840 Tok.getLocation(), 1841 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1842 getSourceManager(), getLangOpts()))); 1843 } 1844 } 1845 Diag(RemovalDiagLoc, RemovalDiag); 1846 } 1847 1848 QualType StrTy = 1849 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1850 1851 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1852 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1853 Kind, Literal.Pascal, StrTy, 1854 &StringTokLocs[0], 1855 StringTokLocs.size()); 1856 if (Literal.getUDSuffix().empty()) 1857 return Lit; 1858 1859 // We're building a user-defined literal. 1860 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1861 SourceLocation UDSuffixLoc = 1862 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1863 Literal.getUDSuffixOffset()); 1864 1865 // Make sure we're allowed user-defined literals here. 1866 if (!UDLScope) 1867 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1868 1869 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1870 // operator "" X (str, len) 1871 QualType SizeType = Context.getSizeType(); 1872 1873 DeclarationName OpName = 1874 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1875 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1876 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1877 1878 QualType ArgTy[] = { 1879 Context.getArrayDecayedType(StrTy), SizeType 1880 }; 1881 1882 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1883 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1884 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1885 /*AllowStringTemplatePack*/ true, 1886 /*DiagnoseMissing*/ true, Lit)) { 1887 1888 case LOLR_Cooked: { 1889 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1890 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1891 StringTokLocs[0]); 1892 Expr *Args[] = { Lit, LenArg }; 1893 1894 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1895 } 1896 1897 case LOLR_Template: { 1898 TemplateArgumentListInfo ExplicitArgs; 1899 TemplateArgument Arg(Lit); 1900 TemplateArgumentLocInfo ArgInfo(Lit); 1901 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1902 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1903 &ExplicitArgs); 1904 } 1905 1906 case LOLR_StringTemplatePack: { 1907 TemplateArgumentListInfo ExplicitArgs; 1908 1909 unsigned CharBits = Context.getIntWidth(CharTy); 1910 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1911 llvm::APSInt Value(CharBits, CharIsUnsigned); 1912 1913 TemplateArgument TypeArg(CharTy); 1914 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1915 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1916 1917 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1918 Value = Lit->getCodeUnit(I); 1919 TemplateArgument Arg(Context, Value, CharTy); 1920 TemplateArgumentLocInfo ArgInfo; 1921 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1922 } 1923 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1924 &ExplicitArgs); 1925 } 1926 case LOLR_Raw: 1927 case LOLR_ErrorNoDiagnostic: 1928 llvm_unreachable("unexpected literal operator lookup result"); 1929 case LOLR_Error: 1930 return ExprError(); 1931 } 1932 llvm_unreachable("unexpected literal operator lookup result"); 1933 } 1934 1935 DeclRefExpr * 1936 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1937 SourceLocation Loc, 1938 const CXXScopeSpec *SS) { 1939 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1940 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1941 } 1942 1943 DeclRefExpr * 1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1945 const DeclarationNameInfo &NameInfo, 1946 const CXXScopeSpec *SS, NamedDecl *FoundD, 1947 SourceLocation TemplateKWLoc, 1948 const TemplateArgumentListInfo *TemplateArgs) { 1949 NestedNameSpecifierLoc NNS = 1950 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1951 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1952 TemplateArgs); 1953 } 1954 1955 // CUDA/HIP: Check whether a captured reference variable is referencing a 1956 // host variable in a device or host device lambda. 1957 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1958 VarDecl *VD) { 1959 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1960 return false; 1961 assert(VD->getType()->isReferenceType()); 1962 1963 // Check whether the reference variable is referencing a host variable. 1964 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1965 if (!DRE) 1966 return false; 1967 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1968 if (!Referee || !Referee->hasGlobalStorage() || 1969 Referee->hasAttr<CUDADeviceAttr>()) 1970 return false; 1971 1972 // Check whether the current function is a device or host device lambda. 1973 // Check whether the reference variable is a capture by getDeclContext() 1974 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1975 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1976 if (MD && MD->getParent()->isLambda() && 1977 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1978 VD->getDeclContext() != MD) 1979 return true; 1980 1981 return false; 1982 } 1983 1984 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1985 // A declaration named in an unevaluated operand never constitutes an odr-use. 1986 if (isUnevaluatedContext()) 1987 return NOUR_Unevaluated; 1988 1989 // C++2a [basic.def.odr]p4: 1990 // A variable x whose name appears as a potentially-evaluated expression e 1991 // is odr-used by e unless [...] x is a reference that is usable in 1992 // constant expressions. 1993 // CUDA/HIP: 1994 // If a reference variable referencing a host variable is captured in a 1995 // device or host device lambda, the value of the referee must be copied 1996 // to the capture and the reference variable must be treated as odr-use 1997 // since the value of the referee is not known at compile time and must 1998 // be loaded from the captured. 1999 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2000 if (VD->getType()->isReferenceType() && 2001 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2002 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2003 VD->isUsableInConstantExpressions(Context)) 2004 return NOUR_Constant; 2005 } 2006 2007 // All remaining non-variable cases constitute an odr-use. For variables, we 2008 // need to wait and see how the expression is used. 2009 return NOUR_None; 2010 } 2011 2012 /// BuildDeclRefExpr - Build an expression that references a 2013 /// declaration that does not require a closure capture. 2014 DeclRefExpr * 2015 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2016 const DeclarationNameInfo &NameInfo, 2017 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2018 SourceLocation TemplateKWLoc, 2019 const TemplateArgumentListInfo *TemplateArgs) { 2020 bool RefersToCapturedVariable = 2021 isa<VarDecl>(D) && 2022 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2023 2024 DeclRefExpr *E = DeclRefExpr::Create( 2025 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2026 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2027 MarkDeclRefReferenced(E); 2028 2029 // C++ [except.spec]p17: 2030 // An exception-specification is considered to be needed when: 2031 // - in an expression, the function is the unique lookup result or 2032 // the selected member of a set of overloaded functions. 2033 // 2034 // We delay doing this until after we've built the function reference and 2035 // marked it as used so that: 2036 // a) if the function is defaulted, we get errors from defining it before / 2037 // instead of errors from computing its exception specification, and 2038 // b) if the function is a defaulted comparison, we can use the body we 2039 // build when defining it as input to the exception specification 2040 // computation rather than computing a new body. 2041 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2042 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2043 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2044 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2045 } 2046 } 2047 2048 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2049 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2050 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2051 getCurFunction()->recordUseOfWeak(E); 2052 2053 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2054 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2055 FD = IFD->getAnonField(); 2056 if (FD) { 2057 UnusedPrivateFields.remove(FD); 2058 // Just in case we're building an illegal pointer-to-member. 2059 if (FD->isBitField()) 2060 E->setObjectKind(OK_BitField); 2061 } 2062 2063 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2064 // designates a bit-field. 2065 if (auto *BD = dyn_cast<BindingDecl>(D)) 2066 if (auto *BE = BD->getBinding()) 2067 E->setObjectKind(BE->getObjectKind()); 2068 2069 return E; 2070 } 2071 2072 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2073 /// possibly a list of template arguments. 2074 /// 2075 /// If this produces template arguments, it is permitted to call 2076 /// DecomposeTemplateName. 2077 /// 2078 /// This actually loses a lot of source location information for 2079 /// non-standard name kinds; we should consider preserving that in 2080 /// some way. 2081 void 2082 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2083 TemplateArgumentListInfo &Buffer, 2084 DeclarationNameInfo &NameInfo, 2085 const TemplateArgumentListInfo *&TemplateArgs) { 2086 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2087 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2088 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2089 2090 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2091 Id.TemplateId->NumArgs); 2092 translateTemplateArguments(TemplateArgsPtr, Buffer); 2093 2094 TemplateName TName = Id.TemplateId->Template.get(); 2095 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2096 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2097 TemplateArgs = &Buffer; 2098 } else { 2099 NameInfo = GetNameFromUnqualifiedId(Id); 2100 TemplateArgs = nullptr; 2101 } 2102 } 2103 2104 static void emitEmptyLookupTypoDiagnostic( 2105 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2106 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2107 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2108 DeclContext *Ctx = 2109 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2110 if (!TC) { 2111 // Emit a special diagnostic for failed member lookups. 2112 // FIXME: computing the declaration context might fail here (?) 2113 if (Ctx) 2114 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2115 << SS.getRange(); 2116 else 2117 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2118 return; 2119 } 2120 2121 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2122 bool DroppedSpecifier = 2123 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2124 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2125 ? diag::note_implicit_param_decl 2126 : diag::note_previous_decl; 2127 if (!Ctx) 2128 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2129 SemaRef.PDiag(NoteID)); 2130 else 2131 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2132 << Typo << Ctx << DroppedSpecifier 2133 << SS.getRange(), 2134 SemaRef.PDiag(NoteID)); 2135 } 2136 2137 /// Diagnose a lookup that found results in an enclosing class during error 2138 /// recovery. This usually indicates that the results were found in a dependent 2139 /// base class that could not be searched as part of a template definition. 2140 /// Always issues a diagnostic (though this may be only a warning in MS 2141 /// compatibility mode). 2142 /// 2143 /// Return \c true if the error is unrecoverable, or \c false if the caller 2144 /// should attempt to recover using these lookup results. 2145 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2146 // During a default argument instantiation the CurContext points 2147 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2148 // function parameter list, hence add an explicit check. 2149 bool isDefaultArgument = 2150 !CodeSynthesisContexts.empty() && 2151 CodeSynthesisContexts.back().Kind == 2152 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2153 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2154 bool isInstance = CurMethod && CurMethod->isInstance() && 2155 R.getNamingClass() == CurMethod->getParent() && 2156 !isDefaultArgument; 2157 2158 // There are two ways we can find a class-scope declaration during template 2159 // instantiation that we did not find in the template definition: if it is a 2160 // member of a dependent base class, or if it is declared after the point of 2161 // use in the same class. Distinguish these by comparing the class in which 2162 // the member was found to the naming class of the lookup. 2163 unsigned DiagID = diag::err_found_in_dependent_base; 2164 unsigned NoteID = diag::note_member_declared_at; 2165 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2166 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2167 : diag::err_found_later_in_class; 2168 } else if (getLangOpts().MSVCCompat) { 2169 DiagID = diag::ext_found_in_dependent_base; 2170 NoteID = diag::note_dependent_member_use; 2171 } 2172 2173 if (isInstance) { 2174 // Give a code modification hint to insert 'this->'. 2175 Diag(R.getNameLoc(), DiagID) 2176 << R.getLookupName() 2177 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2178 CheckCXXThisCapture(R.getNameLoc()); 2179 } else { 2180 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2181 // they're not shadowed). 2182 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2183 } 2184 2185 for (NamedDecl *D : R) 2186 Diag(D->getLocation(), NoteID); 2187 2188 // Return true if we are inside a default argument instantiation 2189 // and the found name refers to an instance member function, otherwise 2190 // the caller will try to create an implicit member call and this is wrong 2191 // for default arguments. 2192 // 2193 // FIXME: Is this special case necessary? We could allow the caller to 2194 // diagnose this. 2195 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2196 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2197 return true; 2198 } 2199 2200 // Tell the callee to try to recover. 2201 return false; 2202 } 2203 2204 /// Diagnose an empty lookup. 2205 /// 2206 /// \return false if new lookup candidates were found 2207 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2208 CorrectionCandidateCallback &CCC, 2209 TemplateArgumentListInfo *ExplicitTemplateArgs, 2210 ArrayRef<Expr *> Args, TypoExpr **Out) { 2211 DeclarationName Name = R.getLookupName(); 2212 2213 unsigned diagnostic = diag::err_undeclared_var_use; 2214 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2215 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2216 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2217 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2218 diagnostic = diag::err_undeclared_use; 2219 diagnostic_suggest = diag::err_undeclared_use_suggest; 2220 } 2221 2222 // If the original lookup was an unqualified lookup, fake an 2223 // unqualified lookup. This is useful when (for example) the 2224 // original lookup would not have found something because it was a 2225 // dependent name. 2226 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2227 while (DC) { 2228 if (isa<CXXRecordDecl>(DC)) { 2229 LookupQualifiedName(R, DC); 2230 2231 if (!R.empty()) { 2232 // Don't give errors about ambiguities in this lookup. 2233 R.suppressDiagnostics(); 2234 2235 // If there's a best viable function among the results, only mention 2236 // that one in the notes. 2237 OverloadCandidateSet Candidates(R.getNameLoc(), 2238 OverloadCandidateSet::CSK_Normal); 2239 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2240 OverloadCandidateSet::iterator Best; 2241 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2242 OR_Success) { 2243 R.clear(); 2244 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2245 R.resolveKind(); 2246 } 2247 2248 return DiagnoseDependentMemberLookup(R); 2249 } 2250 2251 R.clear(); 2252 } 2253 2254 DC = DC->getLookupParent(); 2255 } 2256 2257 // We didn't find anything, so try to correct for a typo. 2258 TypoCorrection Corrected; 2259 if (S && Out) { 2260 SourceLocation TypoLoc = R.getNameLoc(); 2261 assert(!ExplicitTemplateArgs && 2262 "Diagnosing an empty lookup with explicit template args!"); 2263 *Out = CorrectTypoDelayed( 2264 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2265 [=](const TypoCorrection &TC) { 2266 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2267 diagnostic, diagnostic_suggest); 2268 }, 2269 nullptr, CTK_ErrorRecovery); 2270 if (*Out) 2271 return true; 2272 } else if (S && 2273 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2274 S, &SS, CCC, CTK_ErrorRecovery))) { 2275 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2276 bool DroppedSpecifier = 2277 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2278 R.setLookupName(Corrected.getCorrection()); 2279 2280 bool AcceptableWithRecovery = false; 2281 bool AcceptableWithoutRecovery = false; 2282 NamedDecl *ND = Corrected.getFoundDecl(); 2283 if (ND) { 2284 if (Corrected.isOverloaded()) { 2285 OverloadCandidateSet OCS(R.getNameLoc(), 2286 OverloadCandidateSet::CSK_Normal); 2287 OverloadCandidateSet::iterator Best; 2288 for (NamedDecl *CD : Corrected) { 2289 if (FunctionTemplateDecl *FTD = 2290 dyn_cast<FunctionTemplateDecl>(CD)) 2291 AddTemplateOverloadCandidate( 2292 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2293 Args, OCS); 2294 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2295 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2296 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2297 Args, OCS); 2298 } 2299 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2300 case OR_Success: 2301 ND = Best->FoundDecl; 2302 Corrected.setCorrectionDecl(ND); 2303 break; 2304 default: 2305 // FIXME: Arbitrarily pick the first declaration for the note. 2306 Corrected.setCorrectionDecl(ND); 2307 break; 2308 } 2309 } 2310 R.addDecl(ND); 2311 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2312 CXXRecordDecl *Record = nullptr; 2313 if (Corrected.getCorrectionSpecifier()) { 2314 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2315 Record = Ty->getAsCXXRecordDecl(); 2316 } 2317 if (!Record) 2318 Record = cast<CXXRecordDecl>( 2319 ND->getDeclContext()->getRedeclContext()); 2320 R.setNamingClass(Record); 2321 } 2322 2323 auto *UnderlyingND = ND->getUnderlyingDecl(); 2324 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2325 isa<FunctionTemplateDecl>(UnderlyingND); 2326 // FIXME: If we ended up with a typo for a type name or 2327 // Objective-C class name, we're in trouble because the parser 2328 // is in the wrong place to recover. Suggest the typo 2329 // correction, but don't make it a fix-it since we're not going 2330 // to recover well anyway. 2331 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2332 getAsTypeTemplateDecl(UnderlyingND) || 2333 isa<ObjCInterfaceDecl>(UnderlyingND); 2334 } else { 2335 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2336 // because we aren't able to recover. 2337 AcceptableWithoutRecovery = true; 2338 } 2339 2340 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2341 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2342 ? diag::note_implicit_param_decl 2343 : diag::note_previous_decl; 2344 if (SS.isEmpty()) 2345 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2346 PDiag(NoteID), AcceptableWithRecovery); 2347 else 2348 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2349 << Name << computeDeclContext(SS, false) 2350 << DroppedSpecifier << SS.getRange(), 2351 PDiag(NoteID), AcceptableWithRecovery); 2352 2353 // Tell the callee whether to try to recover. 2354 return !AcceptableWithRecovery; 2355 } 2356 } 2357 R.clear(); 2358 2359 // Emit a special diagnostic for failed member lookups. 2360 // FIXME: computing the declaration context might fail here (?) 2361 if (!SS.isEmpty()) { 2362 Diag(R.getNameLoc(), diag::err_no_member) 2363 << Name << computeDeclContext(SS, false) 2364 << SS.getRange(); 2365 return true; 2366 } 2367 2368 // Give up, we can't recover. 2369 Diag(R.getNameLoc(), diagnostic) << Name; 2370 return true; 2371 } 2372 2373 /// In Microsoft mode, if we are inside a template class whose parent class has 2374 /// dependent base classes, and we can't resolve an unqualified identifier, then 2375 /// assume the identifier is a member of a dependent base class. We can only 2376 /// recover successfully in static methods, instance methods, and other contexts 2377 /// where 'this' is available. This doesn't precisely match MSVC's 2378 /// instantiation model, but it's close enough. 2379 static Expr * 2380 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2381 DeclarationNameInfo &NameInfo, 2382 SourceLocation TemplateKWLoc, 2383 const TemplateArgumentListInfo *TemplateArgs) { 2384 // Only try to recover from lookup into dependent bases in static methods or 2385 // contexts where 'this' is available. 2386 QualType ThisType = S.getCurrentThisType(); 2387 const CXXRecordDecl *RD = nullptr; 2388 if (!ThisType.isNull()) 2389 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2390 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2391 RD = MD->getParent(); 2392 if (!RD || !RD->hasAnyDependentBases()) 2393 return nullptr; 2394 2395 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2396 // is available, suggest inserting 'this->' as a fixit. 2397 SourceLocation Loc = NameInfo.getLoc(); 2398 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2399 DB << NameInfo.getName() << RD; 2400 2401 if (!ThisType.isNull()) { 2402 DB << FixItHint::CreateInsertion(Loc, "this->"); 2403 return CXXDependentScopeMemberExpr::Create( 2404 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2405 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2406 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2407 } 2408 2409 // Synthesize a fake NNS that points to the derived class. This will 2410 // perform name lookup during template instantiation. 2411 CXXScopeSpec SS; 2412 auto *NNS = 2413 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2414 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2415 return DependentScopeDeclRefExpr::Create( 2416 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2417 TemplateArgs); 2418 } 2419 2420 ExprResult 2421 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2422 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2423 bool HasTrailingLParen, bool IsAddressOfOperand, 2424 CorrectionCandidateCallback *CCC, 2425 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2426 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2427 "cannot be direct & operand and have a trailing lparen"); 2428 if (SS.isInvalid()) 2429 return ExprError(); 2430 2431 TemplateArgumentListInfo TemplateArgsBuffer; 2432 2433 // Decompose the UnqualifiedId into the following data. 2434 DeclarationNameInfo NameInfo; 2435 const TemplateArgumentListInfo *TemplateArgs; 2436 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2437 2438 DeclarationName Name = NameInfo.getName(); 2439 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2440 SourceLocation NameLoc = NameInfo.getLoc(); 2441 2442 if (II && II->isEditorPlaceholder()) { 2443 // FIXME: When typed placeholders are supported we can create a typed 2444 // placeholder expression node. 2445 return ExprError(); 2446 } 2447 2448 // C++ [temp.dep.expr]p3: 2449 // An id-expression is type-dependent if it contains: 2450 // -- an identifier that was declared with a dependent type, 2451 // (note: handled after lookup) 2452 // -- a template-id that is dependent, 2453 // (note: handled in BuildTemplateIdExpr) 2454 // -- a conversion-function-id that specifies a dependent type, 2455 // -- a nested-name-specifier that contains a class-name that 2456 // names a dependent type. 2457 // Determine whether this is a member of an unknown specialization; 2458 // we need to handle these differently. 2459 bool DependentID = false; 2460 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2461 Name.getCXXNameType()->isDependentType()) { 2462 DependentID = true; 2463 } else if (SS.isSet()) { 2464 if (DeclContext *DC = computeDeclContext(SS, false)) { 2465 if (RequireCompleteDeclContext(SS, DC)) 2466 return ExprError(); 2467 } else { 2468 DependentID = true; 2469 } 2470 } 2471 2472 if (DependentID) 2473 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2474 IsAddressOfOperand, TemplateArgs); 2475 2476 // Perform the required lookup. 2477 LookupResult R(*this, NameInfo, 2478 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2479 ? LookupObjCImplicitSelfParam 2480 : LookupOrdinaryName); 2481 if (TemplateKWLoc.isValid() || TemplateArgs) { 2482 // Lookup the template name again to correctly establish the context in 2483 // which it was found. This is really unfortunate as we already did the 2484 // lookup to determine that it was a template name in the first place. If 2485 // this becomes a performance hit, we can work harder to preserve those 2486 // results until we get here but it's likely not worth it. 2487 bool MemberOfUnknownSpecialization; 2488 AssumedTemplateKind AssumedTemplate; 2489 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2490 MemberOfUnknownSpecialization, TemplateKWLoc, 2491 &AssumedTemplate)) 2492 return ExprError(); 2493 2494 if (MemberOfUnknownSpecialization || 2495 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2496 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2497 IsAddressOfOperand, TemplateArgs); 2498 } else { 2499 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2500 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2501 2502 // If the result might be in a dependent base class, this is a dependent 2503 // id-expression. 2504 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2505 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2506 IsAddressOfOperand, TemplateArgs); 2507 2508 // If this reference is in an Objective-C method, then we need to do 2509 // some special Objective-C lookup, too. 2510 if (IvarLookupFollowUp) { 2511 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2512 if (E.isInvalid()) 2513 return ExprError(); 2514 2515 if (Expr *Ex = E.getAs<Expr>()) 2516 return Ex; 2517 } 2518 } 2519 2520 if (R.isAmbiguous()) 2521 return ExprError(); 2522 2523 // This could be an implicitly declared function reference (legal in C90, 2524 // extension in C99, forbidden in C++). 2525 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2526 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2527 if (D) R.addDecl(D); 2528 } 2529 2530 // Determine whether this name might be a candidate for 2531 // argument-dependent lookup. 2532 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2533 2534 if (R.empty() && !ADL) { 2535 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2536 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2537 TemplateKWLoc, TemplateArgs)) 2538 return E; 2539 } 2540 2541 // Don't diagnose an empty lookup for inline assembly. 2542 if (IsInlineAsmIdentifier) 2543 return ExprError(); 2544 2545 // If this name wasn't predeclared and if this is not a function 2546 // call, diagnose the problem. 2547 TypoExpr *TE = nullptr; 2548 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2549 : nullptr); 2550 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2551 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2552 "Typo correction callback misconfigured"); 2553 if (CCC) { 2554 // Make sure the callback knows what the typo being diagnosed is. 2555 CCC->setTypoName(II); 2556 if (SS.isValid()) 2557 CCC->setTypoNNS(SS.getScopeRep()); 2558 } 2559 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2560 // a template name, but we happen to have always already looked up the name 2561 // before we get here if it must be a template name. 2562 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2563 None, &TE)) { 2564 if (TE && KeywordReplacement) { 2565 auto &State = getTypoExprState(TE); 2566 auto BestTC = State.Consumer->getNextCorrection(); 2567 if (BestTC.isKeyword()) { 2568 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2569 if (State.DiagHandler) 2570 State.DiagHandler(BestTC); 2571 KeywordReplacement->startToken(); 2572 KeywordReplacement->setKind(II->getTokenID()); 2573 KeywordReplacement->setIdentifierInfo(II); 2574 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2575 // Clean up the state associated with the TypoExpr, since it has 2576 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2577 clearDelayedTypo(TE); 2578 // Signal that a correction to a keyword was performed by returning a 2579 // valid-but-null ExprResult. 2580 return (Expr*)nullptr; 2581 } 2582 State.Consumer->resetCorrectionStream(); 2583 } 2584 return TE ? TE : ExprError(); 2585 } 2586 2587 assert(!R.empty() && 2588 "DiagnoseEmptyLookup returned false but added no results"); 2589 2590 // If we found an Objective-C instance variable, let 2591 // LookupInObjCMethod build the appropriate expression to 2592 // reference the ivar. 2593 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2594 R.clear(); 2595 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2596 // In a hopelessly buggy code, Objective-C instance variable 2597 // lookup fails and no expression will be built to reference it. 2598 if (!E.isInvalid() && !E.get()) 2599 return ExprError(); 2600 return E; 2601 } 2602 } 2603 2604 // This is guaranteed from this point on. 2605 assert(!R.empty() || ADL); 2606 2607 // Check whether this might be a C++ implicit instance member access. 2608 // C++ [class.mfct.non-static]p3: 2609 // When an id-expression that is not part of a class member access 2610 // syntax and not used to form a pointer to member is used in the 2611 // body of a non-static member function of class X, if name lookup 2612 // resolves the name in the id-expression to a non-static non-type 2613 // member of some class C, the id-expression is transformed into a 2614 // class member access expression using (*this) as the 2615 // postfix-expression to the left of the . operator. 2616 // 2617 // But we don't actually need to do this for '&' operands if R 2618 // resolved to a function or overloaded function set, because the 2619 // expression is ill-formed if it actually works out to be a 2620 // non-static member function: 2621 // 2622 // C++ [expr.ref]p4: 2623 // Otherwise, if E1.E2 refers to a non-static member function. . . 2624 // [t]he expression can be used only as the left-hand operand of a 2625 // member function call. 2626 // 2627 // There are other safeguards against such uses, but it's important 2628 // to get this right here so that we don't end up making a 2629 // spuriously dependent expression if we're inside a dependent 2630 // instance method. 2631 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2632 bool MightBeImplicitMember; 2633 if (!IsAddressOfOperand) 2634 MightBeImplicitMember = true; 2635 else if (!SS.isEmpty()) 2636 MightBeImplicitMember = false; 2637 else if (R.isOverloadedResult()) 2638 MightBeImplicitMember = false; 2639 else if (R.isUnresolvableResult()) 2640 MightBeImplicitMember = true; 2641 else 2642 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2643 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2644 isa<MSPropertyDecl>(R.getFoundDecl()); 2645 2646 if (MightBeImplicitMember) 2647 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2648 R, TemplateArgs, S); 2649 } 2650 2651 if (TemplateArgs || TemplateKWLoc.isValid()) { 2652 2653 // In C++1y, if this is a variable template id, then check it 2654 // in BuildTemplateIdExpr(). 2655 // The single lookup result must be a variable template declaration. 2656 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2657 Id.TemplateId->Kind == TNK_Var_template) { 2658 assert(R.getAsSingle<VarTemplateDecl>() && 2659 "There should only be one declaration found."); 2660 } 2661 2662 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2663 } 2664 2665 return BuildDeclarationNameExpr(SS, R, ADL); 2666 } 2667 2668 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2669 /// declaration name, generally during template instantiation. 2670 /// There's a large number of things which don't need to be done along 2671 /// this path. 2672 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2673 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2674 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2675 DeclContext *DC = computeDeclContext(SS, false); 2676 if (!DC) 2677 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2678 NameInfo, /*TemplateArgs=*/nullptr); 2679 2680 if (RequireCompleteDeclContext(SS, DC)) 2681 return ExprError(); 2682 2683 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2684 LookupQualifiedName(R, DC); 2685 2686 if (R.isAmbiguous()) 2687 return ExprError(); 2688 2689 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2690 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2691 NameInfo, /*TemplateArgs=*/nullptr); 2692 2693 if (R.empty()) { 2694 // Don't diagnose problems with invalid record decl, the secondary no_member 2695 // diagnostic during template instantiation is likely bogus, e.g. if a class 2696 // is invalid because it's derived from an invalid base class, then missing 2697 // members were likely supposed to be inherited. 2698 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2699 if (CD->isInvalidDecl()) 2700 return ExprError(); 2701 Diag(NameInfo.getLoc(), diag::err_no_member) 2702 << NameInfo.getName() << DC << SS.getRange(); 2703 return ExprError(); 2704 } 2705 2706 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2707 // Diagnose a missing typename if this resolved unambiguously to a type in 2708 // a dependent context. If we can recover with a type, downgrade this to 2709 // a warning in Microsoft compatibility mode. 2710 unsigned DiagID = diag::err_typename_missing; 2711 if (RecoveryTSI && getLangOpts().MSVCCompat) 2712 DiagID = diag::ext_typename_missing; 2713 SourceLocation Loc = SS.getBeginLoc(); 2714 auto D = Diag(Loc, DiagID); 2715 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2716 << SourceRange(Loc, NameInfo.getEndLoc()); 2717 2718 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2719 // context. 2720 if (!RecoveryTSI) 2721 return ExprError(); 2722 2723 // Only issue the fixit if we're prepared to recover. 2724 D << FixItHint::CreateInsertion(Loc, "typename "); 2725 2726 // Recover by pretending this was an elaborated type. 2727 QualType Ty = Context.getTypeDeclType(TD); 2728 TypeLocBuilder TLB; 2729 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2730 2731 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2732 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2733 QTL.setElaboratedKeywordLoc(SourceLocation()); 2734 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2735 2736 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2737 2738 return ExprEmpty(); 2739 } 2740 2741 // Defend against this resolving to an implicit member access. We usually 2742 // won't get here if this might be a legitimate a class member (we end up in 2743 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2744 // a pointer-to-member or in an unevaluated context in C++11. 2745 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2746 return BuildPossibleImplicitMemberExpr(SS, 2747 /*TemplateKWLoc=*/SourceLocation(), 2748 R, /*TemplateArgs=*/nullptr, S); 2749 2750 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2751 } 2752 2753 /// The parser has read a name in, and Sema has detected that we're currently 2754 /// inside an ObjC method. Perform some additional checks and determine if we 2755 /// should form a reference to an ivar. 2756 /// 2757 /// Ideally, most of this would be done by lookup, but there's 2758 /// actually quite a lot of extra work involved. 2759 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2760 IdentifierInfo *II) { 2761 SourceLocation Loc = Lookup.getNameLoc(); 2762 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2763 2764 // Check for error condition which is already reported. 2765 if (!CurMethod) 2766 return DeclResult(true); 2767 2768 // There are two cases to handle here. 1) scoped lookup could have failed, 2769 // in which case we should look for an ivar. 2) scoped lookup could have 2770 // found a decl, but that decl is outside the current instance method (i.e. 2771 // a global variable). In these two cases, we do a lookup for an ivar with 2772 // this name, if the lookup sucedes, we replace it our current decl. 2773 2774 // If we're in a class method, we don't normally want to look for 2775 // ivars. But if we don't find anything else, and there's an 2776 // ivar, that's an error. 2777 bool IsClassMethod = CurMethod->isClassMethod(); 2778 2779 bool LookForIvars; 2780 if (Lookup.empty()) 2781 LookForIvars = true; 2782 else if (IsClassMethod) 2783 LookForIvars = false; 2784 else 2785 LookForIvars = (Lookup.isSingleResult() && 2786 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2787 ObjCInterfaceDecl *IFace = nullptr; 2788 if (LookForIvars) { 2789 IFace = CurMethod->getClassInterface(); 2790 ObjCInterfaceDecl *ClassDeclared; 2791 ObjCIvarDecl *IV = nullptr; 2792 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2793 // Diagnose using an ivar in a class method. 2794 if (IsClassMethod) { 2795 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2796 return DeclResult(true); 2797 } 2798 2799 // Diagnose the use of an ivar outside of the declaring class. 2800 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2801 !declaresSameEntity(ClassDeclared, IFace) && 2802 !getLangOpts().DebuggerSupport) 2803 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2804 2805 // Success. 2806 return IV; 2807 } 2808 } else if (CurMethod->isInstanceMethod()) { 2809 // We should warn if a local variable hides an ivar. 2810 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2811 ObjCInterfaceDecl *ClassDeclared; 2812 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2813 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2814 declaresSameEntity(IFace, ClassDeclared)) 2815 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2816 } 2817 } 2818 } else if (Lookup.isSingleResult() && 2819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2820 // If accessing a stand-alone ivar in a class method, this is an error. 2821 if (const ObjCIvarDecl *IV = 2822 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2823 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2824 return DeclResult(true); 2825 } 2826 } 2827 2828 // Didn't encounter an error, didn't find an ivar. 2829 return DeclResult(false); 2830 } 2831 2832 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2833 ObjCIvarDecl *IV) { 2834 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2835 assert(CurMethod && CurMethod->isInstanceMethod() && 2836 "should not reference ivar from this context"); 2837 2838 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2839 assert(IFace && "should not reference ivar from this context"); 2840 2841 // If we're referencing an invalid decl, just return this as a silent 2842 // error node. The error diagnostic was already emitted on the decl. 2843 if (IV->isInvalidDecl()) 2844 return ExprError(); 2845 2846 // Check if referencing a field with __attribute__((deprecated)). 2847 if (DiagnoseUseOfDecl(IV, Loc)) 2848 return ExprError(); 2849 2850 // FIXME: This should use a new expr for a direct reference, don't 2851 // turn this into Self->ivar, just return a BareIVarExpr or something. 2852 IdentifierInfo &II = Context.Idents.get("self"); 2853 UnqualifiedId SelfName; 2854 SelfName.setIdentifier(&II, SourceLocation()); 2855 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2856 CXXScopeSpec SelfScopeSpec; 2857 SourceLocation TemplateKWLoc; 2858 ExprResult SelfExpr = 2859 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2860 /*HasTrailingLParen=*/false, 2861 /*IsAddressOfOperand=*/false); 2862 if (SelfExpr.isInvalid()) 2863 return ExprError(); 2864 2865 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2866 if (SelfExpr.isInvalid()) 2867 return ExprError(); 2868 2869 MarkAnyDeclReferenced(Loc, IV, true); 2870 2871 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2872 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2873 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2874 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2875 2876 ObjCIvarRefExpr *Result = new (Context) 2877 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2878 IV->getLocation(), SelfExpr.get(), true, true); 2879 2880 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2881 if (!isUnevaluatedContext() && 2882 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2883 getCurFunction()->recordUseOfWeak(Result); 2884 } 2885 if (getLangOpts().ObjCAutoRefCount) 2886 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2887 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2888 2889 return Result; 2890 } 2891 2892 /// The parser has read a name in, and Sema has detected that we're currently 2893 /// inside an ObjC method. Perform some additional checks and determine if we 2894 /// should form a reference to an ivar. If so, build an expression referencing 2895 /// that ivar. 2896 ExprResult 2897 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2898 IdentifierInfo *II, bool AllowBuiltinCreation) { 2899 // FIXME: Integrate this lookup step into LookupParsedName. 2900 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2901 if (Ivar.isInvalid()) 2902 return ExprError(); 2903 if (Ivar.isUsable()) 2904 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2905 cast<ObjCIvarDecl>(Ivar.get())); 2906 2907 if (Lookup.empty() && II && AllowBuiltinCreation) 2908 LookupBuiltin(Lookup); 2909 2910 // Sentinel value saying that we didn't do anything special. 2911 return ExprResult(false); 2912 } 2913 2914 /// Cast a base object to a member's actual type. 2915 /// 2916 /// There are two relevant checks: 2917 /// 2918 /// C++ [class.access.base]p7: 2919 /// 2920 /// If a class member access operator [...] is used to access a non-static 2921 /// data member or non-static member function, the reference is ill-formed if 2922 /// the left operand [...] cannot be implicitly converted to a pointer to the 2923 /// naming class of the right operand. 2924 /// 2925 /// C++ [expr.ref]p7: 2926 /// 2927 /// If E2 is a non-static data member or a non-static member function, the 2928 /// program is ill-formed if the class of which E2 is directly a member is an 2929 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2930 /// 2931 /// Note that the latter check does not consider access; the access of the 2932 /// "real" base class is checked as appropriate when checking the access of the 2933 /// member name. 2934 ExprResult 2935 Sema::PerformObjectMemberConversion(Expr *From, 2936 NestedNameSpecifier *Qualifier, 2937 NamedDecl *FoundDecl, 2938 NamedDecl *Member) { 2939 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2940 if (!RD) 2941 return From; 2942 2943 QualType DestRecordType; 2944 QualType DestType; 2945 QualType FromRecordType; 2946 QualType FromType = From->getType(); 2947 bool PointerConversions = false; 2948 if (isa<FieldDecl>(Member)) { 2949 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2950 auto FromPtrType = FromType->getAs<PointerType>(); 2951 DestRecordType = Context.getAddrSpaceQualType( 2952 DestRecordType, FromPtrType 2953 ? FromType->getPointeeType().getAddressSpace() 2954 : FromType.getAddressSpace()); 2955 2956 if (FromPtrType) { 2957 DestType = Context.getPointerType(DestRecordType); 2958 FromRecordType = FromPtrType->getPointeeType(); 2959 PointerConversions = true; 2960 } else { 2961 DestType = DestRecordType; 2962 FromRecordType = FromType; 2963 } 2964 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2965 if (Method->isStatic()) 2966 return From; 2967 2968 DestType = Method->getThisType(); 2969 DestRecordType = DestType->getPointeeType(); 2970 2971 if (FromType->getAs<PointerType>()) { 2972 FromRecordType = FromType->getPointeeType(); 2973 PointerConversions = true; 2974 } else { 2975 FromRecordType = FromType; 2976 DestType = DestRecordType; 2977 } 2978 2979 LangAS FromAS = FromRecordType.getAddressSpace(); 2980 LangAS DestAS = DestRecordType.getAddressSpace(); 2981 if (FromAS != DestAS) { 2982 QualType FromRecordTypeWithoutAS = 2983 Context.removeAddrSpaceQualType(FromRecordType); 2984 QualType FromTypeWithDestAS = 2985 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2986 if (PointerConversions) 2987 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2988 From = ImpCastExprToType(From, FromTypeWithDestAS, 2989 CK_AddressSpaceConversion, From->getValueKind()) 2990 .get(); 2991 } 2992 } else { 2993 // No conversion necessary. 2994 return From; 2995 } 2996 2997 if (DestType->isDependentType() || FromType->isDependentType()) 2998 return From; 2999 3000 // If the unqualified types are the same, no conversion is necessary. 3001 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3002 return From; 3003 3004 SourceRange FromRange = From->getSourceRange(); 3005 SourceLocation FromLoc = FromRange.getBegin(); 3006 3007 ExprValueKind VK = From->getValueKind(); 3008 3009 // C++ [class.member.lookup]p8: 3010 // [...] Ambiguities can often be resolved by qualifying a name with its 3011 // class name. 3012 // 3013 // If the member was a qualified name and the qualified referred to a 3014 // specific base subobject type, we'll cast to that intermediate type 3015 // first and then to the object in which the member is declared. That allows 3016 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3017 // 3018 // class Base { public: int x; }; 3019 // class Derived1 : public Base { }; 3020 // class Derived2 : public Base { }; 3021 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3022 // 3023 // void VeryDerived::f() { 3024 // x = 17; // error: ambiguous base subobjects 3025 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3026 // } 3027 if (Qualifier && Qualifier->getAsType()) { 3028 QualType QType = QualType(Qualifier->getAsType(), 0); 3029 assert(QType->isRecordType() && "lookup done with non-record type"); 3030 3031 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3032 3033 // In C++98, the qualifier type doesn't actually have to be a base 3034 // type of the object type, in which case we just ignore it. 3035 // Otherwise build the appropriate casts. 3036 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3037 CXXCastPath BasePath; 3038 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3039 FromLoc, FromRange, &BasePath)) 3040 return ExprError(); 3041 3042 if (PointerConversions) 3043 QType = Context.getPointerType(QType); 3044 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3045 VK, &BasePath).get(); 3046 3047 FromType = QType; 3048 FromRecordType = QRecordType; 3049 3050 // If the qualifier type was the same as the destination type, 3051 // we're done. 3052 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3053 return From; 3054 } 3055 } 3056 3057 CXXCastPath BasePath; 3058 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3059 FromLoc, FromRange, &BasePath, 3060 /*IgnoreAccess=*/true)) 3061 return ExprError(); 3062 3063 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3064 VK, &BasePath); 3065 } 3066 3067 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3068 const LookupResult &R, 3069 bool HasTrailingLParen) { 3070 // Only when used directly as the postfix-expression of a call. 3071 if (!HasTrailingLParen) 3072 return false; 3073 3074 // Never if a scope specifier was provided. 3075 if (SS.isSet()) 3076 return false; 3077 3078 // Only in C++ or ObjC++. 3079 if (!getLangOpts().CPlusPlus) 3080 return false; 3081 3082 // Turn off ADL when we find certain kinds of declarations during 3083 // normal lookup: 3084 for (NamedDecl *D : R) { 3085 // C++0x [basic.lookup.argdep]p3: 3086 // -- a declaration of a class member 3087 // Since using decls preserve this property, we check this on the 3088 // original decl. 3089 if (D->isCXXClassMember()) 3090 return false; 3091 3092 // C++0x [basic.lookup.argdep]p3: 3093 // -- a block-scope function declaration that is not a 3094 // using-declaration 3095 // NOTE: we also trigger this for function templates (in fact, we 3096 // don't check the decl type at all, since all other decl types 3097 // turn off ADL anyway). 3098 if (isa<UsingShadowDecl>(D)) 3099 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3100 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3101 return false; 3102 3103 // C++0x [basic.lookup.argdep]p3: 3104 // -- a declaration that is neither a function or a function 3105 // template 3106 // And also for builtin functions. 3107 if (isa<FunctionDecl>(D)) { 3108 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3109 3110 // But also builtin functions. 3111 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3112 return false; 3113 } else if (!isa<FunctionTemplateDecl>(D)) 3114 return false; 3115 } 3116 3117 return true; 3118 } 3119 3120 3121 /// Diagnoses obvious problems with the use of the given declaration 3122 /// as an expression. This is only actually called for lookups that 3123 /// were not overloaded, and it doesn't promise that the declaration 3124 /// will in fact be used. 3125 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3126 if (D->isInvalidDecl()) 3127 return true; 3128 3129 if (isa<TypedefNameDecl>(D)) { 3130 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3131 return true; 3132 } 3133 3134 if (isa<ObjCInterfaceDecl>(D)) { 3135 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3136 return true; 3137 } 3138 3139 if (isa<NamespaceDecl>(D)) { 3140 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3141 return true; 3142 } 3143 3144 return false; 3145 } 3146 3147 // Certain multiversion types should be treated as overloaded even when there is 3148 // only one result. 3149 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3150 assert(R.isSingleResult() && "Expected only a single result"); 3151 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3152 return FD && 3153 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3154 } 3155 3156 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3157 LookupResult &R, bool NeedsADL, 3158 bool AcceptInvalidDecl) { 3159 // If this is a single, fully-resolved result and we don't need ADL, 3160 // just build an ordinary singleton decl ref. 3161 if (!NeedsADL && R.isSingleResult() && 3162 !R.getAsSingle<FunctionTemplateDecl>() && 3163 !ShouldLookupResultBeMultiVersionOverload(R)) 3164 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3165 R.getRepresentativeDecl(), nullptr, 3166 AcceptInvalidDecl); 3167 3168 // We only need to check the declaration if there's exactly one 3169 // result, because in the overloaded case the results can only be 3170 // functions and function templates. 3171 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3172 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3173 return ExprError(); 3174 3175 // Otherwise, just build an unresolved lookup expression. Suppress 3176 // any lookup-related diagnostics; we'll hash these out later, when 3177 // we've picked a target. 3178 R.suppressDiagnostics(); 3179 3180 UnresolvedLookupExpr *ULE 3181 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3182 SS.getWithLocInContext(Context), 3183 R.getLookupNameInfo(), 3184 NeedsADL, R.isOverloadedResult(), 3185 R.begin(), R.end()); 3186 3187 return ULE; 3188 } 3189 3190 static void 3191 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3192 ValueDecl *var, DeclContext *DC); 3193 3194 /// Complete semantic analysis for a reference to the given declaration. 3195 ExprResult Sema::BuildDeclarationNameExpr( 3196 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3197 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3198 bool AcceptInvalidDecl) { 3199 assert(D && "Cannot refer to a NULL declaration"); 3200 assert(!isa<FunctionTemplateDecl>(D) && 3201 "Cannot refer unambiguously to a function template"); 3202 3203 SourceLocation Loc = NameInfo.getLoc(); 3204 if (CheckDeclInExpr(*this, Loc, D)) 3205 return ExprError(); 3206 3207 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3208 // Specifically diagnose references to class templates that are missing 3209 // a template argument list. 3210 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3211 return ExprError(); 3212 } 3213 3214 // Make sure that we're referring to a value. 3215 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3216 if (!VD) { 3217 Diag(Loc, diag::err_ref_non_value) 3218 << D << SS.getRange(); 3219 Diag(D->getLocation(), diag::note_declared_at); 3220 return ExprError(); 3221 } 3222 3223 // Check whether this declaration can be used. Note that we suppress 3224 // this check when we're going to perform argument-dependent lookup 3225 // on this function name, because this might not be the function 3226 // that overload resolution actually selects. 3227 if (DiagnoseUseOfDecl(VD, Loc)) 3228 return ExprError(); 3229 3230 // Only create DeclRefExpr's for valid Decl's. 3231 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3232 return ExprError(); 3233 3234 // Handle members of anonymous structs and unions. If we got here, 3235 // and the reference is to a class member indirect field, then this 3236 // must be the subject of a pointer-to-member expression. 3237 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3238 if (!indirectField->isCXXClassMember()) 3239 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3240 indirectField); 3241 3242 { 3243 QualType type = VD->getType(); 3244 if (type.isNull()) 3245 return ExprError(); 3246 ExprValueKind valueKind = VK_RValue; 3247 3248 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3249 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3250 // is expanded by some outer '...' in the context of the use. 3251 type = type.getNonPackExpansionType(); 3252 3253 switch (D->getKind()) { 3254 // Ignore all the non-ValueDecl kinds. 3255 #define ABSTRACT_DECL(kind) 3256 #define VALUE(type, base) 3257 #define DECL(type, base) \ 3258 case Decl::type: 3259 #include "clang/AST/DeclNodes.inc" 3260 llvm_unreachable("invalid value decl kind"); 3261 3262 // These shouldn't make it here. 3263 case Decl::ObjCAtDefsField: 3264 llvm_unreachable("forming non-member reference to ivar?"); 3265 3266 // Enum constants are always r-values and never references. 3267 // Unresolved using declarations are dependent. 3268 case Decl::EnumConstant: 3269 case Decl::UnresolvedUsingValue: 3270 case Decl::OMPDeclareReduction: 3271 case Decl::OMPDeclareMapper: 3272 valueKind = VK_RValue; 3273 break; 3274 3275 // Fields and indirect fields that got here must be for 3276 // pointer-to-member expressions; we just call them l-values for 3277 // internal consistency, because this subexpression doesn't really 3278 // exist in the high-level semantics. 3279 case Decl::Field: 3280 case Decl::IndirectField: 3281 case Decl::ObjCIvar: 3282 assert(getLangOpts().CPlusPlus && 3283 "building reference to field in C?"); 3284 3285 // These can't have reference type in well-formed programs, but 3286 // for internal consistency we do this anyway. 3287 type = type.getNonReferenceType(); 3288 valueKind = VK_LValue; 3289 break; 3290 3291 // Non-type template parameters are either l-values or r-values 3292 // depending on the type. 3293 case Decl::NonTypeTemplateParm: { 3294 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3295 type = reftype->getPointeeType(); 3296 valueKind = VK_LValue; // even if the parameter is an r-value reference 3297 break; 3298 } 3299 3300 // [expr.prim.id.unqual]p2: 3301 // If the entity is a template parameter object for a template 3302 // parameter of type T, the type of the expression is const T. 3303 // [...] The expression is an lvalue if the entity is a [...] template 3304 // parameter object. 3305 if (type->isRecordType()) { 3306 type = type.getUnqualifiedType().withConst(); 3307 valueKind = VK_LValue; 3308 break; 3309 } 3310 3311 // For non-references, we need to strip qualifiers just in case 3312 // the template parameter was declared as 'const int' or whatever. 3313 valueKind = VK_RValue; 3314 type = type.getUnqualifiedType(); 3315 break; 3316 } 3317 3318 case Decl::Var: 3319 case Decl::VarTemplateSpecialization: 3320 case Decl::VarTemplatePartialSpecialization: 3321 case Decl::Decomposition: 3322 case Decl::OMPCapturedExpr: 3323 // In C, "extern void blah;" is valid and is an r-value. 3324 if (!getLangOpts().CPlusPlus && 3325 !type.hasQualifiers() && 3326 type->isVoidType()) { 3327 valueKind = VK_RValue; 3328 break; 3329 } 3330 LLVM_FALLTHROUGH; 3331 3332 case Decl::ImplicitParam: 3333 case Decl::ParmVar: { 3334 // These are always l-values. 3335 valueKind = VK_LValue; 3336 type = type.getNonReferenceType(); 3337 3338 // FIXME: Does the addition of const really only apply in 3339 // potentially-evaluated contexts? Since the variable isn't actually 3340 // captured in an unevaluated context, it seems that the answer is no. 3341 if (!isUnevaluatedContext()) { 3342 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3343 if (!CapturedType.isNull()) 3344 type = CapturedType; 3345 } 3346 3347 break; 3348 } 3349 3350 case Decl::Binding: { 3351 // These are always lvalues. 3352 valueKind = VK_LValue; 3353 type = type.getNonReferenceType(); 3354 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3355 // decides how that's supposed to work. 3356 auto *BD = cast<BindingDecl>(VD); 3357 if (BD->getDeclContext() != CurContext) { 3358 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3359 if (DD && DD->hasLocalStorage()) 3360 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3361 } 3362 break; 3363 } 3364 3365 case Decl::Function: { 3366 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3367 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3368 type = Context.BuiltinFnTy; 3369 valueKind = VK_RValue; 3370 break; 3371 } 3372 } 3373 3374 const FunctionType *fty = type->castAs<FunctionType>(); 3375 3376 // If we're referring to a function with an __unknown_anytype 3377 // result type, make the entire expression __unknown_anytype. 3378 if (fty->getReturnType() == Context.UnknownAnyTy) { 3379 type = Context.UnknownAnyTy; 3380 valueKind = VK_RValue; 3381 break; 3382 } 3383 3384 // Functions are l-values in C++. 3385 if (getLangOpts().CPlusPlus) { 3386 valueKind = VK_LValue; 3387 break; 3388 } 3389 3390 // C99 DR 316 says that, if a function type comes from a 3391 // function definition (without a prototype), that type is only 3392 // used for checking compatibility. Therefore, when referencing 3393 // the function, we pretend that we don't have the full function 3394 // type. 3395 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3396 isa<FunctionProtoType>(fty)) 3397 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3398 fty->getExtInfo()); 3399 3400 // Functions are r-values in C. 3401 valueKind = VK_RValue; 3402 break; 3403 } 3404 3405 case Decl::CXXDeductionGuide: 3406 llvm_unreachable("building reference to deduction guide"); 3407 3408 case Decl::MSProperty: 3409 case Decl::MSGuid: 3410 case Decl::TemplateParamObject: 3411 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3412 // capture in OpenMP, or duplicated between host and device? 3413 valueKind = VK_LValue; 3414 break; 3415 3416 case Decl::CXXMethod: 3417 // If we're referring to a method with an __unknown_anytype 3418 // result type, make the entire expression __unknown_anytype. 3419 // This should only be possible with a type written directly. 3420 if (const FunctionProtoType *proto 3421 = dyn_cast<FunctionProtoType>(VD->getType())) 3422 if (proto->getReturnType() == Context.UnknownAnyTy) { 3423 type = Context.UnknownAnyTy; 3424 valueKind = VK_RValue; 3425 break; 3426 } 3427 3428 // C++ methods are l-values if static, r-values if non-static. 3429 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3430 valueKind = VK_LValue; 3431 break; 3432 } 3433 LLVM_FALLTHROUGH; 3434 3435 case Decl::CXXConversion: 3436 case Decl::CXXDestructor: 3437 case Decl::CXXConstructor: 3438 valueKind = VK_RValue; 3439 break; 3440 } 3441 3442 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3443 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3444 TemplateArgs); 3445 } 3446 } 3447 3448 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3449 SmallString<32> &Target) { 3450 Target.resize(CharByteWidth * (Source.size() + 1)); 3451 char *ResultPtr = &Target[0]; 3452 const llvm::UTF8 *ErrorPtr; 3453 bool success = 3454 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3455 (void)success; 3456 assert(success); 3457 Target.resize(ResultPtr - &Target[0]); 3458 } 3459 3460 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3461 PredefinedExpr::IdentKind IK) { 3462 // Pick the current block, lambda, captured statement or function. 3463 Decl *currentDecl = nullptr; 3464 if (const BlockScopeInfo *BSI = getCurBlock()) 3465 currentDecl = BSI->TheDecl; 3466 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3467 currentDecl = LSI->CallOperator; 3468 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3469 currentDecl = CSI->TheCapturedDecl; 3470 else 3471 currentDecl = getCurFunctionOrMethodDecl(); 3472 3473 if (!currentDecl) { 3474 Diag(Loc, diag::ext_predef_outside_function); 3475 currentDecl = Context.getTranslationUnitDecl(); 3476 } 3477 3478 QualType ResTy; 3479 StringLiteral *SL = nullptr; 3480 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3481 ResTy = Context.DependentTy; 3482 else { 3483 // Pre-defined identifiers are of type char[x], where x is the length of 3484 // the string. 3485 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3486 unsigned Length = Str.length(); 3487 3488 llvm::APInt LengthI(32, Length + 1); 3489 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3490 ResTy = 3491 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3492 SmallString<32> RawChars; 3493 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3494 Str, RawChars); 3495 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3496 ArrayType::Normal, 3497 /*IndexTypeQuals*/ 0); 3498 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3499 /*Pascal*/ false, ResTy, Loc); 3500 } else { 3501 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3502 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3503 ArrayType::Normal, 3504 /*IndexTypeQuals*/ 0); 3505 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3506 /*Pascal*/ false, ResTy, Loc); 3507 } 3508 } 3509 3510 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3511 } 3512 3513 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3514 PredefinedExpr::IdentKind IK; 3515 3516 switch (Kind) { 3517 default: llvm_unreachable("Unknown simple primary expr!"); 3518 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3519 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3520 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3521 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3522 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3523 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3524 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3525 } 3526 3527 return BuildPredefinedExpr(Loc, IK); 3528 } 3529 3530 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3531 SmallString<16> CharBuffer; 3532 bool Invalid = false; 3533 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3534 if (Invalid) 3535 return ExprError(); 3536 3537 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3538 PP, Tok.getKind()); 3539 if (Literal.hadError()) 3540 return ExprError(); 3541 3542 QualType Ty; 3543 if (Literal.isWide()) 3544 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3545 else if (Literal.isUTF8() && getLangOpts().Char8) 3546 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3547 else if (Literal.isUTF16()) 3548 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3549 else if (Literal.isUTF32()) 3550 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3551 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3552 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3553 else 3554 Ty = Context.CharTy; // 'x' -> char in C++ 3555 3556 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3557 if (Literal.isWide()) 3558 Kind = CharacterLiteral::Wide; 3559 else if (Literal.isUTF16()) 3560 Kind = CharacterLiteral::UTF16; 3561 else if (Literal.isUTF32()) 3562 Kind = CharacterLiteral::UTF32; 3563 else if (Literal.isUTF8()) 3564 Kind = CharacterLiteral::UTF8; 3565 3566 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3567 Tok.getLocation()); 3568 3569 if (Literal.getUDSuffix().empty()) 3570 return Lit; 3571 3572 // We're building a user-defined literal. 3573 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3574 SourceLocation UDSuffixLoc = 3575 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3576 3577 // Make sure we're allowed user-defined literals here. 3578 if (!UDLScope) 3579 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3580 3581 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3582 // operator "" X (ch) 3583 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3584 Lit, Tok.getLocation()); 3585 } 3586 3587 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3588 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3589 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3590 Context.IntTy, Loc); 3591 } 3592 3593 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3594 QualType Ty, SourceLocation Loc) { 3595 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3596 3597 using llvm::APFloat; 3598 APFloat Val(Format); 3599 3600 APFloat::opStatus result = Literal.GetFloatValue(Val); 3601 3602 // Overflow is always an error, but underflow is only an error if 3603 // we underflowed to zero (APFloat reports denormals as underflow). 3604 if ((result & APFloat::opOverflow) || 3605 ((result & APFloat::opUnderflow) && Val.isZero())) { 3606 unsigned diagnostic; 3607 SmallString<20> buffer; 3608 if (result & APFloat::opOverflow) { 3609 diagnostic = diag::warn_float_overflow; 3610 APFloat::getLargest(Format).toString(buffer); 3611 } else { 3612 diagnostic = diag::warn_float_underflow; 3613 APFloat::getSmallest(Format).toString(buffer); 3614 } 3615 3616 S.Diag(Loc, diagnostic) 3617 << Ty 3618 << StringRef(buffer.data(), buffer.size()); 3619 } 3620 3621 bool isExact = (result == APFloat::opOK); 3622 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3623 } 3624 3625 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3626 assert(E && "Invalid expression"); 3627 3628 if (E->isValueDependent()) 3629 return false; 3630 3631 QualType QT = E->getType(); 3632 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3633 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3634 return true; 3635 } 3636 3637 llvm::APSInt ValueAPS; 3638 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3639 3640 if (R.isInvalid()) 3641 return true; 3642 3643 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3644 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3645 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3646 << ValueAPS.toString(10) << ValueIsPositive; 3647 return true; 3648 } 3649 3650 return false; 3651 } 3652 3653 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3654 // Fast path for a single digit (which is quite common). A single digit 3655 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3656 if (Tok.getLength() == 1) { 3657 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3658 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3659 } 3660 3661 SmallString<128> SpellingBuffer; 3662 // NumericLiteralParser wants to overread by one character. Add padding to 3663 // the buffer in case the token is copied to the buffer. If getSpelling() 3664 // returns a StringRef to the memory buffer, it should have a null char at 3665 // the EOF, so it is also safe. 3666 SpellingBuffer.resize(Tok.getLength() + 1); 3667 3668 // Get the spelling of the token, which eliminates trigraphs, etc. 3669 bool Invalid = false; 3670 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3671 if (Invalid) 3672 return ExprError(); 3673 3674 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3675 PP.getSourceManager(), PP.getLangOpts(), 3676 PP.getTargetInfo(), PP.getDiagnostics()); 3677 if (Literal.hadError) 3678 return ExprError(); 3679 3680 if (Literal.hasUDSuffix()) { 3681 // We're building a user-defined literal. 3682 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3683 SourceLocation UDSuffixLoc = 3684 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3685 3686 // Make sure we're allowed user-defined literals here. 3687 if (!UDLScope) 3688 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3689 3690 QualType CookedTy; 3691 if (Literal.isFloatingLiteral()) { 3692 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3693 // long double, the literal is treated as a call of the form 3694 // operator "" X (f L) 3695 CookedTy = Context.LongDoubleTy; 3696 } else { 3697 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3698 // unsigned long long, the literal is treated as a call of the form 3699 // operator "" X (n ULL) 3700 CookedTy = Context.UnsignedLongLongTy; 3701 } 3702 3703 DeclarationName OpName = 3704 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3705 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3706 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3707 3708 SourceLocation TokLoc = Tok.getLocation(); 3709 3710 // Perform literal operator lookup to determine if we're building a raw 3711 // literal or a cooked one. 3712 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3713 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3714 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3715 /*AllowStringTemplatePack*/ false, 3716 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3717 case LOLR_ErrorNoDiagnostic: 3718 // Lookup failure for imaginary constants isn't fatal, there's still the 3719 // GNU extension producing _Complex types. 3720 break; 3721 case LOLR_Error: 3722 return ExprError(); 3723 case LOLR_Cooked: { 3724 Expr *Lit; 3725 if (Literal.isFloatingLiteral()) { 3726 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3727 } else { 3728 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3729 if (Literal.GetIntegerValue(ResultVal)) 3730 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3731 << /* Unsigned */ 1; 3732 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3733 Tok.getLocation()); 3734 } 3735 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3736 } 3737 3738 case LOLR_Raw: { 3739 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3740 // literal is treated as a call of the form 3741 // operator "" X ("n") 3742 unsigned Length = Literal.getUDSuffixOffset(); 3743 QualType StrTy = Context.getConstantArrayType( 3744 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3745 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3746 Expr *Lit = StringLiteral::Create( 3747 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3748 /*Pascal*/false, StrTy, &TokLoc, 1); 3749 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3750 } 3751 3752 case LOLR_Template: { 3753 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3754 // template), L is treated as a call fo the form 3755 // operator "" X <'c1', 'c2', ... 'ck'>() 3756 // where n is the source character sequence c1 c2 ... ck. 3757 TemplateArgumentListInfo ExplicitArgs; 3758 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3759 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3760 llvm::APSInt Value(CharBits, CharIsUnsigned); 3761 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3762 Value = TokSpelling[I]; 3763 TemplateArgument Arg(Context, Value, Context.CharTy); 3764 TemplateArgumentLocInfo ArgInfo; 3765 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3766 } 3767 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3768 &ExplicitArgs); 3769 } 3770 case LOLR_StringTemplatePack: 3771 llvm_unreachable("unexpected literal operator lookup result"); 3772 } 3773 } 3774 3775 Expr *Res; 3776 3777 if (Literal.isFixedPointLiteral()) { 3778 QualType Ty; 3779 3780 if (Literal.isAccum) { 3781 if (Literal.isHalf) { 3782 Ty = Context.ShortAccumTy; 3783 } else if (Literal.isLong) { 3784 Ty = Context.LongAccumTy; 3785 } else { 3786 Ty = Context.AccumTy; 3787 } 3788 } else if (Literal.isFract) { 3789 if (Literal.isHalf) { 3790 Ty = Context.ShortFractTy; 3791 } else if (Literal.isLong) { 3792 Ty = Context.LongFractTy; 3793 } else { 3794 Ty = Context.FractTy; 3795 } 3796 } 3797 3798 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3799 3800 bool isSigned = !Literal.isUnsigned; 3801 unsigned scale = Context.getFixedPointScale(Ty); 3802 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3803 3804 llvm::APInt Val(bit_width, 0, isSigned); 3805 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3806 bool ValIsZero = Val.isNullValue() && !Overflowed; 3807 3808 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3809 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3810 // Clause 6.4.4 - The value of a constant shall be in the range of 3811 // representable values for its type, with exception for constants of a 3812 // fract type with a value of exactly 1; such a constant shall denote 3813 // the maximal value for the type. 3814 --Val; 3815 else if (Val.ugt(MaxVal) || Overflowed) 3816 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3817 3818 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3819 Tok.getLocation(), scale); 3820 } else if (Literal.isFloatingLiteral()) { 3821 QualType Ty; 3822 if (Literal.isHalf){ 3823 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3824 Ty = Context.HalfTy; 3825 else { 3826 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3827 return ExprError(); 3828 } 3829 } else if (Literal.isFloat) 3830 Ty = Context.FloatTy; 3831 else if (Literal.isLong) 3832 Ty = Context.LongDoubleTy; 3833 else if (Literal.isFloat16) 3834 Ty = Context.Float16Ty; 3835 else if (Literal.isFloat128) 3836 Ty = Context.Float128Ty; 3837 else 3838 Ty = Context.DoubleTy; 3839 3840 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3841 3842 if (Ty == Context.DoubleTy) { 3843 if (getLangOpts().SinglePrecisionConstants) { 3844 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3845 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3846 } 3847 } else if (getLangOpts().OpenCL && 3848 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3849 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3850 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3851 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3852 } 3853 } 3854 } else if (!Literal.isIntegerLiteral()) { 3855 return ExprError(); 3856 } else { 3857 QualType Ty; 3858 3859 // 'long long' is a C99 or C++11 feature. 3860 if (!getLangOpts().C99 && Literal.isLongLong) { 3861 if (getLangOpts().CPlusPlus) 3862 Diag(Tok.getLocation(), 3863 getLangOpts().CPlusPlus11 ? 3864 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3865 else 3866 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3867 } 3868 3869 // Get the value in the widest-possible width. 3870 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3871 llvm::APInt ResultVal(MaxWidth, 0); 3872 3873 if (Literal.GetIntegerValue(ResultVal)) { 3874 // If this value didn't fit into uintmax_t, error and force to ull. 3875 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3876 << /* Unsigned */ 1; 3877 Ty = Context.UnsignedLongLongTy; 3878 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3879 "long long is not intmax_t?"); 3880 } else { 3881 // If this value fits into a ULL, try to figure out what else it fits into 3882 // according to the rules of C99 6.4.4.1p5. 3883 3884 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3885 // be an unsigned int. 3886 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3887 3888 // Check from smallest to largest, picking the smallest type we can. 3889 unsigned Width = 0; 3890 3891 // Microsoft specific integer suffixes are explicitly sized. 3892 if (Literal.MicrosoftInteger) { 3893 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3894 Width = 8; 3895 Ty = Context.CharTy; 3896 } else { 3897 Width = Literal.MicrosoftInteger; 3898 Ty = Context.getIntTypeForBitwidth(Width, 3899 /*Signed=*/!Literal.isUnsigned); 3900 } 3901 } 3902 3903 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3904 // Are int/unsigned possibilities? 3905 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3906 3907 // Does it fit in a unsigned int? 3908 if (ResultVal.isIntN(IntSize)) { 3909 // Does it fit in a signed int? 3910 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3911 Ty = Context.IntTy; 3912 else if (AllowUnsigned) 3913 Ty = Context.UnsignedIntTy; 3914 Width = IntSize; 3915 } 3916 } 3917 3918 // Are long/unsigned long possibilities? 3919 if (Ty.isNull() && !Literal.isLongLong) { 3920 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3921 3922 // Does it fit in a unsigned long? 3923 if (ResultVal.isIntN(LongSize)) { 3924 // Does it fit in a signed long? 3925 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3926 Ty = Context.LongTy; 3927 else if (AllowUnsigned) 3928 Ty = Context.UnsignedLongTy; 3929 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3930 // is compatible. 3931 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3932 const unsigned LongLongSize = 3933 Context.getTargetInfo().getLongLongWidth(); 3934 Diag(Tok.getLocation(), 3935 getLangOpts().CPlusPlus 3936 ? Literal.isLong 3937 ? diag::warn_old_implicitly_unsigned_long_cxx 3938 : /*C++98 UB*/ diag:: 3939 ext_old_implicitly_unsigned_long_cxx 3940 : diag::warn_old_implicitly_unsigned_long) 3941 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3942 : /*will be ill-formed*/ 1); 3943 Ty = Context.UnsignedLongTy; 3944 } 3945 Width = LongSize; 3946 } 3947 } 3948 3949 // Check long long if needed. 3950 if (Ty.isNull()) { 3951 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3952 3953 // Does it fit in a unsigned long long? 3954 if (ResultVal.isIntN(LongLongSize)) { 3955 // Does it fit in a signed long long? 3956 // To be compatible with MSVC, hex integer literals ending with the 3957 // LL or i64 suffix are always signed in Microsoft mode. 3958 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3959 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3960 Ty = Context.LongLongTy; 3961 else if (AllowUnsigned) 3962 Ty = Context.UnsignedLongLongTy; 3963 Width = LongLongSize; 3964 } 3965 } 3966 3967 // If we still couldn't decide a type, we probably have something that 3968 // does not fit in a signed long long, but has no U suffix. 3969 if (Ty.isNull()) { 3970 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3971 Ty = Context.UnsignedLongLongTy; 3972 Width = Context.getTargetInfo().getLongLongWidth(); 3973 } 3974 3975 if (ResultVal.getBitWidth() != Width) 3976 ResultVal = ResultVal.trunc(Width); 3977 } 3978 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3979 } 3980 3981 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3982 if (Literal.isImaginary) { 3983 Res = new (Context) ImaginaryLiteral(Res, 3984 Context.getComplexType(Res->getType())); 3985 3986 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3987 } 3988 return Res; 3989 } 3990 3991 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3992 assert(E && "ActOnParenExpr() missing expr"); 3993 return new (Context) ParenExpr(L, R, E); 3994 } 3995 3996 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3997 SourceLocation Loc, 3998 SourceRange ArgRange) { 3999 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4000 // scalar or vector data type argument..." 4001 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4002 // type (C99 6.2.5p18) or void. 4003 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4004 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4005 << T << ArgRange; 4006 return true; 4007 } 4008 4009 assert((T->isVoidType() || !T->isIncompleteType()) && 4010 "Scalar types should always be complete"); 4011 return false; 4012 } 4013 4014 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4015 SourceLocation Loc, 4016 SourceRange ArgRange, 4017 UnaryExprOrTypeTrait TraitKind) { 4018 // Invalid types must be hard errors for SFINAE in C++. 4019 if (S.LangOpts.CPlusPlus) 4020 return true; 4021 4022 // C99 6.5.3.4p1: 4023 if (T->isFunctionType() && 4024 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4025 TraitKind == UETT_PreferredAlignOf)) { 4026 // sizeof(function)/alignof(function) is allowed as an extension. 4027 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4028 << getTraitSpelling(TraitKind) << ArgRange; 4029 return false; 4030 } 4031 4032 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4033 // this is an error (OpenCL v1.1 s6.3.k) 4034 if (T->isVoidType()) { 4035 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4036 : diag::ext_sizeof_alignof_void_type; 4037 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4038 return false; 4039 } 4040 4041 return true; 4042 } 4043 4044 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4045 SourceLocation Loc, 4046 SourceRange ArgRange, 4047 UnaryExprOrTypeTrait TraitKind) { 4048 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4049 // runtime doesn't allow it. 4050 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4051 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4052 << T << (TraitKind == UETT_SizeOf) 4053 << ArgRange; 4054 return true; 4055 } 4056 4057 return false; 4058 } 4059 4060 /// Check whether E is a pointer from a decayed array type (the decayed 4061 /// pointer type is equal to T) and emit a warning if it is. 4062 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4063 Expr *E) { 4064 // Don't warn if the operation changed the type. 4065 if (T != E->getType()) 4066 return; 4067 4068 // Now look for array decays. 4069 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4070 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4071 return; 4072 4073 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4074 << ICE->getType() 4075 << ICE->getSubExpr()->getType(); 4076 } 4077 4078 /// Check the constraints on expression operands to unary type expression 4079 /// and type traits. 4080 /// 4081 /// Completes any types necessary and validates the constraints on the operand 4082 /// expression. The logic mostly mirrors the type-based overload, but may modify 4083 /// the expression as it completes the type for that expression through template 4084 /// instantiation, etc. 4085 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4086 UnaryExprOrTypeTrait ExprKind) { 4087 QualType ExprTy = E->getType(); 4088 assert(!ExprTy->isReferenceType()); 4089 4090 bool IsUnevaluatedOperand = 4091 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4092 ExprKind == UETT_PreferredAlignOf); 4093 if (IsUnevaluatedOperand) { 4094 ExprResult Result = CheckUnevaluatedOperand(E); 4095 if (Result.isInvalid()) 4096 return true; 4097 E = Result.get(); 4098 } 4099 4100 if (ExprKind == UETT_VecStep) 4101 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4102 E->getSourceRange()); 4103 4104 // Explicitly list some types as extensions. 4105 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4106 E->getSourceRange(), ExprKind)) 4107 return false; 4108 4109 // 'alignof' applied to an expression only requires the base element type of 4110 // the expression to be complete. 'sizeof' requires the expression's type to 4111 // be complete (and will attempt to complete it if it's an array of unknown 4112 // bound). 4113 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4114 if (RequireCompleteSizedType( 4115 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4116 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4117 getTraitSpelling(ExprKind), E->getSourceRange())) 4118 return true; 4119 } else { 4120 if (RequireCompleteSizedExprType( 4121 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4122 getTraitSpelling(ExprKind), E->getSourceRange())) 4123 return true; 4124 } 4125 4126 // Completing the expression's type may have changed it. 4127 ExprTy = E->getType(); 4128 assert(!ExprTy->isReferenceType()); 4129 4130 if (ExprTy->isFunctionType()) { 4131 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4132 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4133 return true; 4134 } 4135 4136 // The operand for sizeof and alignof is in an unevaluated expression context, 4137 // so side effects could result in unintended consequences. 4138 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4139 E->HasSideEffects(Context, false)) 4140 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4141 4142 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4143 E->getSourceRange(), ExprKind)) 4144 return true; 4145 4146 if (ExprKind == UETT_SizeOf) { 4147 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4148 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4149 QualType OType = PVD->getOriginalType(); 4150 QualType Type = PVD->getType(); 4151 if (Type->isPointerType() && OType->isArrayType()) { 4152 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4153 << Type << OType; 4154 Diag(PVD->getLocation(), diag::note_declared_at); 4155 } 4156 } 4157 } 4158 4159 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4160 // decays into a pointer and returns an unintended result. This is most 4161 // likely a typo for "sizeof(array) op x". 4162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4163 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4164 BO->getLHS()); 4165 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4166 BO->getRHS()); 4167 } 4168 } 4169 4170 return false; 4171 } 4172 4173 /// Check the constraints on operands to unary expression and type 4174 /// traits. 4175 /// 4176 /// This will complete any types necessary, and validate the various constraints 4177 /// on those operands. 4178 /// 4179 /// The UsualUnaryConversions() function is *not* called by this routine. 4180 /// C99 6.3.2.1p[2-4] all state: 4181 /// Except when it is the operand of the sizeof operator ... 4182 /// 4183 /// C++ [expr.sizeof]p4 4184 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4185 /// standard conversions are not applied to the operand of sizeof. 4186 /// 4187 /// This policy is followed for all of the unary trait expressions. 4188 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4189 SourceLocation OpLoc, 4190 SourceRange ExprRange, 4191 UnaryExprOrTypeTrait ExprKind) { 4192 if (ExprType->isDependentType()) 4193 return false; 4194 4195 // C++ [expr.sizeof]p2: 4196 // When applied to a reference or a reference type, the result 4197 // is the size of the referenced type. 4198 // C++11 [expr.alignof]p3: 4199 // When alignof is applied to a reference type, the result 4200 // shall be the alignment of the referenced type. 4201 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4202 ExprType = Ref->getPointeeType(); 4203 4204 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4205 // When alignof or _Alignof is applied to an array type, the result 4206 // is the alignment of the element type. 4207 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4208 ExprKind == UETT_OpenMPRequiredSimdAlign) 4209 ExprType = Context.getBaseElementType(ExprType); 4210 4211 if (ExprKind == UETT_VecStep) 4212 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4213 4214 // Explicitly list some types as extensions. 4215 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4216 ExprKind)) 4217 return false; 4218 4219 if (RequireCompleteSizedType( 4220 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4221 getTraitSpelling(ExprKind), ExprRange)) 4222 return true; 4223 4224 if (ExprType->isFunctionType()) { 4225 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4226 << getTraitSpelling(ExprKind) << ExprRange; 4227 return true; 4228 } 4229 4230 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4231 ExprKind)) 4232 return true; 4233 4234 return false; 4235 } 4236 4237 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4238 // Cannot know anything else if the expression is dependent. 4239 if (E->isTypeDependent()) 4240 return false; 4241 4242 if (E->getObjectKind() == OK_BitField) { 4243 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4244 << 1 << E->getSourceRange(); 4245 return true; 4246 } 4247 4248 ValueDecl *D = nullptr; 4249 Expr *Inner = E->IgnoreParens(); 4250 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4251 D = DRE->getDecl(); 4252 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4253 D = ME->getMemberDecl(); 4254 } 4255 4256 // If it's a field, require the containing struct to have a 4257 // complete definition so that we can compute the layout. 4258 // 4259 // This can happen in C++11 onwards, either by naming the member 4260 // in a way that is not transformed into a member access expression 4261 // (in an unevaluated operand, for instance), or by naming the member 4262 // in a trailing-return-type. 4263 // 4264 // For the record, since __alignof__ on expressions is a GCC 4265 // extension, GCC seems to permit this but always gives the 4266 // nonsensical answer 0. 4267 // 4268 // We don't really need the layout here --- we could instead just 4269 // directly check for all the appropriate alignment-lowing 4270 // attributes --- but that would require duplicating a lot of 4271 // logic that just isn't worth duplicating for such a marginal 4272 // use-case. 4273 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4274 // Fast path this check, since we at least know the record has a 4275 // definition if we can find a member of it. 4276 if (!FD->getParent()->isCompleteDefinition()) { 4277 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4278 << E->getSourceRange(); 4279 return true; 4280 } 4281 4282 // Otherwise, if it's a field, and the field doesn't have 4283 // reference type, then it must have a complete type (or be a 4284 // flexible array member, which we explicitly want to 4285 // white-list anyway), which makes the following checks trivial. 4286 if (!FD->getType()->isReferenceType()) 4287 return false; 4288 } 4289 4290 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4291 } 4292 4293 bool Sema::CheckVecStepExpr(Expr *E) { 4294 E = E->IgnoreParens(); 4295 4296 // Cannot know anything else if the expression is dependent. 4297 if (E->isTypeDependent()) 4298 return false; 4299 4300 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4301 } 4302 4303 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4304 CapturingScopeInfo *CSI) { 4305 assert(T->isVariablyModifiedType()); 4306 assert(CSI != nullptr); 4307 4308 // We're going to walk down into the type and look for VLA expressions. 4309 do { 4310 const Type *Ty = T.getTypePtr(); 4311 switch (Ty->getTypeClass()) { 4312 #define TYPE(Class, Base) 4313 #define ABSTRACT_TYPE(Class, Base) 4314 #define NON_CANONICAL_TYPE(Class, Base) 4315 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4316 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4317 #include "clang/AST/TypeNodes.inc" 4318 T = QualType(); 4319 break; 4320 // These types are never variably-modified. 4321 case Type::Builtin: 4322 case Type::Complex: 4323 case Type::Vector: 4324 case Type::ExtVector: 4325 case Type::ConstantMatrix: 4326 case Type::Record: 4327 case Type::Enum: 4328 case Type::Elaborated: 4329 case Type::TemplateSpecialization: 4330 case Type::ObjCObject: 4331 case Type::ObjCInterface: 4332 case Type::ObjCObjectPointer: 4333 case Type::ObjCTypeParam: 4334 case Type::Pipe: 4335 case Type::ExtInt: 4336 llvm_unreachable("type class is never variably-modified!"); 4337 case Type::Adjusted: 4338 T = cast<AdjustedType>(Ty)->getOriginalType(); 4339 break; 4340 case Type::Decayed: 4341 T = cast<DecayedType>(Ty)->getPointeeType(); 4342 break; 4343 case Type::Pointer: 4344 T = cast<PointerType>(Ty)->getPointeeType(); 4345 break; 4346 case Type::BlockPointer: 4347 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4348 break; 4349 case Type::LValueReference: 4350 case Type::RValueReference: 4351 T = cast<ReferenceType>(Ty)->getPointeeType(); 4352 break; 4353 case Type::MemberPointer: 4354 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4355 break; 4356 case Type::ConstantArray: 4357 case Type::IncompleteArray: 4358 // Losing element qualification here is fine. 4359 T = cast<ArrayType>(Ty)->getElementType(); 4360 break; 4361 case Type::VariableArray: { 4362 // Losing element qualification here is fine. 4363 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4364 4365 // Unknown size indication requires no size computation. 4366 // Otherwise, evaluate and record it. 4367 auto Size = VAT->getSizeExpr(); 4368 if (Size && !CSI->isVLATypeCaptured(VAT) && 4369 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4370 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4371 4372 T = VAT->getElementType(); 4373 break; 4374 } 4375 case Type::FunctionProto: 4376 case Type::FunctionNoProto: 4377 T = cast<FunctionType>(Ty)->getReturnType(); 4378 break; 4379 case Type::Paren: 4380 case Type::TypeOf: 4381 case Type::UnaryTransform: 4382 case Type::Attributed: 4383 case Type::SubstTemplateTypeParm: 4384 case Type::MacroQualified: 4385 // Keep walking after single level desugaring. 4386 T = T.getSingleStepDesugaredType(Context); 4387 break; 4388 case Type::Typedef: 4389 T = cast<TypedefType>(Ty)->desugar(); 4390 break; 4391 case Type::Decltype: 4392 T = cast<DecltypeType>(Ty)->desugar(); 4393 break; 4394 case Type::Auto: 4395 case Type::DeducedTemplateSpecialization: 4396 T = cast<DeducedType>(Ty)->getDeducedType(); 4397 break; 4398 case Type::TypeOfExpr: 4399 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4400 break; 4401 case Type::Atomic: 4402 T = cast<AtomicType>(Ty)->getValueType(); 4403 break; 4404 } 4405 } while (!T.isNull() && T->isVariablyModifiedType()); 4406 } 4407 4408 /// Build a sizeof or alignof expression given a type operand. 4409 ExprResult 4410 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4411 SourceLocation OpLoc, 4412 UnaryExprOrTypeTrait ExprKind, 4413 SourceRange R) { 4414 if (!TInfo) 4415 return ExprError(); 4416 4417 QualType T = TInfo->getType(); 4418 4419 if (!T->isDependentType() && 4420 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4421 return ExprError(); 4422 4423 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4424 if (auto *TT = T->getAs<TypedefType>()) { 4425 for (auto I = FunctionScopes.rbegin(), 4426 E = std::prev(FunctionScopes.rend()); 4427 I != E; ++I) { 4428 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4429 if (CSI == nullptr) 4430 break; 4431 DeclContext *DC = nullptr; 4432 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4433 DC = LSI->CallOperator; 4434 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4435 DC = CRSI->TheCapturedDecl; 4436 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4437 DC = BSI->TheDecl; 4438 if (DC) { 4439 if (DC->containsDecl(TT->getDecl())) 4440 break; 4441 captureVariablyModifiedType(Context, T, CSI); 4442 } 4443 } 4444 } 4445 } 4446 4447 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4448 return new (Context) UnaryExprOrTypeTraitExpr( 4449 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4450 } 4451 4452 /// Build a sizeof or alignof expression given an expression 4453 /// operand. 4454 ExprResult 4455 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4456 UnaryExprOrTypeTrait ExprKind) { 4457 ExprResult PE = CheckPlaceholderExpr(E); 4458 if (PE.isInvalid()) 4459 return ExprError(); 4460 4461 E = PE.get(); 4462 4463 // Verify that the operand is valid. 4464 bool isInvalid = false; 4465 if (E->isTypeDependent()) { 4466 // Delay type-checking for type-dependent expressions. 4467 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4468 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4469 } else if (ExprKind == UETT_VecStep) { 4470 isInvalid = CheckVecStepExpr(E); 4471 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4472 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4473 isInvalid = true; 4474 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4475 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4476 isInvalid = true; 4477 } else { 4478 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4479 } 4480 4481 if (isInvalid) 4482 return ExprError(); 4483 4484 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4485 PE = TransformToPotentiallyEvaluated(E); 4486 if (PE.isInvalid()) return ExprError(); 4487 E = PE.get(); 4488 } 4489 4490 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4491 return new (Context) UnaryExprOrTypeTraitExpr( 4492 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4493 } 4494 4495 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4496 /// expr and the same for @c alignof and @c __alignof 4497 /// Note that the ArgRange is invalid if isType is false. 4498 ExprResult 4499 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4500 UnaryExprOrTypeTrait ExprKind, bool IsType, 4501 void *TyOrEx, SourceRange ArgRange) { 4502 // If error parsing type, ignore. 4503 if (!TyOrEx) return ExprError(); 4504 4505 if (IsType) { 4506 TypeSourceInfo *TInfo; 4507 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4508 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4509 } 4510 4511 Expr *ArgEx = (Expr *)TyOrEx; 4512 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4513 return Result; 4514 } 4515 4516 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4517 bool IsReal) { 4518 if (V.get()->isTypeDependent()) 4519 return S.Context.DependentTy; 4520 4521 // _Real and _Imag are only l-values for normal l-values. 4522 if (V.get()->getObjectKind() != OK_Ordinary) { 4523 V = S.DefaultLvalueConversion(V.get()); 4524 if (V.isInvalid()) 4525 return QualType(); 4526 } 4527 4528 // These operators return the element type of a complex type. 4529 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4530 return CT->getElementType(); 4531 4532 // Otherwise they pass through real integer and floating point types here. 4533 if (V.get()->getType()->isArithmeticType()) 4534 return V.get()->getType(); 4535 4536 // Test for placeholders. 4537 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4538 if (PR.isInvalid()) return QualType(); 4539 if (PR.get() != V.get()) { 4540 V = PR; 4541 return CheckRealImagOperand(S, V, Loc, IsReal); 4542 } 4543 4544 // Reject anything else. 4545 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4546 << (IsReal ? "__real" : "__imag"); 4547 return QualType(); 4548 } 4549 4550 4551 4552 ExprResult 4553 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4554 tok::TokenKind Kind, Expr *Input) { 4555 UnaryOperatorKind Opc; 4556 switch (Kind) { 4557 default: llvm_unreachable("Unknown unary op!"); 4558 case tok::plusplus: Opc = UO_PostInc; break; 4559 case tok::minusminus: Opc = UO_PostDec; break; 4560 } 4561 4562 // Since this might is a postfix expression, get rid of ParenListExprs. 4563 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4564 if (Result.isInvalid()) return ExprError(); 4565 Input = Result.get(); 4566 4567 return BuildUnaryOp(S, OpLoc, Opc, Input); 4568 } 4569 4570 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4571 /// 4572 /// \return true on error 4573 static bool checkArithmeticOnObjCPointer(Sema &S, 4574 SourceLocation opLoc, 4575 Expr *op) { 4576 assert(op->getType()->isObjCObjectPointerType()); 4577 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4578 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4579 return false; 4580 4581 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4582 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4583 << op->getSourceRange(); 4584 return true; 4585 } 4586 4587 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4588 auto *BaseNoParens = Base->IgnoreParens(); 4589 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4590 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4591 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4592 } 4593 4594 ExprResult 4595 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4596 Expr *idx, SourceLocation rbLoc) { 4597 if (base && !base->getType().isNull() && 4598 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4599 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4600 SourceLocation(), /*Length*/ nullptr, 4601 /*Stride=*/nullptr, rbLoc); 4602 4603 // Since this might be a postfix expression, get rid of ParenListExprs. 4604 if (isa<ParenListExpr>(base)) { 4605 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4606 if (result.isInvalid()) return ExprError(); 4607 base = result.get(); 4608 } 4609 4610 // Check if base and idx form a MatrixSubscriptExpr. 4611 // 4612 // Helper to check for comma expressions, which are not allowed as indices for 4613 // matrix subscript expressions. 4614 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4615 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4616 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4617 << SourceRange(base->getBeginLoc(), rbLoc); 4618 return true; 4619 } 4620 return false; 4621 }; 4622 // The matrix subscript operator ([][])is considered a single operator. 4623 // Separating the index expressions by parenthesis is not allowed. 4624 if (base->getType()->isSpecificPlaceholderType( 4625 BuiltinType::IncompleteMatrixIdx) && 4626 !isa<MatrixSubscriptExpr>(base)) { 4627 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4628 << SourceRange(base->getBeginLoc(), rbLoc); 4629 return ExprError(); 4630 } 4631 // If the base is a MatrixSubscriptExpr, try to create a new 4632 // MatrixSubscriptExpr. 4633 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4634 if (matSubscriptE) { 4635 if (CheckAndReportCommaError(idx)) 4636 return ExprError(); 4637 4638 assert(matSubscriptE->isIncomplete() && 4639 "base has to be an incomplete matrix subscript"); 4640 return CreateBuiltinMatrixSubscriptExpr( 4641 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4642 } 4643 4644 // Handle any non-overload placeholder types in the base and index 4645 // expressions. We can't handle overloads here because the other 4646 // operand might be an overloadable type, in which case the overload 4647 // resolution for the operator overload should get the first crack 4648 // at the overload. 4649 bool IsMSPropertySubscript = false; 4650 if (base->getType()->isNonOverloadPlaceholderType()) { 4651 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4652 if (!IsMSPropertySubscript) { 4653 ExprResult result = CheckPlaceholderExpr(base); 4654 if (result.isInvalid()) 4655 return ExprError(); 4656 base = result.get(); 4657 } 4658 } 4659 4660 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4661 if (base->getType()->isMatrixType()) { 4662 if (CheckAndReportCommaError(idx)) 4663 return ExprError(); 4664 4665 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4666 } 4667 4668 // A comma-expression as the index is deprecated in C++2a onwards. 4669 if (getLangOpts().CPlusPlus20 && 4670 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4671 (isa<CXXOperatorCallExpr>(idx) && 4672 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4673 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4674 << SourceRange(base->getBeginLoc(), rbLoc); 4675 } 4676 4677 if (idx->getType()->isNonOverloadPlaceholderType()) { 4678 ExprResult result = CheckPlaceholderExpr(idx); 4679 if (result.isInvalid()) return ExprError(); 4680 idx = result.get(); 4681 } 4682 4683 // Build an unanalyzed expression if either operand is type-dependent. 4684 if (getLangOpts().CPlusPlus && 4685 (base->isTypeDependent() || idx->isTypeDependent())) { 4686 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4687 VK_LValue, OK_Ordinary, rbLoc); 4688 } 4689 4690 // MSDN, property (C++) 4691 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4692 // This attribute can also be used in the declaration of an empty array in a 4693 // class or structure definition. For example: 4694 // __declspec(property(get=GetX, put=PutX)) int x[]; 4695 // The above statement indicates that x[] can be used with one or more array 4696 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4697 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4698 if (IsMSPropertySubscript) { 4699 // Build MS property subscript expression if base is MS property reference 4700 // or MS property subscript. 4701 return new (Context) MSPropertySubscriptExpr( 4702 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4703 } 4704 4705 // Use C++ overloaded-operator rules if either operand has record 4706 // type. The spec says to do this if either type is *overloadable*, 4707 // but enum types can't declare subscript operators or conversion 4708 // operators, so there's nothing interesting for overload resolution 4709 // to do if there aren't any record types involved. 4710 // 4711 // ObjC pointers have their own subscripting logic that is not tied 4712 // to overload resolution and so should not take this path. 4713 if (getLangOpts().CPlusPlus && 4714 (base->getType()->isRecordType() || 4715 (!base->getType()->isObjCObjectPointerType() && 4716 idx->getType()->isRecordType()))) { 4717 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4718 } 4719 4720 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4721 4722 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4723 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4724 4725 return Res; 4726 } 4727 4728 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4729 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4730 InitializationKind Kind = 4731 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4732 InitializationSequence InitSeq(*this, Entity, Kind, E); 4733 return InitSeq.Perform(*this, Entity, Kind, E); 4734 } 4735 4736 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4737 Expr *ColumnIdx, 4738 SourceLocation RBLoc) { 4739 ExprResult BaseR = CheckPlaceholderExpr(Base); 4740 if (BaseR.isInvalid()) 4741 return BaseR; 4742 Base = BaseR.get(); 4743 4744 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4745 if (RowR.isInvalid()) 4746 return RowR; 4747 RowIdx = RowR.get(); 4748 4749 if (!ColumnIdx) 4750 return new (Context) MatrixSubscriptExpr( 4751 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4752 4753 // Build an unanalyzed expression if any of the operands is type-dependent. 4754 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4755 ColumnIdx->isTypeDependent()) 4756 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4757 Context.DependentTy, RBLoc); 4758 4759 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4760 if (ColumnR.isInvalid()) 4761 return ColumnR; 4762 ColumnIdx = ColumnR.get(); 4763 4764 // Check that IndexExpr is an integer expression. If it is a constant 4765 // expression, check that it is less than Dim (= the number of elements in the 4766 // corresponding dimension). 4767 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4768 bool IsColumnIdx) -> Expr * { 4769 if (!IndexExpr->getType()->isIntegerType() && 4770 !IndexExpr->isTypeDependent()) { 4771 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4772 << IsColumnIdx; 4773 return nullptr; 4774 } 4775 4776 if (Optional<llvm::APSInt> Idx = 4777 IndexExpr->getIntegerConstantExpr(Context)) { 4778 if ((*Idx < 0 || *Idx >= Dim)) { 4779 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4780 << IsColumnIdx << Dim; 4781 return nullptr; 4782 } 4783 } 4784 4785 ExprResult ConvExpr = 4786 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4787 assert(!ConvExpr.isInvalid() && 4788 "should be able to convert any integer type to size type"); 4789 return ConvExpr.get(); 4790 }; 4791 4792 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4793 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4794 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4795 if (!RowIdx || !ColumnIdx) 4796 return ExprError(); 4797 4798 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4799 MTy->getElementType(), RBLoc); 4800 } 4801 4802 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4803 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4804 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4805 4806 // For expressions like `&(*s).b`, the base is recorded and what should be 4807 // checked. 4808 const MemberExpr *Member = nullptr; 4809 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4810 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4811 4812 LastRecord.PossibleDerefs.erase(StrippedExpr); 4813 } 4814 4815 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4816 if (isUnevaluatedContext()) 4817 return; 4818 4819 QualType ResultTy = E->getType(); 4820 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4821 4822 // Bail if the element is an array since it is not memory access. 4823 if (isa<ArrayType>(ResultTy)) 4824 return; 4825 4826 if (ResultTy->hasAttr(attr::NoDeref)) { 4827 LastRecord.PossibleDerefs.insert(E); 4828 return; 4829 } 4830 4831 // Check if the base type is a pointer to a member access of a struct 4832 // marked with noderef. 4833 const Expr *Base = E->getBase(); 4834 QualType BaseTy = Base->getType(); 4835 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4836 // Not a pointer access 4837 return; 4838 4839 const MemberExpr *Member = nullptr; 4840 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4841 Member->isArrow()) 4842 Base = Member->getBase(); 4843 4844 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4845 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4846 LastRecord.PossibleDerefs.insert(E); 4847 } 4848 } 4849 4850 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4851 Expr *LowerBound, 4852 SourceLocation ColonLocFirst, 4853 SourceLocation ColonLocSecond, 4854 Expr *Length, Expr *Stride, 4855 SourceLocation RBLoc) { 4856 if (Base->getType()->isPlaceholderType() && 4857 !Base->getType()->isSpecificPlaceholderType( 4858 BuiltinType::OMPArraySection)) { 4859 ExprResult Result = CheckPlaceholderExpr(Base); 4860 if (Result.isInvalid()) 4861 return ExprError(); 4862 Base = Result.get(); 4863 } 4864 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4865 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4866 if (Result.isInvalid()) 4867 return ExprError(); 4868 Result = DefaultLvalueConversion(Result.get()); 4869 if (Result.isInvalid()) 4870 return ExprError(); 4871 LowerBound = Result.get(); 4872 } 4873 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4874 ExprResult Result = CheckPlaceholderExpr(Length); 4875 if (Result.isInvalid()) 4876 return ExprError(); 4877 Result = DefaultLvalueConversion(Result.get()); 4878 if (Result.isInvalid()) 4879 return ExprError(); 4880 Length = Result.get(); 4881 } 4882 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4883 ExprResult Result = CheckPlaceholderExpr(Stride); 4884 if (Result.isInvalid()) 4885 return ExprError(); 4886 Result = DefaultLvalueConversion(Result.get()); 4887 if (Result.isInvalid()) 4888 return ExprError(); 4889 Stride = Result.get(); 4890 } 4891 4892 // Build an unanalyzed expression if either operand is type-dependent. 4893 if (Base->isTypeDependent() || 4894 (LowerBound && 4895 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4896 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4897 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4898 return new (Context) OMPArraySectionExpr( 4899 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4900 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4901 } 4902 4903 // Perform default conversions. 4904 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4905 QualType ResultTy; 4906 if (OriginalTy->isAnyPointerType()) { 4907 ResultTy = OriginalTy->getPointeeType(); 4908 } else if (OriginalTy->isArrayType()) { 4909 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4910 } else { 4911 return ExprError( 4912 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4913 << Base->getSourceRange()); 4914 } 4915 // C99 6.5.2.1p1 4916 if (LowerBound) { 4917 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4918 LowerBound); 4919 if (Res.isInvalid()) 4920 return ExprError(Diag(LowerBound->getExprLoc(), 4921 diag::err_omp_typecheck_section_not_integer) 4922 << 0 << LowerBound->getSourceRange()); 4923 LowerBound = Res.get(); 4924 4925 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4926 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4927 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4928 << 0 << LowerBound->getSourceRange(); 4929 } 4930 if (Length) { 4931 auto Res = 4932 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4933 if (Res.isInvalid()) 4934 return ExprError(Diag(Length->getExprLoc(), 4935 diag::err_omp_typecheck_section_not_integer) 4936 << 1 << Length->getSourceRange()); 4937 Length = Res.get(); 4938 4939 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4940 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4941 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4942 << 1 << Length->getSourceRange(); 4943 } 4944 if (Stride) { 4945 ExprResult Res = 4946 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4947 if (Res.isInvalid()) 4948 return ExprError(Diag(Stride->getExprLoc(), 4949 diag::err_omp_typecheck_section_not_integer) 4950 << 1 << Stride->getSourceRange()); 4951 Stride = Res.get(); 4952 4953 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4954 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4955 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4956 << 1 << Stride->getSourceRange(); 4957 } 4958 4959 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4960 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4961 // type. Note that functions are not objects, and that (in C99 parlance) 4962 // incomplete types are not object types. 4963 if (ResultTy->isFunctionType()) { 4964 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4965 << ResultTy << Base->getSourceRange(); 4966 return ExprError(); 4967 } 4968 4969 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4970 diag::err_omp_section_incomplete_type, Base)) 4971 return ExprError(); 4972 4973 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4974 Expr::EvalResult Result; 4975 if (LowerBound->EvaluateAsInt(Result, Context)) { 4976 // OpenMP 5.0, [2.1.5 Array Sections] 4977 // The array section must be a subset of the original array. 4978 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4979 if (LowerBoundValue.isNegative()) { 4980 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4981 << LowerBound->getSourceRange(); 4982 return ExprError(); 4983 } 4984 } 4985 } 4986 4987 if (Length) { 4988 Expr::EvalResult Result; 4989 if (Length->EvaluateAsInt(Result, Context)) { 4990 // OpenMP 5.0, [2.1.5 Array Sections] 4991 // The length must evaluate to non-negative integers. 4992 llvm::APSInt LengthValue = Result.Val.getInt(); 4993 if (LengthValue.isNegative()) { 4994 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4995 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4996 << Length->getSourceRange(); 4997 return ExprError(); 4998 } 4999 } 5000 } else if (ColonLocFirst.isValid() && 5001 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5002 !OriginalTy->isVariableArrayType()))) { 5003 // OpenMP 5.0, [2.1.5 Array Sections] 5004 // When the size of the array dimension is not known, the length must be 5005 // specified explicitly. 5006 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5007 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5008 return ExprError(); 5009 } 5010 5011 if (Stride) { 5012 Expr::EvalResult Result; 5013 if (Stride->EvaluateAsInt(Result, Context)) { 5014 // OpenMP 5.0, [2.1.5 Array Sections] 5015 // The stride must evaluate to a positive integer. 5016 llvm::APSInt StrideValue = Result.Val.getInt(); 5017 if (!StrideValue.isStrictlyPositive()) { 5018 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5019 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5020 << Stride->getSourceRange(); 5021 return ExprError(); 5022 } 5023 } 5024 } 5025 5026 if (!Base->getType()->isSpecificPlaceholderType( 5027 BuiltinType::OMPArraySection)) { 5028 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5029 if (Result.isInvalid()) 5030 return ExprError(); 5031 Base = Result.get(); 5032 } 5033 return new (Context) OMPArraySectionExpr( 5034 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5035 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5036 } 5037 5038 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5039 SourceLocation RParenLoc, 5040 ArrayRef<Expr *> Dims, 5041 ArrayRef<SourceRange> Brackets) { 5042 if (Base->getType()->isPlaceholderType()) { 5043 ExprResult Result = CheckPlaceholderExpr(Base); 5044 if (Result.isInvalid()) 5045 return ExprError(); 5046 Result = DefaultLvalueConversion(Result.get()); 5047 if (Result.isInvalid()) 5048 return ExprError(); 5049 Base = Result.get(); 5050 } 5051 QualType BaseTy = Base->getType(); 5052 // Delay analysis of the types/expressions if instantiation/specialization is 5053 // required. 5054 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5055 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5056 LParenLoc, RParenLoc, Dims, Brackets); 5057 if (!BaseTy->isPointerType() || 5058 (!Base->isTypeDependent() && 5059 BaseTy->getPointeeType()->isIncompleteType())) 5060 return ExprError(Diag(Base->getExprLoc(), 5061 diag::err_omp_non_pointer_type_array_shaping_base) 5062 << Base->getSourceRange()); 5063 5064 SmallVector<Expr *, 4> NewDims; 5065 bool ErrorFound = false; 5066 for (Expr *Dim : Dims) { 5067 if (Dim->getType()->isPlaceholderType()) { 5068 ExprResult Result = CheckPlaceholderExpr(Dim); 5069 if (Result.isInvalid()) { 5070 ErrorFound = true; 5071 continue; 5072 } 5073 Result = DefaultLvalueConversion(Result.get()); 5074 if (Result.isInvalid()) { 5075 ErrorFound = true; 5076 continue; 5077 } 5078 Dim = Result.get(); 5079 } 5080 if (!Dim->isTypeDependent()) { 5081 ExprResult Result = 5082 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5083 if (Result.isInvalid()) { 5084 ErrorFound = true; 5085 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5086 << Dim->getSourceRange(); 5087 continue; 5088 } 5089 Dim = Result.get(); 5090 Expr::EvalResult EvResult; 5091 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5092 // OpenMP 5.0, [2.1.4 Array Shaping] 5093 // Each si is an integral type expression that must evaluate to a 5094 // positive integer. 5095 llvm::APSInt Value = EvResult.Val.getInt(); 5096 if (!Value.isStrictlyPositive()) { 5097 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5098 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5099 << Dim->getSourceRange(); 5100 ErrorFound = true; 5101 continue; 5102 } 5103 } 5104 } 5105 NewDims.push_back(Dim); 5106 } 5107 if (ErrorFound) 5108 return ExprError(); 5109 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5110 LParenLoc, RParenLoc, NewDims, Brackets); 5111 } 5112 5113 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5114 SourceLocation LLoc, SourceLocation RLoc, 5115 ArrayRef<OMPIteratorData> Data) { 5116 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5117 bool IsCorrect = true; 5118 for (const OMPIteratorData &D : Data) { 5119 TypeSourceInfo *TInfo = nullptr; 5120 SourceLocation StartLoc; 5121 QualType DeclTy; 5122 if (!D.Type.getAsOpaquePtr()) { 5123 // OpenMP 5.0, 2.1.6 Iterators 5124 // In an iterator-specifier, if the iterator-type is not specified then 5125 // the type of that iterator is of int type. 5126 DeclTy = Context.IntTy; 5127 StartLoc = D.DeclIdentLoc; 5128 } else { 5129 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5130 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5131 } 5132 5133 bool IsDeclTyDependent = DeclTy->isDependentType() || 5134 DeclTy->containsUnexpandedParameterPack() || 5135 DeclTy->isInstantiationDependentType(); 5136 if (!IsDeclTyDependent) { 5137 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5138 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5139 // The iterator-type must be an integral or pointer type. 5140 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5141 << DeclTy; 5142 IsCorrect = false; 5143 continue; 5144 } 5145 if (DeclTy.isConstant(Context)) { 5146 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5147 // The iterator-type must not be const qualified. 5148 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5149 << DeclTy; 5150 IsCorrect = false; 5151 continue; 5152 } 5153 } 5154 5155 // Iterator declaration. 5156 assert(D.DeclIdent && "Identifier expected."); 5157 // Always try to create iterator declarator to avoid extra error messages 5158 // about unknown declarations use. 5159 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5160 D.DeclIdent, DeclTy, TInfo, SC_None); 5161 VD->setImplicit(); 5162 if (S) { 5163 // Check for conflicting previous declaration. 5164 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5165 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5166 ForVisibleRedeclaration); 5167 Previous.suppressDiagnostics(); 5168 LookupName(Previous, S); 5169 5170 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5171 /*AllowInlineNamespace=*/false); 5172 if (!Previous.empty()) { 5173 NamedDecl *Old = Previous.getRepresentativeDecl(); 5174 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5175 Diag(Old->getLocation(), diag::note_previous_definition); 5176 } else { 5177 PushOnScopeChains(VD, S); 5178 } 5179 } else { 5180 CurContext->addDecl(VD); 5181 } 5182 Expr *Begin = D.Range.Begin; 5183 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5184 ExprResult BeginRes = 5185 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5186 Begin = BeginRes.get(); 5187 } 5188 Expr *End = D.Range.End; 5189 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5190 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5191 End = EndRes.get(); 5192 } 5193 Expr *Step = D.Range.Step; 5194 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5195 if (!Step->getType()->isIntegralType(Context)) { 5196 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5197 << Step << Step->getSourceRange(); 5198 IsCorrect = false; 5199 continue; 5200 } 5201 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5202 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5203 // If the step expression of a range-specification equals zero, the 5204 // behavior is unspecified. 5205 if (Result && Result->isNullValue()) { 5206 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5207 << Step << Step->getSourceRange(); 5208 IsCorrect = false; 5209 continue; 5210 } 5211 } 5212 if (!Begin || !End || !IsCorrect) { 5213 IsCorrect = false; 5214 continue; 5215 } 5216 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5217 IDElem.IteratorDecl = VD; 5218 IDElem.AssignmentLoc = D.AssignLoc; 5219 IDElem.Range.Begin = Begin; 5220 IDElem.Range.End = End; 5221 IDElem.Range.Step = Step; 5222 IDElem.ColonLoc = D.ColonLoc; 5223 IDElem.SecondColonLoc = D.SecColonLoc; 5224 } 5225 if (!IsCorrect) { 5226 // Invalidate all created iterator declarations if error is found. 5227 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5228 if (Decl *ID = D.IteratorDecl) 5229 ID->setInvalidDecl(); 5230 } 5231 return ExprError(); 5232 } 5233 SmallVector<OMPIteratorHelperData, 4> Helpers; 5234 if (!CurContext->isDependentContext()) { 5235 // Build number of ityeration for each iteration range. 5236 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5237 // ((Begini-Stepi-1-Endi) / -Stepi); 5238 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5239 // (Endi - Begini) 5240 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5241 D.Range.Begin); 5242 if(!Res.isUsable()) { 5243 IsCorrect = false; 5244 continue; 5245 } 5246 ExprResult St, St1; 5247 if (D.Range.Step) { 5248 St = D.Range.Step; 5249 // (Endi - Begini) + Stepi 5250 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5251 if (!Res.isUsable()) { 5252 IsCorrect = false; 5253 continue; 5254 } 5255 // (Endi - Begini) + Stepi - 1 5256 Res = 5257 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5258 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5259 if (!Res.isUsable()) { 5260 IsCorrect = false; 5261 continue; 5262 } 5263 // ((Endi - Begini) + Stepi - 1) / Stepi 5264 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5265 if (!Res.isUsable()) { 5266 IsCorrect = false; 5267 continue; 5268 } 5269 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5270 // (Begini - Endi) 5271 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5272 D.Range.Begin, D.Range.End); 5273 if (!Res1.isUsable()) { 5274 IsCorrect = false; 5275 continue; 5276 } 5277 // (Begini - Endi) - Stepi 5278 Res1 = 5279 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5280 if (!Res1.isUsable()) { 5281 IsCorrect = false; 5282 continue; 5283 } 5284 // (Begini - Endi) - Stepi - 1 5285 Res1 = 5286 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5287 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5288 if (!Res1.isUsable()) { 5289 IsCorrect = false; 5290 continue; 5291 } 5292 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5293 Res1 = 5294 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5295 if (!Res1.isUsable()) { 5296 IsCorrect = false; 5297 continue; 5298 } 5299 // Stepi > 0. 5300 ExprResult CmpRes = 5301 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5302 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5303 if (!CmpRes.isUsable()) { 5304 IsCorrect = false; 5305 continue; 5306 } 5307 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5308 Res.get(), Res1.get()); 5309 if (!Res.isUsable()) { 5310 IsCorrect = false; 5311 continue; 5312 } 5313 } 5314 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5315 if (!Res.isUsable()) { 5316 IsCorrect = false; 5317 continue; 5318 } 5319 5320 // Build counter update. 5321 // Build counter. 5322 auto *CounterVD = 5323 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5324 D.IteratorDecl->getBeginLoc(), nullptr, 5325 Res.get()->getType(), nullptr, SC_None); 5326 CounterVD->setImplicit(); 5327 ExprResult RefRes = 5328 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5329 D.IteratorDecl->getBeginLoc()); 5330 // Build counter update. 5331 // I = Begini + counter * Stepi; 5332 ExprResult UpdateRes; 5333 if (D.Range.Step) { 5334 UpdateRes = CreateBuiltinBinOp( 5335 D.AssignmentLoc, BO_Mul, 5336 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5337 } else { 5338 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5339 } 5340 if (!UpdateRes.isUsable()) { 5341 IsCorrect = false; 5342 continue; 5343 } 5344 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5345 UpdateRes.get()); 5346 if (!UpdateRes.isUsable()) { 5347 IsCorrect = false; 5348 continue; 5349 } 5350 ExprResult VDRes = 5351 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5352 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5353 D.IteratorDecl->getBeginLoc()); 5354 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5355 UpdateRes.get()); 5356 if (!UpdateRes.isUsable()) { 5357 IsCorrect = false; 5358 continue; 5359 } 5360 UpdateRes = 5361 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5362 if (!UpdateRes.isUsable()) { 5363 IsCorrect = false; 5364 continue; 5365 } 5366 ExprResult CounterUpdateRes = 5367 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5368 if (!CounterUpdateRes.isUsable()) { 5369 IsCorrect = false; 5370 continue; 5371 } 5372 CounterUpdateRes = 5373 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5374 if (!CounterUpdateRes.isUsable()) { 5375 IsCorrect = false; 5376 continue; 5377 } 5378 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5379 HD.CounterVD = CounterVD; 5380 HD.Upper = Res.get(); 5381 HD.Update = UpdateRes.get(); 5382 HD.CounterUpdate = CounterUpdateRes.get(); 5383 } 5384 } else { 5385 Helpers.assign(ID.size(), {}); 5386 } 5387 if (!IsCorrect) { 5388 // Invalidate all created iterator declarations if error is found. 5389 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5390 if (Decl *ID = D.IteratorDecl) 5391 ID->setInvalidDecl(); 5392 } 5393 return ExprError(); 5394 } 5395 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5396 LLoc, RLoc, ID, Helpers); 5397 } 5398 5399 ExprResult 5400 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5401 Expr *Idx, SourceLocation RLoc) { 5402 Expr *LHSExp = Base; 5403 Expr *RHSExp = Idx; 5404 5405 ExprValueKind VK = VK_LValue; 5406 ExprObjectKind OK = OK_Ordinary; 5407 5408 // Per C++ core issue 1213, the result is an xvalue if either operand is 5409 // a non-lvalue array, and an lvalue otherwise. 5410 if (getLangOpts().CPlusPlus11) { 5411 for (auto *Op : {LHSExp, RHSExp}) { 5412 Op = Op->IgnoreImplicit(); 5413 if (Op->getType()->isArrayType() && !Op->isLValue()) 5414 VK = VK_XValue; 5415 } 5416 } 5417 5418 // Perform default conversions. 5419 if (!LHSExp->getType()->getAs<VectorType>()) { 5420 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5421 if (Result.isInvalid()) 5422 return ExprError(); 5423 LHSExp = Result.get(); 5424 } 5425 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5426 if (Result.isInvalid()) 5427 return ExprError(); 5428 RHSExp = Result.get(); 5429 5430 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5431 5432 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5433 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5434 // in the subscript position. As a result, we need to derive the array base 5435 // and index from the expression types. 5436 Expr *BaseExpr, *IndexExpr; 5437 QualType ResultType; 5438 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5439 BaseExpr = LHSExp; 5440 IndexExpr = RHSExp; 5441 ResultType = Context.DependentTy; 5442 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5443 BaseExpr = LHSExp; 5444 IndexExpr = RHSExp; 5445 ResultType = PTy->getPointeeType(); 5446 } else if (const ObjCObjectPointerType *PTy = 5447 LHSTy->getAs<ObjCObjectPointerType>()) { 5448 BaseExpr = LHSExp; 5449 IndexExpr = RHSExp; 5450 5451 // Use custom logic if this should be the pseudo-object subscript 5452 // expression. 5453 if (!LangOpts.isSubscriptPointerArithmetic()) 5454 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5455 nullptr); 5456 5457 ResultType = PTy->getPointeeType(); 5458 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5459 // Handle the uncommon case of "123[Ptr]". 5460 BaseExpr = RHSExp; 5461 IndexExpr = LHSExp; 5462 ResultType = PTy->getPointeeType(); 5463 } else if (const ObjCObjectPointerType *PTy = 5464 RHSTy->getAs<ObjCObjectPointerType>()) { 5465 // Handle the uncommon case of "123[Ptr]". 5466 BaseExpr = RHSExp; 5467 IndexExpr = LHSExp; 5468 ResultType = PTy->getPointeeType(); 5469 if (!LangOpts.isSubscriptPointerArithmetic()) { 5470 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5471 << ResultType << BaseExpr->getSourceRange(); 5472 return ExprError(); 5473 } 5474 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5475 BaseExpr = LHSExp; // vectors: V[123] 5476 IndexExpr = RHSExp; 5477 // We apply C++ DR1213 to vector subscripting too. 5478 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5479 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5480 if (Materialized.isInvalid()) 5481 return ExprError(); 5482 LHSExp = Materialized.get(); 5483 } 5484 VK = LHSExp->getValueKind(); 5485 if (VK != VK_RValue) 5486 OK = OK_VectorComponent; 5487 5488 ResultType = VTy->getElementType(); 5489 QualType BaseType = BaseExpr->getType(); 5490 Qualifiers BaseQuals = BaseType.getQualifiers(); 5491 Qualifiers MemberQuals = ResultType.getQualifiers(); 5492 Qualifiers Combined = BaseQuals + MemberQuals; 5493 if (Combined != MemberQuals) 5494 ResultType = Context.getQualifiedType(ResultType, Combined); 5495 } else if (LHSTy->isArrayType()) { 5496 // If we see an array that wasn't promoted by 5497 // DefaultFunctionArrayLvalueConversion, it must be an array that 5498 // wasn't promoted because of the C90 rule that doesn't 5499 // allow promoting non-lvalue arrays. Warn, then 5500 // force the promotion here. 5501 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5502 << LHSExp->getSourceRange(); 5503 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5504 CK_ArrayToPointerDecay).get(); 5505 LHSTy = LHSExp->getType(); 5506 5507 BaseExpr = LHSExp; 5508 IndexExpr = RHSExp; 5509 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5510 } else if (RHSTy->isArrayType()) { 5511 // Same as previous, except for 123[f().a] case 5512 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5513 << RHSExp->getSourceRange(); 5514 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5515 CK_ArrayToPointerDecay).get(); 5516 RHSTy = RHSExp->getType(); 5517 5518 BaseExpr = RHSExp; 5519 IndexExpr = LHSExp; 5520 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5521 } else { 5522 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5523 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5524 } 5525 // C99 6.5.2.1p1 5526 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5527 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5528 << IndexExpr->getSourceRange()); 5529 5530 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5531 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5532 && !IndexExpr->isTypeDependent()) 5533 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5534 5535 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5536 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5537 // type. Note that Functions are not objects, and that (in C99 parlance) 5538 // incomplete types are not object types. 5539 if (ResultType->isFunctionType()) { 5540 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5541 << ResultType << BaseExpr->getSourceRange(); 5542 return ExprError(); 5543 } 5544 5545 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5546 // GNU extension: subscripting on pointer to void 5547 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5548 << BaseExpr->getSourceRange(); 5549 5550 // C forbids expressions of unqualified void type from being l-values. 5551 // See IsCForbiddenLValueType. 5552 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5553 } else if (!ResultType->isDependentType() && 5554 RequireCompleteSizedType( 5555 LLoc, ResultType, 5556 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5557 return ExprError(); 5558 5559 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5560 !ResultType.isCForbiddenLValueType()); 5561 5562 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5563 FunctionScopes.size() > 1) { 5564 if (auto *TT = 5565 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5566 for (auto I = FunctionScopes.rbegin(), 5567 E = std::prev(FunctionScopes.rend()); 5568 I != E; ++I) { 5569 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5570 if (CSI == nullptr) 5571 break; 5572 DeclContext *DC = nullptr; 5573 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5574 DC = LSI->CallOperator; 5575 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5576 DC = CRSI->TheCapturedDecl; 5577 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5578 DC = BSI->TheDecl; 5579 if (DC) { 5580 if (DC->containsDecl(TT->getDecl())) 5581 break; 5582 captureVariablyModifiedType( 5583 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5584 } 5585 } 5586 } 5587 } 5588 5589 return new (Context) 5590 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5591 } 5592 5593 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5594 ParmVarDecl *Param) { 5595 if (Param->hasUnparsedDefaultArg()) { 5596 // If we've already cleared out the location for the default argument, 5597 // that means we're parsing it right now. 5598 if (!UnparsedDefaultArgLocs.count(Param)) { 5599 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5600 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5601 Param->setInvalidDecl(); 5602 return true; 5603 } 5604 5605 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5606 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5607 Diag(UnparsedDefaultArgLocs[Param], 5608 diag::note_default_argument_declared_here); 5609 return true; 5610 } 5611 5612 if (Param->hasUninstantiatedDefaultArg() && 5613 InstantiateDefaultArgument(CallLoc, FD, Param)) 5614 return true; 5615 5616 assert(Param->hasInit() && "default argument but no initializer?"); 5617 5618 // If the default expression creates temporaries, we need to 5619 // push them to the current stack of expression temporaries so they'll 5620 // be properly destroyed. 5621 // FIXME: We should really be rebuilding the default argument with new 5622 // bound temporaries; see the comment in PR5810. 5623 // We don't need to do that with block decls, though, because 5624 // blocks in default argument expression can never capture anything. 5625 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5626 // Set the "needs cleanups" bit regardless of whether there are 5627 // any explicit objects. 5628 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5629 5630 // Append all the objects to the cleanup list. Right now, this 5631 // should always be a no-op, because blocks in default argument 5632 // expressions should never be able to capture anything. 5633 assert(!Init->getNumObjects() && 5634 "default argument expression has capturing blocks?"); 5635 } 5636 5637 // We already type-checked the argument, so we know it works. 5638 // Just mark all of the declarations in this potentially-evaluated expression 5639 // as being "referenced". 5640 EnterExpressionEvaluationContext EvalContext( 5641 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5642 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5643 /*SkipLocalVariables=*/true); 5644 return false; 5645 } 5646 5647 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5648 FunctionDecl *FD, ParmVarDecl *Param) { 5649 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5650 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5651 return ExprError(); 5652 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5653 } 5654 5655 Sema::VariadicCallType 5656 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5657 Expr *Fn) { 5658 if (Proto && Proto->isVariadic()) { 5659 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5660 return VariadicConstructor; 5661 else if (Fn && Fn->getType()->isBlockPointerType()) 5662 return VariadicBlock; 5663 else if (FDecl) { 5664 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5665 if (Method->isInstance()) 5666 return VariadicMethod; 5667 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5668 return VariadicMethod; 5669 return VariadicFunction; 5670 } 5671 return VariadicDoesNotApply; 5672 } 5673 5674 namespace { 5675 class FunctionCallCCC final : public FunctionCallFilterCCC { 5676 public: 5677 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5678 unsigned NumArgs, MemberExpr *ME) 5679 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5680 FunctionName(FuncName) {} 5681 5682 bool ValidateCandidate(const TypoCorrection &candidate) override { 5683 if (!candidate.getCorrectionSpecifier() || 5684 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5685 return false; 5686 } 5687 5688 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5689 } 5690 5691 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5692 return std::make_unique<FunctionCallCCC>(*this); 5693 } 5694 5695 private: 5696 const IdentifierInfo *const FunctionName; 5697 }; 5698 } 5699 5700 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5701 FunctionDecl *FDecl, 5702 ArrayRef<Expr *> Args) { 5703 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5704 DeclarationName FuncName = FDecl->getDeclName(); 5705 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5706 5707 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5708 if (TypoCorrection Corrected = S.CorrectTypo( 5709 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5710 S.getScopeForContext(S.CurContext), nullptr, CCC, 5711 Sema::CTK_ErrorRecovery)) { 5712 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5713 if (Corrected.isOverloaded()) { 5714 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5715 OverloadCandidateSet::iterator Best; 5716 for (NamedDecl *CD : Corrected) { 5717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5718 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5719 OCS); 5720 } 5721 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5722 case OR_Success: 5723 ND = Best->FoundDecl; 5724 Corrected.setCorrectionDecl(ND); 5725 break; 5726 default: 5727 break; 5728 } 5729 } 5730 ND = ND->getUnderlyingDecl(); 5731 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5732 return Corrected; 5733 } 5734 } 5735 return TypoCorrection(); 5736 } 5737 5738 /// ConvertArgumentsForCall - Converts the arguments specified in 5739 /// Args/NumArgs to the parameter types of the function FDecl with 5740 /// function prototype Proto. Call is the call expression itself, and 5741 /// Fn is the function expression. For a C++ member function, this 5742 /// routine does not attempt to convert the object argument. Returns 5743 /// true if the call is ill-formed. 5744 bool 5745 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5746 FunctionDecl *FDecl, 5747 const FunctionProtoType *Proto, 5748 ArrayRef<Expr *> Args, 5749 SourceLocation RParenLoc, 5750 bool IsExecConfig) { 5751 // Bail out early if calling a builtin with custom typechecking. 5752 if (FDecl) 5753 if (unsigned ID = FDecl->getBuiltinID()) 5754 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5755 return false; 5756 5757 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5758 // assignment, to the types of the corresponding parameter, ... 5759 unsigned NumParams = Proto->getNumParams(); 5760 bool Invalid = false; 5761 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5762 unsigned FnKind = Fn->getType()->isBlockPointerType() 5763 ? 1 /* block */ 5764 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5765 : 0 /* function */); 5766 5767 // If too few arguments are available (and we don't have default 5768 // arguments for the remaining parameters), don't make the call. 5769 if (Args.size() < NumParams) { 5770 if (Args.size() < MinArgs) { 5771 TypoCorrection TC; 5772 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5773 unsigned diag_id = 5774 MinArgs == NumParams && !Proto->isVariadic() 5775 ? diag::err_typecheck_call_too_few_args_suggest 5776 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5777 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5778 << static_cast<unsigned>(Args.size()) 5779 << TC.getCorrectionRange()); 5780 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5781 Diag(RParenLoc, 5782 MinArgs == NumParams && !Proto->isVariadic() 5783 ? diag::err_typecheck_call_too_few_args_one 5784 : diag::err_typecheck_call_too_few_args_at_least_one) 5785 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5786 else 5787 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5788 ? diag::err_typecheck_call_too_few_args 5789 : diag::err_typecheck_call_too_few_args_at_least) 5790 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5791 << Fn->getSourceRange(); 5792 5793 // Emit the location of the prototype. 5794 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5795 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5796 5797 return true; 5798 } 5799 // We reserve space for the default arguments when we create 5800 // the call expression, before calling ConvertArgumentsForCall. 5801 assert((Call->getNumArgs() == NumParams) && 5802 "We should have reserved space for the default arguments before!"); 5803 } 5804 5805 // If too many are passed and not variadic, error on the extras and drop 5806 // them. 5807 if (Args.size() > NumParams) { 5808 if (!Proto->isVariadic()) { 5809 TypoCorrection TC; 5810 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5811 unsigned diag_id = 5812 MinArgs == NumParams && !Proto->isVariadic() 5813 ? diag::err_typecheck_call_too_many_args_suggest 5814 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5815 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5816 << static_cast<unsigned>(Args.size()) 5817 << TC.getCorrectionRange()); 5818 } else if (NumParams == 1 && FDecl && 5819 FDecl->getParamDecl(0)->getDeclName()) 5820 Diag(Args[NumParams]->getBeginLoc(), 5821 MinArgs == NumParams 5822 ? diag::err_typecheck_call_too_many_args_one 5823 : diag::err_typecheck_call_too_many_args_at_most_one) 5824 << FnKind << FDecl->getParamDecl(0) 5825 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5826 << SourceRange(Args[NumParams]->getBeginLoc(), 5827 Args.back()->getEndLoc()); 5828 else 5829 Diag(Args[NumParams]->getBeginLoc(), 5830 MinArgs == NumParams 5831 ? diag::err_typecheck_call_too_many_args 5832 : diag::err_typecheck_call_too_many_args_at_most) 5833 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5834 << Fn->getSourceRange() 5835 << SourceRange(Args[NumParams]->getBeginLoc(), 5836 Args.back()->getEndLoc()); 5837 5838 // Emit the location of the prototype. 5839 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5840 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5841 5842 // This deletes the extra arguments. 5843 Call->shrinkNumArgs(NumParams); 5844 return true; 5845 } 5846 } 5847 SmallVector<Expr *, 8> AllArgs; 5848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5849 5850 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5851 AllArgs, CallType); 5852 if (Invalid) 5853 return true; 5854 unsigned TotalNumArgs = AllArgs.size(); 5855 for (unsigned i = 0; i < TotalNumArgs; ++i) 5856 Call->setArg(i, AllArgs[i]); 5857 5858 return false; 5859 } 5860 5861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5862 const FunctionProtoType *Proto, 5863 unsigned FirstParam, ArrayRef<Expr *> Args, 5864 SmallVectorImpl<Expr *> &AllArgs, 5865 VariadicCallType CallType, bool AllowExplicit, 5866 bool IsListInitialization) { 5867 unsigned NumParams = Proto->getNumParams(); 5868 bool Invalid = false; 5869 size_t ArgIx = 0; 5870 // Continue to check argument types (even if we have too few/many args). 5871 for (unsigned i = FirstParam; i < NumParams; i++) { 5872 QualType ProtoArgType = Proto->getParamType(i); 5873 5874 Expr *Arg; 5875 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5876 if (ArgIx < Args.size()) { 5877 Arg = Args[ArgIx++]; 5878 5879 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5880 diag::err_call_incomplete_argument, Arg)) 5881 return true; 5882 5883 // Strip the unbridged-cast placeholder expression off, if applicable. 5884 bool CFAudited = false; 5885 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5886 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5887 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5888 Arg = stripARCUnbridgedCast(Arg); 5889 else if (getLangOpts().ObjCAutoRefCount && 5890 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5891 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5892 CFAudited = true; 5893 5894 if (Proto->getExtParameterInfo(i).isNoEscape()) 5895 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5896 BE->getBlockDecl()->setDoesNotEscape(); 5897 5898 InitializedEntity Entity = 5899 Param ? InitializedEntity::InitializeParameter(Context, Param, 5900 ProtoArgType) 5901 : InitializedEntity::InitializeParameter( 5902 Context, ProtoArgType, Proto->isParamConsumed(i)); 5903 5904 // Remember that parameter belongs to a CF audited API. 5905 if (CFAudited) 5906 Entity.setParameterCFAudited(); 5907 5908 ExprResult ArgE = PerformCopyInitialization( 5909 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5910 if (ArgE.isInvalid()) 5911 return true; 5912 5913 Arg = ArgE.getAs<Expr>(); 5914 } else { 5915 assert(Param && "can't use default arguments without a known callee"); 5916 5917 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5918 if (ArgExpr.isInvalid()) 5919 return true; 5920 5921 Arg = ArgExpr.getAs<Expr>(); 5922 } 5923 5924 // Check for array bounds violations for each argument to the call. This 5925 // check only triggers warnings when the argument isn't a more complex Expr 5926 // with its own checking, such as a BinaryOperator. 5927 CheckArrayAccess(Arg); 5928 5929 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5930 CheckStaticArrayArgument(CallLoc, Param, Arg); 5931 5932 AllArgs.push_back(Arg); 5933 } 5934 5935 // If this is a variadic call, handle args passed through "...". 5936 if (CallType != VariadicDoesNotApply) { 5937 // Assume that extern "C" functions with variadic arguments that 5938 // return __unknown_anytype aren't *really* variadic. 5939 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5940 FDecl->isExternC()) { 5941 for (Expr *A : Args.slice(ArgIx)) { 5942 QualType paramType; // ignored 5943 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5944 Invalid |= arg.isInvalid(); 5945 AllArgs.push_back(arg.get()); 5946 } 5947 5948 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5949 } else { 5950 for (Expr *A : Args.slice(ArgIx)) { 5951 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5952 Invalid |= Arg.isInvalid(); 5953 AllArgs.push_back(Arg.get()); 5954 } 5955 } 5956 5957 // Check for array bounds violations. 5958 for (Expr *A : Args.slice(ArgIx)) 5959 CheckArrayAccess(A); 5960 } 5961 return Invalid; 5962 } 5963 5964 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5965 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5966 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5967 TL = DTL.getOriginalLoc(); 5968 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5969 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5970 << ATL.getLocalSourceRange(); 5971 } 5972 5973 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5974 /// array parameter, check that it is non-null, and that if it is formed by 5975 /// array-to-pointer decay, the underlying array is sufficiently large. 5976 /// 5977 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5978 /// array type derivation, then for each call to the function, the value of the 5979 /// corresponding actual argument shall provide access to the first element of 5980 /// an array with at least as many elements as specified by the size expression. 5981 void 5982 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5983 ParmVarDecl *Param, 5984 const Expr *ArgExpr) { 5985 // Static array parameters are not supported in C++. 5986 if (!Param || getLangOpts().CPlusPlus) 5987 return; 5988 5989 QualType OrigTy = Param->getOriginalType(); 5990 5991 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5992 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5993 return; 5994 5995 if (ArgExpr->isNullPointerConstant(Context, 5996 Expr::NPC_NeverValueDependent)) { 5997 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5998 DiagnoseCalleeStaticArrayParam(*this, Param); 5999 return; 6000 } 6001 6002 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6003 if (!CAT) 6004 return; 6005 6006 const ConstantArrayType *ArgCAT = 6007 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6008 if (!ArgCAT) 6009 return; 6010 6011 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6012 ArgCAT->getElementType())) { 6013 if (ArgCAT->getSize().ult(CAT->getSize())) { 6014 Diag(CallLoc, diag::warn_static_array_too_small) 6015 << ArgExpr->getSourceRange() 6016 << (unsigned)ArgCAT->getSize().getZExtValue() 6017 << (unsigned)CAT->getSize().getZExtValue() << 0; 6018 DiagnoseCalleeStaticArrayParam(*this, Param); 6019 } 6020 return; 6021 } 6022 6023 Optional<CharUnits> ArgSize = 6024 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6025 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6026 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6027 Diag(CallLoc, diag::warn_static_array_too_small) 6028 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6029 << (unsigned)ParmSize->getQuantity() << 1; 6030 DiagnoseCalleeStaticArrayParam(*this, Param); 6031 } 6032 } 6033 6034 /// Given a function expression of unknown-any type, try to rebuild it 6035 /// to have a function type. 6036 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6037 6038 /// Is the given type a placeholder that we need to lower out 6039 /// immediately during argument processing? 6040 static bool isPlaceholderToRemoveAsArg(QualType type) { 6041 // Placeholders are never sugared. 6042 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6043 if (!placeholder) return false; 6044 6045 switch (placeholder->getKind()) { 6046 // Ignore all the non-placeholder types. 6047 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6048 case BuiltinType::Id: 6049 #include "clang/Basic/OpenCLImageTypes.def" 6050 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6051 case BuiltinType::Id: 6052 #include "clang/Basic/OpenCLExtensionTypes.def" 6053 // In practice we'll never use this, since all SVE types are sugared 6054 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6055 #define SVE_TYPE(Name, Id, SingletonId) \ 6056 case BuiltinType::Id: 6057 #include "clang/Basic/AArch64SVEACLETypes.def" 6058 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ 6059 case BuiltinType::Id: 6060 #include "clang/Basic/PPCTypes.def" 6061 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6062 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6063 #include "clang/AST/BuiltinTypes.def" 6064 return false; 6065 6066 // We cannot lower out overload sets; they might validly be resolved 6067 // by the call machinery. 6068 case BuiltinType::Overload: 6069 return false; 6070 6071 // Unbridged casts in ARC can be handled in some call positions and 6072 // should be left in place. 6073 case BuiltinType::ARCUnbridgedCast: 6074 return false; 6075 6076 // Pseudo-objects should be converted as soon as possible. 6077 case BuiltinType::PseudoObject: 6078 return true; 6079 6080 // The debugger mode could theoretically but currently does not try 6081 // to resolve unknown-typed arguments based on known parameter types. 6082 case BuiltinType::UnknownAny: 6083 return true; 6084 6085 // These are always invalid as call arguments and should be reported. 6086 case BuiltinType::BoundMember: 6087 case BuiltinType::BuiltinFn: 6088 case BuiltinType::IncompleteMatrixIdx: 6089 case BuiltinType::OMPArraySection: 6090 case BuiltinType::OMPArrayShaping: 6091 case BuiltinType::OMPIterator: 6092 return true; 6093 6094 } 6095 llvm_unreachable("bad builtin type kind"); 6096 } 6097 6098 /// Check an argument list for placeholders that we won't try to 6099 /// handle later. 6100 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6101 // Apply this processing to all the arguments at once instead of 6102 // dying at the first failure. 6103 bool hasInvalid = false; 6104 for (size_t i = 0, e = args.size(); i != e; i++) { 6105 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6106 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6107 if (result.isInvalid()) hasInvalid = true; 6108 else args[i] = result.get(); 6109 } 6110 } 6111 return hasInvalid; 6112 } 6113 6114 /// If a builtin function has a pointer argument with no explicit address 6115 /// space, then it should be able to accept a pointer to any address 6116 /// space as input. In order to do this, we need to replace the 6117 /// standard builtin declaration with one that uses the same address space 6118 /// as the call. 6119 /// 6120 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6121 /// it does not contain any pointer arguments without 6122 /// an address space qualifer. Otherwise the rewritten 6123 /// FunctionDecl is returned. 6124 /// TODO: Handle pointer return types. 6125 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6126 FunctionDecl *FDecl, 6127 MultiExprArg ArgExprs) { 6128 6129 QualType DeclType = FDecl->getType(); 6130 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6131 6132 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6133 ArgExprs.size() < FT->getNumParams()) 6134 return nullptr; 6135 6136 bool NeedsNewDecl = false; 6137 unsigned i = 0; 6138 SmallVector<QualType, 8> OverloadParams; 6139 6140 for (QualType ParamType : FT->param_types()) { 6141 6142 // Convert array arguments to pointer to simplify type lookup. 6143 ExprResult ArgRes = 6144 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6145 if (ArgRes.isInvalid()) 6146 return nullptr; 6147 Expr *Arg = ArgRes.get(); 6148 QualType ArgType = Arg->getType(); 6149 if (!ParamType->isPointerType() || 6150 ParamType.hasAddressSpace() || 6151 !ArgType->isPointerType() || 6152 !ArgType->getPointeeType().hasAddressSpace()) { 6153 OverloadParams.push_back(ParamType); 6154 continue; 6155 } 6156 6157 QualType PointeeType = ParamType->getPointeeType(); 6158 if (PointeeType.hasAddressSpace()) 6159 continue; 6160 6161 NeedsNewDecl = true; 6162 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6163 6164 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6165 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6166 } 6167 6168 if (!NeedsNewDecl) 6169 return nullptr; 6170 6171 FunctionProtoType::ExtProtoInfo EPI; 6172 EPI.Variadic = FT->isVariadic(); 6173 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6174 OverloadParams, EPI); 6175 DeclContext *Parent = FDecl->getParent(); 6176 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6177 FDecl->getLocation(), 6178 FDecl->getLocation(), 6179 FDecl->getIdentifier(), 6180 OverloadTy, 6181 /*TInfo=*/nullptr, 6182 SC_Extern, false, 6183 /*hasPrototype=*/true); 6184 SmallVector<ParmVarDecl*, 16> Params; 6185 FT = cast<FunctionProtoType>(OverloadTy); 6186 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6187 QualType ParamType = FT->getParamType(i); 6188 ParmVarDecl *Parm = 6189 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6190 SourceLocation(), nullptr, ParamType, 6191 /*TInfo=*/nullptr, SC_None, nullptr); 6192 Parm->setScopeInfo(0, i); 6193 Params.push_back(Parm); 6194 } 6195 OverloadDecl->setParams(Params); 6196 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6197 return OverloadDecl; 6198 } 6199 6200 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6201 FunctionDecl *Callee, 6202 MultiExprArg ArgExprs) { 6203 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6204 // similar attributes) really don't like it when functions are called with an 6205 // invalid number of args. 6206 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6207 /*PartialOverloading=*/false) && 6208 !Callee->isVariadic()) 6209 return; 6210 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6211 return; 6212 6213 if (const EnableIfAttr *Attr = 6214 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6215 S.Diag(Fn->getBeginLoc(), 6216 isa<CXXMethodDecl>(Callee) 6217 ? diag::err_ovl_no_viable_member_function_in_call 6218 : diag::err_ovl_no_viable_function_in_call) 6219 << Callee << Callee->getSourceRange(); 6220 S.Diag(Callee->getLocation(), 6221 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6222 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6223 return; 6224 } 6225 } 6226 6227 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6228 const UnresolvedMemberExpr *const UME, Sema &S) { 6229 6230 const auto GetFunctionLevelDCIfCXXClass = 6231 [](Sema &S) -> const CXXRecordDecl * { 6232 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6233 if (!DC || !DC->getParent()) 6234 return nullptr; 6235 6236 // If the call to some member function was made from within a member 6237 // function body 'M' return return 'M's parent. 6238 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6239 return MD->getParent()->getCanonicalDecl(); 6240 // else the call was made from within a default member initializer of a 6241 // class, so return the class. 6242 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6243 return RD->getCanonicalDecl(); 6244 return nullptr; 6245 }; 6246 // If our DeclContext is neither a member function nor a class (in the 6247 // case of a lambda in a default member initializer), we can't have an 6248 // enclosing 'this'. 6249 6250 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6251 if (!CurParentClass) 6252 return false; 6253 6254 // The naming class for implicit member functions call is the class in which 6255 // name lookup starts. 6256 const CXXRecordDecl *const NamingClass = 6257 UME->getNamingClass()->getCanonicalDecl(); 6258 assert(NamingClass && "Must have naming class even for implicit access"); 6259 6260 // If the unresolved member functions were found in a 'naming class' that is 6261 // related (either the same or derived from) to the class that contains the 6262 // member function that itself contained the implicit member access. 6263 6264 return CurParentClass == NamingClass || 6265 CurParentClass->isDerivedFrom(NamingClass); 6266 } 6267 6268 static void 6269 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6270 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6271 6272 if (!UME) 6273 return; 6274 6275 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6276 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6277 // already been captured, or if this is an implicit member function call (if 6278 // it isn't, an attempt to capture 'this' should already have been made). 6279 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6280 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6281 return; 6282 6283 // Check if the naming class in which the unresolved members were found is 6284 // related (same as or is a base of) to the enclosing class. 6285 6286 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6287 return; 6288 6289 6290 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6291 // If the enclosing function is not dependent, then this lambda is 6292 // capture ready, so if we can capture this, do so. 6293 if (!EnclosingFunctionCtx->isDependentContext()) { 6294 // If the current lambda and all enclosing lambdas can capture 'this' - 6295 // then go ahead and capture 'this' (since our unresolved overload set 6296 // contains at least one non-static member function). 6297 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6298 S.CheckCXXThisCapture(CallLoc); 6299 } else if (S.CurContext->isDependentContext()) { 6300 // ... since this is an implicit member reference, that might potentially 6301 // involve a 'this' capture, mark 'this' for potential capture in 6302 // enclosing lambdas. 6303 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6304 CurLSI->addPotentialThisCapture(CallLoc); 6305 } 6306 } 6307 6308 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6309 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6310 Expr *ExecConfig) { 6311 ExprResult Call = 6312 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 6313 if (Call.isInvalid()) 6314 return Call; 6315 6316 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6317 // language modes. 6318 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6319 if (ULE->hasExplicitTemplateArgs() && 6320 ULE->decls_begin() == ULE->decls_end()) { 6321 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6322 ? diag::warn_cxx17_compat_adl_only_template_id 6323 : diag::ext_adl_only_template_id) 6324 << ULE->getName(); 6325 } 6326 } 6327 6328 if (LangOpts.OpenMP) 6329 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6330 ExecConfig); 6331 6332 return Call; 6333 } 6334 6335 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6336 /// This provides the location of the left/right parens and a list of comma 6337 /// locations. 6338 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6339 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6340 Expr *ExecConfig, bool IsExecConfig) { 6341 // Since this might be a postfix expression, get rid of ParenListExprs. 6342 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6343 if (Result.isInvalid()) return ExprError(); 6344 Fn = Result.get(); 6345 6346 if (checkArgsForPlaceholders(*this, ArgExprs)) 6347 return ExprError(); 6348 6349 if (getLangOpts().CPlusPlus) { 6350 // If this is a pseudo-destructor expression, build the call immediately. 6351 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6352 if (!ArgExprs.empty()) { 6353 // Pseudo-destructor calls should not have any arguments. 6354 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6355 << FixItHint::CreateRemoval( 6356 SourceRange(ArgExprs.front()->getBeginLoc(), 6357 ArgExprs.back()->getEndLoc())); 6358 } 6359 6360 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6361 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6362 } 6363 if (Fn->getType() == Context.PseudoObjectTy) { 6364 ExprResult result = CheckPlaceholderExpr(Fn); 6365 if (result.isInvalid()) return ExprError(); 6366 Fn = result.get(); 6367 } 6368 6369 // Determine whether this is a dependent call inside a C++ template, 6370 // in which case we won't do any semantic analysis now. 6371 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6372 if (ExecConfig) { 6373 return CUDAKernelCallExpr::Create( 6374 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6375 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6376 } else { 6377 6378 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6379 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6380 Fn->getBeginLoc()); 6381 6382 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6383 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6384 } 6385 } 6386 6387 // Determine whether this is a call to an object (C++ [over.call.object]). 6388 if (Fn->getType()->isRecordType()) 6389 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6390 RParenLoc); 6391 6392 if (Fn->getType() == Context.UnknownAnyTy) { 6393 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6394 if (result.isInvalid()) return ExprError(); 6395 Fn = result.get(); 6396 } 6397 6398 if (Fn->getType() == Context.BoundMemberTy) { 6399 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6400 RParenLoc); 6401 } 6402 } 6403 6404 // Check for overloaded calls. This can happen even in C due to extensions. 6405 if (Fn->getType() == Context.OverloadTy) { 6406 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6407 6408 // We aren't supposed to apply this logic if there's an '&' involved. 6409 if (!find.HasFormOfMemberPointer) { 6410 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6411 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6412 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6413 OverloadExpr *ovl = find.Expression; 6414 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6415 return BuildOverloadedCallExpr( 6416 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6417 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6418 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6419 RParenLoc); 6420 } 6421 } 6422 6423 // If we're directly calling a function, get the appropriate declaration. 6424 if (Fn->getType() == Context.UnknownAnyTy) { 6425 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6426 if (result.isInvalid()) return ExprError(); 6427 Fn = result.get(); 6428 } 6429 6430 Expr *NakedFn = Fn->IgnoreParens(); 6431 6432 bool CallingNDeclIndirectly = false; 6433 NamedDecl *NDecl = nullptr; 6434 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6435 if (UnOp->getOpcode() == UO_AddrOf) { 6436 CallingNDeclIndirectly = true; 6437 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6438 } 6439 } 6440 6441 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6442 NDecl = DRE->getDecl(); 6443 6444 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6445 if (FDecl && FDecl->getBuiltinID()) { 6446 // Rewrite the function decl for this builtin by replacing parameters 6447 // with no explicit address space with the address space of the arguments 6448 // in ArgExprs. 6449 if ((FDecl = 6450 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6451 NDecl = FDecl; 6452 Fn = DeclRefExpr::Create( 6453 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6454 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6455 nullptr, DRE->isNonOdrUse()); 6456 } 6457 } 6458 } else if (isa<MemberExpr>(NakedFn)) 6459 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6460 6461 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6462 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6463 FD, /*Complain=*/true, Fn->getBeginLoc())) 6464 return ExprError(); 6465 6466 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6467 return ExprError(); 6468 6469 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6470 } 6471 6472 if (Context.isDependenceAllowed() && 6473 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6474 assert(!getLangOpts().CPlusPlus); 6475 assert((Fn->containsErrors() || 6476 llvm::any_of(ArgExprs, 6477 [](clang::Expr *E) { return E->containsErrors(); })) && 6478 "should only occur in error-recovery path."); 6479 QualType ReturnType = 6480 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6481 ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType() 6482 : Context.DependentTy; 6483 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6484 Expr::getValueKindForType(ReturnType), RParenLoc, 6485 CurFPFeatureOverrides()); 6486 } 6487 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6488 ExecConfig, IsExecConfig); 6489 } 6490 6491 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6492 /// 6493 /// __builtin_astype( value, dst type ) 6494 /// 6495 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6496 SourceLocation BuiltinLoc, 6497 SourceLocation RParenLoc) { 6498 ExprValueKind VK = VK_RValue; 6499 ExprObjectKind OK = OK_Ordinary; 6500 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6501 QualType SrcTy = E->getType(); 6502 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6503 return ExprError(Diag(BuiltinLoc, 6504 diag::err_invalid_astype_of_different_size) 6505 << DstTy 6506 << SrcTy 6507 << E->getSourceRange()); 6508 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6509 } 6510 6511 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6512 /// provided arguments. 6513 /// 6514 /// __builtin_convertvector( value, dst type ) 6515 /// 6516 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6517 SourceLocation BuiltinLoc, 6518 SourceLocation RParenLoc) { 6519 TypeSourceInfo *TInfo; 6520 GetTypeFromParser(ParsedDestTy, &TInfo); 6521 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6522 } 6523 6524 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6525 /// i.e. an expression not of \p OverloadTy. The expression should 6526 /// unary-convert to an expression of function-pointer or 6527 /// block-pointer type. 6528 /// 6529 /// \param NDecl the declaration being called, if available 6530 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6531 SourceLocation LParenLoc, 6532 ArrayRef<Expr *> Args, 6533 SourceLocation RParenLoc, Expr *Config, 6534 bool IsExecConfig, ADLCallKind UsesADL) { 6535 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6536 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6537 6538 // Functions with 'interrupt' attribute cannot be called directly. 6539 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6540 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6541 return ExprError(); 6542 } 6543 6544 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6545 // so there's some risk when calling out to non-interrupt handler functions 6546 // that the callee might not preserve them. This is easy to diagnose here, 6547 // but can be very challenging to debug. 6548 if (auto *Caller = getCurFunctionDecl()) 6549 if (Caller->hasAttr<ARMInterruptAttr>()) { 6550 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6551 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6552 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6553 } 6554 6555 // Promote the function operand. 6556 // We special-case function promotion here because we only allow promoting 6557 // builtin functions to function pointers in the callee of a call. 6558 ExprResult Result; 6559 QualType ResultTy; 6560 if (BuiltinID && 6561 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6562 // Extract the return type from the (builtin) function pointer type. 6563 // FIXME Several builtins still have setType in 6564 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6565 // Builtins.def to ensure they are correct before removing setType calls. 6566 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6567 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6568 ResultTy = FDecl->getCallResultType(); 6569 } else { 6570 Result = CallExprUnaryConversions(Fn); 6571 ResultTy = Context.BoolTy; 6572 } 6573 if (Result.isInvalid()) 6574 return ExprError(); 6575 Fn = Result.get(); 6576 6577 // Check for a valid function type, but only if it is not a builtin which 6578 // requires custom type checking. These will be handled by 6579 // CheckBuiltinFunctionCall below just after creation of the call expression. 6580 const FunctionType *FuncT = nullptr; 6581 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6582 retry: 6583 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6584 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6585 // have type pointer to function". 6586 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6587 if (!FuncT) 6588 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6589 << Fn->getType() << Fn->getSourceRange()); 6590 } else if (const BlockPointerType *BPT = 6591 Fn->getType()->getAs<BlockPointerType>()) { 6592 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6593 } else { 6594 // Handle calls to expressions of unknown-any type. 6595 if (Fn->getType() == Context.UnknownAnyTy) { 6596 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6597 if (rewrite.isInvalid()) 6598 return ExprError(); 6599 Fn = rewrite.get(); 6600 goto retry; 6601 } 6602 6603 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6604 << Fn->getType() << Fn->getSourceRange()); 6605 } 6606 } 6607 6608 // Get the number of parameters in the function prototype, if any. 6609 // We will allocate space for max(Args.size(), NumParams) arguments 6610 // in the call expression. 6611 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6612 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6613 6614 CallExpr *TheCall; 6615 if (Config) { 6616 assert(UsesADL == ADLCallKind::NotADL && 6617 "CUDAKernelCallExpr should not use ADL"); 6618 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6619 Args, ResultTy, VK_RValue, RParenLoc, 6620 CurFPFeatureOverrides(), NumParams); 6621 } else { 6622 TheCall = 6623 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6624 CurFPFeatureOverrides(), NumParams, UsesADL); 6625 } 6626 6627 if (!Context.isDependenceAllowed()) { 6628 // Forget about the nulled arguments since typo correction 6629 // do not handle them well. 6630 TheCall->shrinkNumArgs(Args.size()); 6631 // C cannot always handle TypoExpr nodes in builtin calls and direct 6632 // function calls as their argument checking don't necessarily handle 6633 // dependent types properly, so make sure any TypoExprs have been 6634 // dealt with. 6635 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6636 if (!Result.isUsable()) return ExprError(); 6637 CallExpr *TheOldCall = TheCall; 6638 TheCall = dyn_cast<CallExpr>(Result.get()); 6639 bool CorrectedTypos = TheCall != TheOldCall; 6640 if (!TheCall) return Result; 6641 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6642 6643 // A new call expression node was created if some typos were corrected. 6644 // However it may not have been constructed with enough storage. In this 6645 // case, rebuild the node with enough storage. The waste of space is 6646 // immaterial since this only happens when some typos were corrected. 6647 if (CorrectedTypos && Args.size() < NumParams) { 6648 if (Config) 6649 TheCall = CUDAKernelCallExpr::Create( 6650 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6651 RParenLoc, CurFPFeatureOverrides(), NumParams); 6652 else 6653 TheCall = 6654 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6655 CurFPFeatureOverrides(), NumParams, UsesADL); 6656 } 6657 // We can now handle the nulled arguments for the default arguments. 6658 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6659 } 6660 6661 // Bail out early if calling a builtin with custom type checking. 6662 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6663 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6664 6665 if (getLangOpts().CUDA) { 6666 if (Config) { 6667 // CUDA: Kernel calls must be to global functions 6668 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6669 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6670 << FDecl << Fn->getSourceRange()); 6671 6672 // CUDA: Kernel function must have 'void' return type 6673 if (!FuncT->getReturnType()->isVoidType() && 6674 !FuncT->getReturnType()->getAs<AutoType>() && 6675 !FuncT->getReturnType()->isInstantiationDependentType()) 6676 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6677 << Fn->getType() << Fn->getSourceRange()); 6678 } else { 6679 // CUDA: Calls to global functions must be configured 6680 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6681 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6682 << FDecl << Fn->getSourceRange()); 6683 } 6684 } 6685 6686 // Check for a valid return type 6687 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6688 FDecl)) 6689 return ExprError(); 6690 6691 // We know the result type of the call, set it. 6692 TheCall->setType(FuncT->getCallResultType(Context)); 6693 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6694 6695 if (Proto) { 6696 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6697 IsExecConfig)) 6698 return ExprError(); 6699 } else { 6700 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6701 6702 if (FDecl) { 6703 // Check if we have too few/too many template arguments, based 6704 // on our knowledge of the function definition. 6705 const FunctionDecl *Def = nullptr; 6706 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6707 Proto = Def->getType()->getAs<FunctionProtoType>(); 6708 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6709 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6710 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6711 } 6712 6713 // If the function we're calling isn't a function prototype, but we have 6714 // a function prototype from a prior declaratiom, use that prototype. 6715 if (!FDecl->hasPrototype()) 6716 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6717 } 6718 6719 // Promote the arguments (C99 6.5.2.2p6). 6720 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6721 Expr *Arg = Args[i]; 6722 6723 if (Proto && i < Proto->getNumParams()) { 6724 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6725 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6726 ExprResult ArgE = 6727 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6728 if (ArgE.isInvalid()) 6729 return true; 6730 6731 Arg = ArgE.getAs<Expr>(); 6732 6733 } else { 6734 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6735 6736 if (ArgE.isInvalid()) 6737 return true; 6738 6739 Arg = ArgE.getAs<Expr>(); 6740 } 6741 6742 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6743 diag::err_call_incomplete_argument, Arg)) 6744 return ExprError(); 6745 6746 TheCall->setArg(i, Arg); 6747 } 6748 } 6749 6750 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6751 if (!Method->isStatic()) 6752 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6753 << Fn->getSourceRange()); 6754 6755 // Check for sentinels 6756 if (NDecl) 6757 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6758 6759 // Warn for unions passing across security boundary (CMSE). 6760 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6761 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6762 if (const auto *RT = 6763 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6764 if (RT->getDecl()->isOrContainsUnion()) 6765 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6766 << 0 << i; 6767 } 6768 } 6769 } 6770 6771 // Do special checking on direct calls to functions. 6772 if (FDecl) { 6773 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6774 return ExprError(); 6775 6776 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6777 6778 if (BuiltinID) 6779 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6780 } else if (NDecl) { 6781 if (CheckPointerCall(NDecl, TheCall, Proto)) 6782 return ExprError(); 6783 } else { 6784 if (CheckOtherCall(TheCall, Proto)) 6785 return ExprError(); 6786 } 6787 6788 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6789 } 6790 6791 ExprResult 6792 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6793 SourceLocation RParenLoc, Expr *InitExpr) { 6794 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6795 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6796 6797 TypeSourceInfo *TInfo; 6798 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6799 if (!TInfo) 6800 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6801 6802 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6803 } 6804 6805 ExprResult 6806 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6807 SourceLocation RParenLoc, Expr *LiteralExpr) { 6808 QualType literalType = TInfo->getType(); 6809 6810 if (literalType->isArrayType()) { 6811 if (RequireCompleteSizedType( 6812 LParenLoc, Context.getBaseElementType(literalType), 6813 diag::err_array_incomplete_or_sizeless_type, 6814 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6815 return ExprError(); 6816 if (literalType->isVariableArrayType()) 6817 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6818 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6819 } else if (!literalType->isDependentType() && 6820 RequireCompleteType(LParenLoc, literalType, 6821 diag::err_typecheck_decl_incomplete_type, 6822 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6823 return ExprError(); 6824 6825 InitializedEntity Entity 6826 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6827 InitializationKind Kind 6828 = InitializationKind::CreateCStyleCast(LParenLoc, 6829 SourceRange(LParenLoc, RParenLoc), 6830 /*InitList=*/true); 6831 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6832 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6833 &literalType); 6834 if (Result.isInvalid()) 6835 return ExprError(); 6836 LiteralExpr = Result.get(); 6837 6838 bool isFileScope = !CurContext->isFunctionOrMethod(); 6839 6840 // In C, compound literals are l-values for some reason. 6841 // For GCC compatibility, in C++, file-scope array compound literals with 6842 // constant initializers are also l-values, and compound literals are 6843 // otherwise prvalues. 6844 // 6845 // (GCC also treats C++ list-initialized file-scope array prvalues with 6846 // constant initializers as l-values, but that's non-conforming, so we don't 6847 // follow it there.) 6848 // 6849 // FIXME: It would be better to handle the lvalue cases as materializing and 6850 // lifetime-extending a temporary object, but our materialized temporaries 6851 // representation only supports lifetime extension from a variable, not "out 6852 // of thin air". 6853 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6854 // is bound to the result of applying array-to-pointer decay to the compound 6855 // literal. 6856 // FIXME: GCC supports compound literals of reference type, which should 6857 // obviously have a value kind derived from the kind of reference involved. 6858 ExprValueKind VK = 6859 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6860 ? VK_RValue 6861 : VK_LValue; 6862 6863 if (isFileScope) 6864 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6865 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6866 Expr *Init = ILE->getInit(i); 6867 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6868 } 6869 6870 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6871 VK, LiteralExpr, isFileScope); 6872 if (isFileScope) { 6873 if (!LiteralExpr->isTypeDependent() && 6874 !LiteralExpr->isValueDependent() && 6875 !literalType->isDependentType()) // C99 6.5.2.5p3 6876 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6877 return ExprError(); 6878 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6879 literalType.getAddressSpace() != LangAS::Default) { 6880 // Embedded-C extensions to C99 6.5.2.5: 6881 // "If the compound literal occurs inside the body of a function, the 6882 // type name shall not be qualified by an address-space qualifier." 6883 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6884 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6885 return ExprError(); 6886 } 6887 6888 if (!isFileScope && !getLangOpts().CPlusPlus) { 6889 // Compound literals that have automatic storage duration are destroyed at 6890 // the end of the scope in C; in C++, they're just temporaries. 6891 6892 // Emit diagnostics if it is or contains a C union type that is non-trivial 6893 // to destruct. 6894 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6895 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6896 NTCUC_CompoundLiteral, NTCUK_Destruct); 6897 6898 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6899 if (literalType.isDestructedType()) { 6900 Cleanup.setExprNeedsCleanups(true); 6901 ExprCleanupObjects.push_back(E); 6902 getCurFunction()->setHasBranchProtectedScope(); 6903 } 6904 } 6905 6906 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6907 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6908 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6909 E->getInitializer()->getExprLoc()); 6910 6911 return MaybeBindToTemporary(E); 6912 } 6913 6914 ExprResult 6915 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6916 SourceLocation RBraceLoc) { 6917 // Only produce each kind of designated initialization diagnostic once. 6918 SourceLocation FirstDesignator; 6919 bool DiagnosedArrayDesignator = false; 6920 bool DiagnosedNestedDesignator = false; 6921 bool DiagnosedMixedDesignator = false; 6922 6923 // Check that any designated initializers are syntactically valid in the 6924 // current language mode. 6925 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6926 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6927 if (FirstDesignator.isInvalid()) 6928 FirstDesignator = DIE->getBeginLoc(); 6929 6930 if (!getLangOpts().CPlusPlus) 6931 break; 6932 6933 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6934 DiagnosedNestedDesignator = true; 6935 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6936 << DIE->getDesignatorsSourceRange(); 6937 } 6938 6939 for (auto &Desig : DIE->designators()) { 6940 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6941 DiagnosedArrayDesignator = true; 6942 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6943 << Desig.getSourceRange(); 6944 } 6945 } 6946 6947 if (!DiagnosedMixedDesignator && 6948 !isa<DesignatedInitExpr>(InitArgList[0])) { 6949 DiagnosedMixedDesignator = true; 6950 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6951 << DIE->getSourceRange(); 6952 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6953 << InitArgList[0]->getSourceRange(); 6954 } 6955 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6956 isa<DesignatedInitExpr>(InitArgList[0])) { 6957 DiagnosedMixedDesignator = true; 6958 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6959 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6960 << DIE->getSourceRange(); 6961 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6962 << InitArgList[I]->getSourceRange(); 6963 } 6964 } 6965 6966 if (FirstDesignator.isValid()) { 6967 // Only diagnose designated initiaization as a C++20 extension if we didn't 6968 // already diagnose use of (non-C++20) C99 designator syntax. 6969 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6970 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6971 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6972 ? diag::warn_cxx17_compat_designated_init 6973 : diag::ext_cxx_designated_init); 6974 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6975 Diag(FirstDesignator, diag::ext_designated_init); 6976 } 6977 } 6978 6979 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6980 } 6981 6982 ExprResult 6983 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6984 SourceLocation RBraceLoc) { 6985 // Semantic analysis for initializers is done by ActOnDeclarator() and 6986 // CheckInitializer() - it requires knowledge of the object being initialized. 6987 6988 // Immediately handle non-overload placeholders. Overloads can be 6989 // resolved contextually, but everything else here can't. 6990 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6991 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6992 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6993 6994 // Ignore failures; dropping the entire initializer list because 6995 // of one failure would be terrible for indexing/etc. 6996 if (result.isInvalid()) continue; 6997 6998 InitArgList[I] = result.get(); 6999 } 7000 } 7001 7002 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7003 RBraceLoc); 7004 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7005 return E; 7006 } 7007 7008 /// Do an explicit extend of the given block pointer if we're in ARC. 7009 void Sema::maybeExtendBlockObject(ExprResult &E) { 7010 assert(E.get()->getType()->isBlockPointerType()); 7011 assert(E.get()->isRValue()); 7012 7013 // Only do this in an r-value context. 7014 if (!getLangOpts().ObjCAutoRefCount) return; 7015 7016 E = ImplicitCastExpr::Create( 7017 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7018 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7019 Cleanup.setExprNeedsCleanups(true); 7020 } 7021 7022 /// Prepare a conversion of the given expression to an ObjC object 7023 /// pointer type. 7024 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7025 QualType type = E.get()->getType(); 7026 if (type->isObjCObjectPointerType()) { 7027 return CK_BitCast; 7028 } else if (type->isBlockPointerType()) { 7029 maybeExtendBlockObject(E); 7030 return CK_BlockPointerToObjCPointerCast; 7031 } else { 7032 assert(type->isPointerType()); 7033 return CK_CPointerToObjCPointerCast; 7034 } 7035 } 7036 7037 /// Prepares for a scalar cast, performing all the necessary stages 7038 /// except the final cast and returning the kind required. 7039 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7040 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7041 // Also, callers should have filtered out the invalid cases with 7042 // pointers. Everything else should be possible. 7043 7044 QualType SrcTy = Src.get()->getType(); 7045 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7046 return CK_NoOp; 7047 7048 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7049 case Type::STK_MemberPointer: 7050 llvm_unreachable("member pointer type in C"); 7051 7052 case Type::STK_CPointer: 7053 case Type::STK_BlockPointer: 7054 case Type::STK_ObjCObjectPointer: 7055 switch (DestTy->getScalarTypeKind()) { 7056 case Type::STK_CPointer: { 7057 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7058 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7059 if (SrcAS != DestAS) 7060 return CK_AddressSpaceConversion; 7061 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7062 return CK_NoOp; 7063 return CK_BitCast; 7064 } 7065 case Type::STK_BlockPointer: 7066 return (SrcKind == Type::STK_BlockPointer 7067 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7068 case Type::STK_ObjCObjectPointer: 7069 if (SrcKind == Type::STK_ObjCObjectPointer) 7070 return CK_BitCast; 7071 if (SrcKind == Type::STK_CPointer) 7072 return CK_CPointerToObjCPointerCast; 7073 maybeExtendBlockObject(Src); 7074 return CK_BlockPointerToObjCPointerCast; 7075 case Type::STK_Bool: 7076 return CK_PointerToBoolean; 7077 case Type::STK_Integral: 7078 return CK_PointerToIntegral; 7079 case Type::STK_Floating: 7080 case Type::STK_FloatingComplex: 7081 case Type::STK_IntegralComplex: 7082 case Type::STK_MemberPointer: 7083 case Type::STK_FixedPoint: 7084 llvm_unreachable("illegal cast from pointer"); 7085 } 7086 llvm_unreachable("Should have returned before this"); 7087 7088 case Type::STK_FixedPoint: 7089 switch (DestTy->getScalarTypeKind()) { 7090 case Type::STK_FixedPoint: 7091 return CK_FixedPointCast; 7092 case Type::STK_Bool: 7093 return CK_FixedPointToBoolean; 7094 case Type::STK_Integral: 7095 return CK_FixedPointToIntegral; 7096 case Type::STK_Floating: 7097 return CK_FixedPointToFloating; 7098 case Type::STK_IntegralComplex: 7099 case Type::STK_FloatingComplex: 7100 Diag(Src.get()->getExprLoc(), 7101 diag::err_unimplemented_conversion_with_fixed_point_type) 7102 << DestTy; 7103 return CK_IntegralCast; 7104 case Type::STK_CPointer: 7105 case Type::STK_ObjCObjectPointer: 7106 case Type::STK_BlockPointer: 7107 case Type::STK_MemberPointer: 7108 llvm_unreachable("illegal cast to pointer type"); 7109 } 7110 llvm_unreachable("Should have returned before this"); 7111 7112 case Type::STK_Bool: // casting from bool is like casting from an integer 7113 case Type::STK_Integral: 7114 switch (DestTy->getScalarTypeKind()) { 7115 case Type::STK_CPointer: 7116 case Type::STK_ObjCObjectPointer: 7117 case Type::STK_BlockPointer: 7118 if (Src.get()->isNullPointerConstant(Context, 7119 Expr::NPC_ValueDependentIsNull)) 7120 return CK_NullToPointer; 7121 return CK_IntegralToPointer; 7122 case Type::STK_Bool: 7123 return CK_IntegralToBoolean; 7124 case Type::STK_Integral: 7125 return CK_IntegralCast; 7126 case Type::STK_Floating: 7127 return CK_IntegralToFloating; 7128 case Type::STK_IntegralComplex: 7129 Src = ImpCastExprToType(Src.get(), 7130 DestTy->castAs<ComplexType>()->getElementType(), 7131 CK_IntegralCast); 7132 return CK_IntegralRealToComplex; 7133 case Type::STK_FloatingComplex: 7134 Src = ImpCastExprToType(Src.get(), 7135 DestTy->castAs<ComplexType>()->getElementType(), 7136 CK_IntegralToFloating); 7137 return CK_FloatingRealToComplex; 7138 case Type::STK_MemberPointer: 7139 llvm_unreachable("member pointer type in C"); 7140 case Type::STK_FixedPoint: 7141 return CK_IntegralToFixedPoint; 7142 } 7143 llvm_unreachable("Should have returned before this"); 7144 7145 case Type::STK_Floating: 7146 switch (DestTy->getScalarTypeKind()) { 7147 case Type::STK_Floating: 7148 return CK_FloatingCast; 7149 case Type::STK_Bool: 7150 return CK_FloatingToBoolean; 7151 case Type::STK_Integral: 7152 return CK_FloatingToIntegral; 7153 case Type::STK_FloatingComplex: 7154 Src = ImpCastExprToType(Src.get(), 7155 DestTy->castAs<ComplexType>()->getElementType(), 7156 CK_FloatingCast); 7157 return CK_FloatingRealToComplex; 7158 case Type::STK_IntegralComplex: 7159 Src = ImpCastExprToType(Src.get(), 7160 DestTy->castAs<ComplexType>()->getElementType(), 7161 CK_FloatingToIntegral); 7162 return CK_IntegralRealToComplex; 7163 case Type::STK_CPointer: 7164 case Type::STK_ObjCObjectPointer: 7165 case Type::STK_BlockPointer: 7166 llvm_unreachable("valid float->pointer cast?"); 7167 case Type::STK_MemberPointer: 7168 llvm_unreachable("member pointer type in C"); 7169 case Type::STK_FixedPoint: 7170 return CK_FloatingToFixedPoint; 7171 } 7172 llvm_unreachable("Should have returned before this"); 7173 7174 case Type::STK_FloatingComplex: 7175 switch (DestTy->getScalarTypeKind()) { 7176 case Type::STK_FloatingComplex: 7177 return CK_FloatingComplexCast; 7178 case Type::STK_IntegralComplex: 7179 return CK_FloatingComplexToIntegralComplex; 7180 case Type::STK_Floating: { 7181 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7182 if (Context.hasSameType(ET, DestTy)) 7183 return CK_FloatingComplexToReal; 7184 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7185 return CK_FloatingCast; 7186 } 7187 case Type::STK_Bool: 7188 return CK_FloatingComplexToBoolean; 7189 case Type::STK_Integral: 7190 Src = ImpCastExprToType(Src.get(), 7191 SrcTy->castAs<ComplexType>()->getElementType(), 7192 CK_FloatingComplexToReal); 7193 return CK_FloatingToIntegral; 7194 case Type::STK_CPointer: 7195 case Type::STK_ObjCObjectPointer: 7196 case Type::STK_BlockPointer: 7197 llvm_unreachable("valid complex float->pointer cast?"); 7198 case Type::STK_MemberPointer: 7199 llvm_unreachable("member pointer type in C"); 7200 case Type::STK_FixedPoint: 7201 Diag(Src.get()->getExprLoc(), 7202 diag::err_unimplemented_conversion_with_fixed_point_type) 7203 << SrcTy; 7204 return CK_IntegralCast; 7205 } 7206 llvm_unreachable("Should have returned before this"); 7207 7208 case Type::STK_IntegralComplex: 7209 switch (DestTy->getScalarTypeKind()) { 7210 case Type::STK_FloatingComplex: 7211 return CK_IntegralComplexToFloatingComplex; 7212 case Type::STK_IntegralComplex: 7213 return CK_IntegralComplexCast; 7214 case Type::STK_Integral: { 7215 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7216 if (Context.hasSameType(ET, DestTy)) 7217 return CK_IntegralComplexToReal; 7218 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7219 return CK_IntegralCast; 7220 } 7221 case Type::STK_Bool: 7222 return CK_IntegralComplexToBoolean; 7223 case Type::STK_Floating: 7224 Src = ImpCastExprToType(Src.get(), 7225 SrcTy->castAs<ComplexType>()->getElementType(), 7226 CK_IntegralComplexToReal); 7227 return CK_IntegralToFloating; 7228 case Type::STK_CPointer: 7229 case Type::STK_ObjCObjectPointer: 7230 case Type::STK_BlockPointer: 7231 llvm_unreachable("valid complex int->pointer cast?"); 7232 case Type::STK_MemberPointer: 7233 llvm_unreachable("member pointer type in C"); 7234 case Type::STK_FixedPoint: 7235 Diag(Src.get()->getExprLoc(), 7236 diag::err_unimplemented_conversion_with_fixed_point_type) 7237 << SrcTy; 7238 return CK_IntegralCast; 7239 } 7240 llvm_unreachable("Should have returned before this"); 7241 } 7242 7243 llvm_unreachable("Unhandled scalar cast"); 7244 } 7245 7246 static bool breakDownVectorType(QualType type, uint64_t &len, 7247 QualType &eltType) { 7248 // Vectors are simple. 7249 if (const VectorType *vecType = type->getAs<VectorType>()) { 7250 len = vecType->getNumElements(); 7251 eltType = vecType->getElementType(); 7252 assert(eltType->isScalarType()); 7253 return true; 7254 } 7255 7256 // We allow lax conversion to and from non-vector types, but only if 7257 // they're real types (i.e. non-complex, non-pointer scalar types). 7258 if (!type->isRealType()) return false; 7259 7260 len = 1; 7261 eltType = type; 7262 return true; 7263 } 7264 7265 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7266 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7267 /// allowed? 7268 /// 7269 /// This will also return false if the two given types do not make sense from 7270 /// the perspective of SVE bitcasts. 7271 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7272 assert(srcTy->isVectorType() || destTy->isVectorType()); 7273 7274 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7275 if (!FirstType->isSizelessBuiltinType()) 7276 return false; 7277 7278 const auto *VecTy = SecondType->getAs<VectorType>(); 7279 return VecTy && 7280 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7281 }; 7282 7283 return ValidScalableConversion(srcTy, destTy) || 7284 ValidScalableConversion(destTy, srcTy); 7285 } 7286 7287 /// Are the two types lax-compatible vector types? That is, given 7288 /// that one of them is a vector, do they have equal storage sizes, 7289 /// where the storage size is the number of elements times the element 7290 /// size? 7291 /// 7292 /// This will also return false if either of the types is neither a 7293 /// vector nor a real type. 7294 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7295 assert(destTy->isVectorType() || srcTy->isVectorType()); 7296 7297 // Disallow lax conversions between scalars and ExtVectors (these 7298 // conversions are allowed for other vector types because common headers 7299 // depend on them). Most scalar OP ExtVector cases are handled by the 7300 // splat path anyway, which does what we want (convert, not bitcast). 7301 // What this rules out for ExtVectors is crazy things like char4*float. 7302 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7303 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7304 7305 uint64_t srcLen, destLen; 7306 QualType srcEltTy, destEltTy; 7307 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7308 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7309 7310 // ASTContext::getTypeSize will return the size rounded up to a 7311 // power of 2, so instead of using that, we need to use the raw 7312 // element size multiplied by the element count. 7313 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7314 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7315 7316 return (srcLen * srcEltSize == destLen * destEltSize); 7317 } 7318 7319 /// Is this a legal conversion between two types, one of which is 7320 /// known to be a vector type? 7321 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7322 assert(destTy->isVectorType() || srcTy->isVectorType()); 7323 7324 switch (Context.getLangOpts().getLaxVectorConversions()) { 7325 case LangOptions::LaxVectorConversionKind::None: 7326 return false; 7327 7328 case LangOptions::LaxVectorConversionKind::Integer: 7329 if (!srcTy->isIntegralOrEnumerationType()) { 7330 auto *Vec = srcTy->getAs<VectorType>(); 7331 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7332 return false; 7333 } 7334 if (!destTy->isIntegralOrEnumerationType()) { 7335 auto *Vec = destTy->getAs<VectorType>(); 7336 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7337 return false; 7338 } 7339 // OK, integer (vector) -> integer (vector) bitcast. 7340 break; 7341 7342 case LangOptions::LaxVectorConversionKind::All: 7343 break; 7344 } 7345 7346 return areLaxCompatibleVectorTypes(srcTy, destTy); 7347 } 7348 7349 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7350 CastKind &Kind) { 7351 assert(VectorTy->isVectorType() && "Not a vector type!"); 7352 7353 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7354 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7355 return Diag(R.getBegin(), 7356 Ty->isVectorType() ? 7357 diag::err_invalid_conversion_between_vectors : 7358 diag::err_invalid_conversion_between_vector_and_integer) 7359 << VectorTy << Ty << R; 7360 } else 7361 return Diag(R.getBegin(), 7362 diag::err_invalid_conversion_between_vector_and_scalar) 7363 << VectorTy << Ty << R; 7364 7365 Kind = CK_BitCast; 7366 return false; 7367 } 7368 7369 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7370 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7371 7372 if (DestElemTy == SplattedExpr->getType()) 7373 return SplattedExpr; 7374 7375 assert(DestElemTy->isFloatingType() || 7376 DestElemTy->isIntegralOrEnumerationType()); 7377 7378 CastKind CK; 7379 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7380 // OpenCL requires that we convert `true` boolean expressions to -1, but 7381 // only when splatting vectors. 7382 if (DestElemTy->isFloatingType()) { 7383 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7384 // in two steps: boolean to signed integral, then to floating. 7385 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7386 CK_BooleanToSignedIntegral); 7387 SplattedExpr = CastExprRes.get(); 7388 CK = CK_IntegralToFloating; 7389 } else { 7390 CK = CK_BooleanToSignedIntegral; 7391 } 7392 } else { 7393 ExprResult CastExprRes = SplattedExpr; 7394 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7395 if (CastExprRes.isInvalid()) 7396 return ExprError(); 7397 SplattedExpr = CastExprRes.get(); 7398 } 7399 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7400 } 7401 7402 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7403 Expr *CastExpr, CastKind &Kind) { 7404 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7405 7406 QualType SrcTy = CastExpr->getType(); 7407 7408 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7409 // an ExtVectorType. 7410 // In OpenCL, casts between vectors of different types are not allowed. 7411 // (See OpenCL 6.2). 7412 if (SrcTy->isVectorType()) { 7413 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7414 (getLangOpts().OpenCL && 7415 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7416 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7417 << DestTy << SrcTy << R; 7418 return ExprError(); 7419 } 7420 Kind = CK_BitCast; 7421 return CastExpr; 7422 } 7423 7424 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7425 // conversion will take place first from scalar to elt type, and then 7426 // splat from elt type to vector. 7427 if (SrcTy->isPointerType()) 7428 return Diag(R.getBegin(), 7429 diag::err_invalid_conversion_between_vector_and_scalar) 7430 << DestTy << SrcTy << R; 7431 7432 Kind = CK_VectorSplat; 7433 return prepareVectorSplat(DestTy, CastExpr); 7434 } 7435 7436 ExprResult 7437 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7438 Declarator &D, ParsedType &Ty, 7439 SourceLocation RParenLoc, Expr *CastExpr) { 7440 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7441 "ActOnCastExpr(): missing type or expr"); 7442 7443 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7444 if (D.isInvalidType()) 7445 return ExprError(); 7446 7447 if (getLangOpts().CPlusPlus) { 7448 // Check that there are no default arguments (C++ only). 7449 CheckExtraCXXDefaultArguments(D); 7450 } else { 7451 // Make sure any TypoExprs have been dealt with. 7452 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7453 if (!Res.isUsable()) 7454 return ExprError(); 7455 CastExpr = Res.get(); 7456 } 7457 7458 checkUnusedDeclAttributes(D); 7459 7460 QualType castType = castTInfo->getType(); 7461 Ty = CreateParsedType(castType, castTInfo); 7462 7463 bool isVectorLiteral = false; 7464 7465 // Check for an altivec or OpenCL literal, 7466 // i.e. all the elements are integer constants. 7467 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7468 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7469 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7470 && castType->isVectorType() && (PE || PLE)) { 7471 if (PLE && PLE->getNumExprs() == 0) { 7472 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7473 return ExprError(); 7474 } 7475 if (PE || PLE->getNumExprs() == 1) { 7476 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7477 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7478 isVectorLiteral = true; 7479 } 7480 else 7481 isVectorLiteral = true; 7482 } 7483 7484 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7485 // then handle it as such. 7486 if (isVectorLiteral) 7487 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7488 7489 // If the Expr being casted is a ParenListExpr, handle it specially. 7490 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7491 // sequence of BinOp comma operators. 7492 if (isa<ParenListExpr>(CastExpr)) { 7493 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7494 if (Result.isInvalid()) return ExprError(); 7495 CastExpr = Result.get(); 7496 } 7497 7498 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7499 !getSourceManager().isInSystemMacro(LParenLoc)) 7500 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7501 7502 CheckTollFreeBridgeCast(castType, CastExpr); 7503 7504 CheckObjCBridgeRelatedCast(castType, CastExpr); 7505 7506 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7507 7508 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7509 } 7510 7511 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7512 SourceLocation RParenLoc, Expr *E, 7513 TypeSourceInfo *TInfo) { 7514 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7515 "Expected paren or paren list expression"); 7516 7517 Expr **exprs; 7518 unsigned numExprs; 7519 Expr *subExpr; 7520 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7521 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7522 LiteralLParenLoc = PE->getLParenLoc(); 7523 LiteralRParenLoc = PE->getRParenLoc(); 7524 exprs = PE->getExprs(); 7525 numExprs = PE->getNumExprs(); 7526 } else { // isa<ParenExpr> by assertion at function entrance 7527 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7528 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7529 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7530 exprs = &subExpr; 7531 numExprs = 1; 7532 } 7533 7534 QualType Ty = TInfo->getType(); 7535 assert(Ty->isVectorType() && "Expected vector type"); 7536 7537 SmallVector<Expr *, 8> initExprs; 7538 const VectorType *VTy = Ty->castAs<VectorType>(); 7539 unsigned numElems = VTy->getNumElements(); 7540 7541 // '(...)' form of vector initialization in AltiVec: the number of 7542 // initializers must be one or must match the size of the vector. 7543 // If a single value is specified in the initializer then it will be 7544 // replicated to all the components of the vector 7545 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7546 // The number of initializers must be one or must match the size of the 7547 // vector. If a single value is specified in the initializer then it will 7548 // be replicated to all the components of the vector 7549 if (numExprs == 1) { 7550 QualType ElemTy = VTy->getElementType(); 7551 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7552 if (Literal.isInvalid()) 7553 return ExprError(); 7554 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7555 PrepareScalarCast(Literal, ElemTy)); 7556 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7557 } 7558 else if (numExprs < numElems) { 7559 Diag(E->getExprLoc(), 7560 diag::err_incorrect_number_of_vector_initializers); 7561 return ExprError(); 7562 } 7563 else 7564 initExprs.append(exprs, exprs + numExprs); 7565 } 7566 else { 7567 // For OpenCL, when the number of initializers is a single value, 7568 // it will be replicated to all components of the vector. 7569 if (getLangOpts().OpenCL && 7570 VTy->getVectorKind() == VectorType::GenericVector && 7571 numExprs == 1) { 7572 QualType ElemTy = VTy->getElementType(); 7573 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7574 if (Literal.isInvalid()) 7575 return ExprError(); 7576 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7577 PrepareScalarCast(Literal, ElemTy)); 7578 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7579 } 7580 7581 initExprs.append(exprs, exprs + numExprs); 7582 } 7583 // FIXME: This means that pretty-printing the final AST will produce curly 7584 // braces instead of the original commas. 7585 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7586 initExprs, LiteralRParenLoc); 7587 initE->setType(Ty); 7588 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7589 } 7590 7591 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7592 /// the ParenListExpr into a sequence of comma binary operators. 7593 ExprResult 7594 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7595 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7596 if (!E) 7597 return OrigExpr; 7598 7599 ExprResult Result(E->getExpr(0)); 7600 7601 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7602 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7603 E->getExpr(i)); 7604 7605 if (Result.isInvalid()) return ExprError(); 7606 7607 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7608 } 7609 7610 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7611 SourceLocation R, 7612 MultiExprArg Val) { 7613 return ParenListExpr::Create(Context, L, Val, R); 7614 } 7615 7616 /// Emit a specialized diagnostic when one expression is a null pointer 7617 /// constant and the other is not a pointer. Returns true if a diagnostic is 7618 /// emitted. 7619 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7620 SourceLocation QuestionLoc) { 7621 Expr *NullExpr = LHSExpr; 7622 Expr *NonPointerExpr = RHSExpr; 7623 Expr::NullPointerConstantKind NullKind = 7624 NullExpr->isNullPointerConstant(Context, 7625 Expr::NPC_ValueDependentIsNotNull); 7626 7627 if (NullKind == Expr::NPCK_NotNull) { 7628 NullExpr = RHSExpr; 7629 NonPointerExpr = LHSExpr; 7630 NullKind = 7631 NullExpr->isNullPointerConstant(Context, 7632 Expr::NPC_ValueDependentIsNotNull); 7633 } 7634 7635 if (NullKind == Expr::NPCK_NotNull) 7636 return false; 7637 7638 if (NullKind == Expr::NPCK_ZeroExpression) 7639 return false; 7640 7641 if (NullKind == Expr::NPCK_ZeroLiteral) { 7642 // In this case, check to make sure that we got here from a "NULL" 7643 // string in the source code. 7644 NullExpr = NullExpr->IgnoreParenImpCasts(); 7645 SourceLocation loc = NullExpr->getExprLoc(); 7646 if (!findMacroSpelling(loc, "NULL")) 7647 return false; 7648 } 7649 7650 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7651 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7652 << NonPointerExpr->getType() << DiagType 7653 << NonPointerExpr->getSourceRange(); 7654 return true; 7655 } 7656 7657 /// Return false if the condition expression is valid, true otherwise. 7658 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7659 QualType CondTy = Cond->getType(); 7660 7661 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7662 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7663 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7664 << CondTy << Cond->getSourceRange(); 7665 return true; 7666 } 7667 7668 // C99 6.5.15p2 7669 if (CondTy->isScalarType()) return false; 7670 7671 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7672 << CondTy << Cond->getSourceRange(); 7673 return true; 7674 } 7675 7676 /// Handle when one or both operands are void type. 7677 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7678 ExprResult &RHS) { 7679 Expr *LHSExpr = LHS.get(); 7680 Expr *RHSExpr = RHS.get(); 7681 7682 if (!LHSExpr->getType()->isVoidType()) 7683 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7684 << RHSExpr->getSourceRange(); 7685 if (!RHSExpr->getType()->isVoidType()) 7686 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7687 << LHSExpr->getSourceRange(); 7688 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7689 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7690 return S.Context.VoidTy; 7691 } 7692 7693 /// Return false if the NullExpr can be promoted to PointerTy, 7694 /// true otherwise. 7695 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7696 QualType PointerTy) { 7697 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7698 !NullExpr.get()->isNullPointerConstant(S.Context, 7699 Expr::NPC_ValueDependentIsNull)) 7700 return true; 7701 7702 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7703 return false; 7704 } 7705 7706 /// Checks compatibility between two pointers and return the resulting 7707 /// type. 7708 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7709 ExprResult &RHS, 7710 SourceLocation Loc) { 7711 QualType LHSTy = LHS.get()->getType(); 7712 QualType RHSTy = RHS.get()->getType(); 7713 7714 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7715 // Two identical pointers types are always compatible. 7716 return LHSTy; 7717 } 7718 7719 QualType lhptee, rhptee; 7720 7721 // Get the pointee types. 7722 bool IsBlockPointer = false; 7723 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7724 lhptee = LHSBTy->getPointeeType(); 7725 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7726 IsBlockPointer = true; 7727 } else { 7728 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7729 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7730 } 7731 7732 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7733 // differently qualified versions of compatible types, the result type is 7734 // a pointer to an appropriately qualified version of the composite 7735 // type. 7736 7737 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7738 // clause doesn't make sense for our extensions. E.g. address space 2 should 7739 // be incompatible with address space 3: they may live on different devices or 7740 // anything. 7741 Qualifiers lhQual = lhptee.getQualifiers(); 7742 Qualifiers rhQual = rhptee.getQualifiers(); 7743 7744 LangAS ResultAddrSpace = LangAS::Default; 7745 LangAS LAddrSpace = lhQual.getAddressSpace(); 7746 LangAS RAddrSpace = rhQual.getAddressSpace(); 7747 7748 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7749 // spaces is disallowed. 7750 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7751 ResultAddrSpace = LAddrSpace; 7752 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7753 ResultAddrSpace = RAddrSpace; 7754 else { 7755 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7756 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7757 << RHS.get()->getSourceRange(); 7758 return QualType(); 7759 } 7760 7761 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7762 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7763 lhQual.removeCVRQualifiers(); 7764 rhQual.removeCVRQualifiers(); 7765 7766 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7767 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7768 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7769 // qual types are compatible iff 7770 // * corresponded types are compatible 7771 // * CVR qualifiers are equal 7772 // * address spaces are equal 7773 // Thus for conditional operator we merge CVR and address space unqualified 7774 // pointees and if there is a composite type we return a pointer to it with 7775 // merged qualifiers. 7776 LHSCastKind = 7777 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7778 RHSCastKind = 7779 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7780 lhQual.removeAddressSpace(); 7781 rhQual.removeAddressSpace(); 7782 7783 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7784 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7785 7786 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7787 7788 if (CompositeTy.isNull()) { 7789 // In this situation, we assume void* type. No especially good 7790 // reason, but this is what gcc does, and we do have to pick 7791 // to get a consistent AST. 7792 QualType incompatTy; 7793 incompatTy = S.Context.getPointerType( 7794 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7795 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7796 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7797 7798 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7799 // for casts between types with incompatible address space qualifiers. 7800 // For the following code the compiler produces casts between global and 7801 // local address spaces of the corresponded innermost pointees: 7802 // local int *global *a; 7803 // global int *global *b; 7804 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7805 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7806 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7807 << RHS.get()->getSourceRange(); 7808 7809 return incompatTy; 7810 } 7811 7812 // The pointer types are compatible. 7813 // In case of OpenCL ResultTy should have the address space qualifier 7814 // which is a superset of address spaces of both the 2nd and the 3rd 7815 // operands of the conditional operator. 7816 QualType ResultTy = [&, ResultAddrSpace]() { 7817 if (S.getLangOpts().OpenCL) { 7818 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7819 CompositeQuals.setAddressSpace(ResultAddrSpace); 7820 return S.Context 7821 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7822 .withCVRQualifiers(MergedCVRQual); 7823 } 7824 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7825 }(); 7826 if (IsBlockPointer) 7827 ResultTy = S.Context.getBlockPointerType(ResultTy); 7828 else 7829 ResultTy = S.Context.getPointerType(ResultTy); 7830 7831 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7832 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7833 return ResultTy; 7834 } 7835 7836 /// Return the resulting type when the operands are both block pointers. 7837 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7838 ExprResult &LHS, 7839 ExprResult &RHS, 7840 SourceLocation Loc) { 7841 QualType LHSTy = LHS.get()->getType(); 7842 QualType RHSTy = RHS.get()->getType(); 7843 7844 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7845 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7846 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7847 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7848 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7849 return destType; 7850 } 7851 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7852 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7853 << RHS.get()->getSourceRange(); 7854 return QualType(); 7855 } 7856 7857 // We have 2 block pointer types. 7858 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7859 } 7860 7861 /// Return the resulting type when the operands are both pointers. 7862 static QualType 7863 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7864 ExprResult &RHS, 7865 SourceLocation Loc) { 7866 // get the pointer types 7867 QualType LHSTy = LHS.get()->getType(); 7868 QualType RHSTy = RHS.get()->getType(); 7869 7870 // get the "pointed to" types 7871 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7872 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7873 7874 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7875 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7876 // Figure out necessary qualifiers (C99 6.5.15p6) 7877 QualType destPointee 7878 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7879 QualType destType = S.Context.getPointerType(destPointee); 7880 // Add qualifiers if necessary. 7881 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7882 // Promote to void*. 7883 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7884 return destType; 7885 } 7886 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7887 QualType destPointee 7888 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7889 QualType destType = S.Context.getPointerType(destPointee); 7890 // Add qualifiers if necessary. 7891 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7892 // Promote to void*. 7893 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7894 return destType; 7895 } 7896 7897 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7898 } 7899 7900 /// Return false if the first expression is not an integer and the second 7901 /// expression is not a pointer, true otherwise. 7902 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7903 Expr* PointerExpr, SourceLocation Loc, 7904 bool IsIntFirstExpr) { 7905 if (!PointerExpr->getType()->isPointerType() || 7906 !Int.get()->getType()->isIntegerType()) 7907 return false; 7908 7909 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7910 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7911 7912 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7913 << Expr1->getType() << Expr2->getType() 7914 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7915 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7916 CK_IntegralToPointer); 7917 return true; 7918 } 7919 7920 /// Simple conversion between integer and floating point types. 7921 /// 7922 /// Used when handling the OpenCL conditional operator where the 7923 /// condition is a vector while the other operands are scalar. 7924 /// 7925 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7926 /// types are either integer or floating type. Between the two 7927 /// operands, the type with the higher rank is defined as the "result 7928 /// type". The other operand needs to be promoted to the same type. No 7929 /// other type promotion is allowed. We cannot use 7930 /// UsualArithmeticConversions() for this purpose, since it always 7931 /// promotes promotable types. 7932 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7933 ExprResult &RHS, 7934 SourceLocation QuestionLoc) { 7935 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7936 if (LHS.isInvalid()) 7937 return QualType(); 7938 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7939 if (RHS.isInvalid()) 7940 return QualType(); 7941 7942 // For conversion purposes, we ignore any qualifiers. 7943 // For example, "const float" and "float" are equivalent. 7944 QualType LHSType = 7945 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7946 QualType RHSType = 7947 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7948 7949 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7950 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7951 << LHSType << LHS.get()->getSourceRange(); 7952 return QualType(); 7953 } 7954 7955 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7956 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7957 << RHSType << RHS.get()->getSourceRange(); 7958 return QualType(); 7959 } 7960 7961 // If both types are identical, no conversion is needed. 7962 if (LHSType == RHSType) 7963 return LHSType; 7964 7965 // Now handle "real" floating types (i.e. float, double, long double). 7966 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7967 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7968 /*IsCompAssign = */ false); 7969 7970 // Finally, we have two differing integer types. 7971 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7972 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7973 } 7974 7975 /// Convert scalar operands to a vector that matches the 7976 /// condition in length. 7977 /// 7978 /// Used when handling the OpenCL conditional operator where the 7979 /// condition is a vector while the other operands are scalar. 7980 /// 7981 /// We first compute the "result type" for the scalar operands 7982 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7983 /// into a vector of that type where the length matches the condition 7984 /// vector type. s6.11.6 requires that the element types of the result 7985 /// and the condition must have the same number of bits. 7986 static QualType 7987 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7988 QualType CondTy, SourceLocation QuestionLoc) { 7989 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7990 if (ResTy.isNull()) return QualType(); 7991 7992 const VectorType *CV = CondTy->getAs<VectorType>(); 7993 assert(CV); 7994 7995 // Determine the vector result type 7996 unsigned NumElements = CV->getNumElements(); 7997 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7998 7999 // Ensure that all types have the same number of bits 8000 if (S.Context.getTypeSize(CV->getElementType()) 8001 != S.Context.getTypeSize(ResTy)) { 8002 // Since VectorTy is created internally, it does not pretty print 8003 // with an OpenCL name. Instead, we just print a description. 8004 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8005 SmallString<64> Str; 8006 llvm::raw_svector_ostream OS(Str); 8007 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8008 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8009 << CondTy << OS.str(); 8010 return QualType(); 8011 } 8012 8013 // Convert operands to the vector result type 8014 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8015 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8016 8017 return VectorTy; 8018 } 8019 8020 /// Return false if this is a valid OpenCL condition vector 8021 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8022 SourceLocation QuestionLoc) { 8023 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8024 // integral type. 8025 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8026 assert(CondTy); 8027 QualType EleTy = CondTy->getElementType(); 8028 if (EleTy->isIntegerType()) return false; 8029 8030 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8031 << Cond->getType() << Cond->getSourceRange(); 8032 return true; 8033 } 8034 8035 /// Return false if the vector condition type and the vector 8036 /// result type are compatible. 8037 /// 8038 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8039 /// number of elements, and their element types have the same number 8040 /// of bits. 8041 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8042 SourceLocation QuestionLoc) { 8043 const VectorType *CV = CondTy->getAs<VectorType>(); 8044 const VectorType *RV = VecResTy->getAs<VectorType>(); 8045 assert(CV && RV); 8046 8047 if (CV->getNumElements() != RV->getNumElements()) { 8048 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8049 << CondTy << VecResTy; 8050 return true; 8051 } 8052 8053 QualType CVE = CV->getElementType(); 8054 QualType RVE = RV->getElementType(); 8055 8056 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8057 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8058 << CondTy << VecResTy; 8059 return true; 8060 } 8061 8062 return false; 8063 } 8064 8065 /// Return the resulting type for the conditional operator in 8066 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8067 /// s6.3.i) when the condition is a vector type. 8068 static QualType 8069 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8070 ExprResult &LHS, ExprResult &RHS, 8071 SourceLocation QuestionLoc) { 8072 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8073 if (Cond.isInvalid()) 8074 return QualType(); 8075 QualType CondTy = Cond.get()->getType(); 8076 8077 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8078 return QualType(); 8079 8080 // If either operand is a vector then find the vector type of the 8081 // result as specified in OpenCL v1.1 s6.3.i. 8082 if (LHS.get()->getType()->isVectorType() || 8083 RHS.get()->getType()->isVectorType()) { 8084 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8085 /*isCompAssign*/false, 8086 /*AllowBothBool*/true, 8087 /*AllowBoolConversions*/false); 8088 if (VecResTy.isNull()) return QualType(); 8089 // The result type must match the condition type as specified in 8090 // OpenCL v1.1 s6.11.6. 8091 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8092 return QualType(); 8093 return VecResTy; 8094 } 8095 8096 // Both operands are scalar. 8097 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8098 } 8099 8100 /// Return true if the Expr is block type 8101 static bool checkBlockType(Sema &S, const Expr *E) { 8102 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8103 QualType Ty = CE->getCallee()->getType(); 8104 if (Ty->isBlockPointerType()) { 8105 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8106 return true; 8107 } 8108 } 8109 return false; 8110 } 8111 8112 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8113 /// In that case, LHS = cond. 8114 /// C99 6.5.15 8115 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8116 ExprResult &RHS, ExprValueKind &VK, 8117 ExprObjectKind &OK, 8118 SourceLocation QuestionLoc) { 8119 8120 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8121 if (!LHSResult.isUsable()) return QualType(); 8122 LHS = LHSResult; 8123 8124 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8125 if (!RHSResult.isUsable()) return QualType(); 8126 RHS = RHSResult; 8127 8128 // C++ is sufficiently different to merit its own checker. 8129 if (getLangOpts().CPlusPlus) 8130 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8131 8132 VK = VK_RValue; 8133 OK = OK_Ordinary; 8134 8135 if (Context.isDependenceAllowed() && 8136 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8137 RHS.get()->isTypeDependent())) { 8138 assert(!getLangOpts().CPlusPlus); 8139 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8140 RHS.get()->containsErrors()) && 8141 "should only occur in error-recovery path."); 8142 return Context.DependentTy; 8143 } 8144 8145 // The OpenCL operator with a vector condition is sufficiently 8146 // different to merit its own checker. 8147 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8148 Cond.get()->getType()->isExtVectorType()) 8149 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8150 8151 // First, check the condition. 8152 Cond = UsualUnaryConversions(Cond.get()); 8153 if (Cond.isInvalid()) 8154 return QualType(); 8155 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8156 return QualType(); 8157 8158 // Now check the two expressions. 8159 if (LHS.get()->getType()->isVectorType() || 8160 RHS.get()->getType()->isVectorType()) 8161 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8162 /*AllowBothBool*/true, 8163 /*AllowBoolConversions*/false); 8164 8165 QualType ResTy = 8166 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8167 if (LHS.isInvalid() || RHS.isInvalid()) 8168 return QualType(); 8169 8170 QualType LHSTy = LHS.get()->getType(); 8171 QualType RHSTy = RHS.get()->getType(); 8172 8173 // Diagnose attempts to convert between __float128 and long double where 8174 // such conversions currently can't be handled. 8175 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8176 Diag(QuestionLoc, 8177 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8178 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8179 return QualType(); 8180 } 8181 8182 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8183 // selection operator (?:). 8184 if (getLangOpts().OpenCL && 8185 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8186 return QualType(); 8187 } 8188 8189 // If both operands have arithmetic type, do the usual arithmetic conversions 8190 // to find a common type: C99 6.5.15p3,5. 8191 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8192 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8193 // different sizes, or between ExtInts and other types. 8194 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8195 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8196 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8197 << RHS.get()->getSourceRange(); 8198 return QualType(); 8199 } 8200 8201 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8202 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8203 8204 return ResTy; 8205 } 8206 8207 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8208 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8209 return LHSTy; 8210 } 8211 8212 // If both operands are the same structure or union type, the result is that 8213 // type. 8214 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8215 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8216 if (LHSRT->getDecl() == RHSRT->getDecl()) 8217 // "If both the operands have structure or union type, the result has 8218 // that type." This implies that CV qualifiers are dropped. 8219 return LHSTy.getUnqualifiedType(); 8220 // FIXME: Type of conditional expression must be complete in C mode. 8221 } 8222 8223 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8224 // The following || allows only one side to be void (a GCC-ism). 8225 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8226 return checkConditionalVoidType(*this, LHS, RHS); 8227 } 8228 8229 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8230 // the type of the other operand." 8231 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8232 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8233 8234 // All objective-c pointer type analysis is done here. 8235 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8236 QuestionLoc); 8237 if (LHS.isInvalid() || RHS.isInvalid()) 8238 return QualType(); 8239 if (!compositeType.isNull()) 8240 return compositeType; 8241 8242 8243 // Handle block pointer types. 8244 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8245 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8246 QuestionLoc); 8247 8248 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8249 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8250 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8251 QuestionLoc); 8252 8253 // GCC compatibility: soften pointer/integer mismatch. Note that 8254 // null pointers have been filtered out by this point. 8255 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8256 /*IsIntFirstExpr=*/true)) 8257 return RHSTy; 8258 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8259 /*IsIntFirstExpr=*/false)) 8260 return LHSTy; 8261 8262 // Allow ?: operations in which both operands have the same 8263 // built-in sizeless type. 8264 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8265 return LHSTy; 8266 8267 // Emit a better diagnostic if one of the expressions is a null pointer 8268 // constant and the other is not a pointer type. In this case, the user most 8269 // likely forgot to take the address of the other expression. 8270 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8271 return QualType(); 8272 8273 // Otherwise, the operands are not compatible. 8274 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8275 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8276 << RHS.get()->getSourceRange(); 8277 return QualType(); 8278 } 8279 8280 /// FindCompositeObjCPointerType - Helper method to find composite type of 8281 /// two objective-c pointer types of the two input expressions. 8282 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8283 SourceLocation QuestionLoc) { 8284 QualType LHSTy = LHS.get()->getType(); 8285 QualType RHSTy = RHS.get()->getType(); 8286 8287 // Handle things like Class and struct objc_class*. Here we case the result 8288 // to the pseudo-builtin, because that will be implicitly cast back to the 8289 // redefinition type if an attempt is made to access its fields. 8290 if (LHSTy->isObjCClassType() && 8291 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8292 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8293 return LHSTy; 8294 } 8295 if (RHSTy->isObjCClassType() && 8296 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8297 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8298 return RHSTy; 8299 } 8300 // And the same for struct objc_object* / id 8301 if (LHSTy->isObjCIdType() && 8302 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8303 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8304 return LHSTy; 8305 } 8306 if (RHSTy->isObjCIdType() && 8307 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8308 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8309 return RHSTy; 8310 } 8311 // And the same for struct objc_selector* / SEL 8312 if (Context.isObjCSelType(LHSTy) && 8313 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8314 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8315 return LHSTy; 8316 } 8317 if (Context.isObjCSelType(RHSTy) && 8318 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8319 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8320 return RHSTy; 8321 } 8322 // Check constraints for Objective-C object pointers types. 8323 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8324 8325 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8326 // Two identical object pointer types are always compatible. 8327 return LHSTy; 8328 } 8329 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8330 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8331 QualType compositeType = LHSTy; 8332 8333 // If both operands are interfaces and either operand can be 8334 // assigned to the other, use that type as the composite 8335 // type. This allows 8336 // xxx ? (A*) a : (B*) b 8337 // where B is a subclass of A. 8338 // 8339 // Additionally, as for assignment, if either type is 'id' 8340 // allow silent coercion. Finally, if the types are 8341 // incompatible then make sure to use 'id' as the composite 8342 // type so the result is acceptable for sending messages to. 8343 8344 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8345 // It could return the composite type. 8346 if (!(compositeType = 8347 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8348 // Nothing more to do. 8349 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8350 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8351 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8352 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8353 } else if ((LHSOPT->isObjCQualifiedIdType() || 8354 RHSOPT->isObjCQualifiedIdType()) && 8355 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8356 true)) { 8357 // Need to handle "id<xx>" explicitly. 8358 // GCC allows qualified id and any Objective-C type to devolve to 8359 // id. Currently localizing to here until clear this should be 8360 // part of ObjCQualifiedIdTypesAreCompatible. 8361 compositeType = Context.getObjCIdType(); 8362 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8363 compositeType = Context.getObjCIdType(); 8364 } else { 8365 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8366 << LHSTy << RHSTy 8367 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8368 QualType incompatTy = Context.getObjCIdType(); 8369 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8370 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8371 return incompatTy; 8372 } 8373 // The object pointer types are compatible. 8374 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8375 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8376 return compositeType; 8377 } 8378 // Check Objective-C object pointer types and 'void *' 8379 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8380 if (getLangOpts().ObjCAutoRefCount) { 8381 // ARC forbids the implicit conversion of object pointers to 'void *', 8382 // so these types are not compatible. 8383 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8384 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8385 LHS = RHS = true; 8386 return QualType(); 8387 } 8388 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8389 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8390 QualType destPointee 8391 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8392 QualType destType = Context.getPointerType(destPointee); 8393 // Add qualifiers if necessary. 8394 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8395 // Promote to void*. 8396 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8397 return destType; 8398 } 8399 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8400 if (getLangOpts().ObjCAutoRefCount) { 8401 // ARC forbids the implicit conversion of object pointers to 'void *', 8402 // so these types are not compatible. 8403 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8404 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8405 LHS = RHS = true; 8406 return QualType(); 8407 } 8408 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8409 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8410 QualType destPointee 8411 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8412 QualType destType = Context.getPointerType(destPointee); 8413 // Add qualifiers if necessary. 8414 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8415 // Promote to void*. 8416 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8417 return destType; 8418 } 8419 return QualType(); 8420 } 8421 8422 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8423 /// ParenRange in parentheses. 8424 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8425 const PartialDiagnostic &Note, 8426 SourceRange ParenRange) { 8427 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8428 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8429 EndLoc.isValid()) { 8430 Self.Diag(Loc, Note) 8431 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8432 << FixItHint::CreateInsertion(EndLoc, ")"); 8433 } else { 8434 // We can't display the parentheses, so just show the bare note. 8435 Self.Diag(Loc, Note) << ParenRange; 8436 } 8437 } 8438 8439 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8440 return BinaryOperator::isAdditiveOp(Opc) || 8441 BinaryOperator::isMultiplicativeOp(Opc) || 8442 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8443 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8444 // not any of the logical operators. Bitwise-xor is commonly used as a 8445 // logical-xor because there is no logical-xor operator. The logical 8446 // operators, including uses of xor, have a high false positive rate for 8447 // precedence warnings. 8448 } 8449 8450 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8451 /// expression, either using a built-in or overloaded operator, 8452 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8453 /// expression. 8454 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8455 Expr **RHSExprs) { 8456 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8457 E = E->IgnoreImpCasts(); 8458 E = E->IgnoreConversionOperatorSingleStep(); 8459 E = E->IgnoreImpCasts(); 8460 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8461 E = MTE->getSubExpr(); 8462 E = E->IgnoreImpCasts(); 8463 } 8464 8465 // Built-in binary operator. 8466 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8467 if (IsArithmeticOp(OP->getOpcode())) { 8468 *Opcode = OP->getOpcode(); 8469 *RHSExprs = OP->getRHS(); 8470 return true; 8471 } 8472 } 8473 8474 // Overloaded operator. 8475 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8476 if (Call->getNumArgs() != 2) 8477 return false; 8478 8479 // Make sure this is really a binary operator that is safe to pass into 8480 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8481 OverloadedOperatorKind OO = Call->getOperator(); 8482 if (OO < OO_Plus || OO > OO_Arrow || 8483 OO == OO_PlusPlus || OO == OO_MinusMinus) 8484 return false; 8485 8486 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8487 if (IsArithmeticOp(OpKind)) { 8488 *Opcode = OpKind; 8489 *RHSExprs = Call->getArg(1); 8490 return true; 8491 } 8492 } 8493 8494 return false; 8495 } 8496 8497 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8498 /// or is a logical expression such as (x==y) which has int type, but is 8499 /// commonly interpreted as boolean. 8500 static bool ExprLooksBoolean(Expr *E) { 8501 E = E->IgnoreParenImpCasts(); 8502 8503 if (E->getType()->isBooleanType()) 8504 return true; 8505 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8506 return OP->isComparisonOp() || OP->isLogicalOp(); 8507 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8508 return OP->getOpcode() == UO_LNot; 8509 if (E->getType()->isPointerType()) 8510 return true; 8511 // FIXME: What about overloaded operator calls returning "unspecified boolean 8512 // type"s (commonly pointer-to-members)? 8513 8514 return false; 8515 } 8516 8517 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8518 /// and binary operator are mixed in a way that suggests the programmer assumed 8519 /// the conditional operator has higher precedence, for example: 8520 /// "int x = a + someBinaryCondition ? 1 : 2". 8521 static void DiagnoseConditionalPrecedence(Sema &Self, 8522 SourceLocation OpLoc, 8523 Expr *Condition, 8524 Expr *LHSExpr, 8525 Expr *RHSExpr) { 8526 BinaryOperatorKind CondOpcode; 8527 Expr *CondRHS; 8528 8529 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8530 return; 8531 if (!ExprLooksBoolean(CondRHS)) 8532 return; 8533 8534 // The condition is an arithmetic binary expression, with a right- 8535 // hand side that looks boolean, so warn. 8536 8537 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8538 ? diag::warn_precedence_bitwise_conditional 8539 : diag::warn_precedence_conditional; 8540 8541 Self.Diag(OpLoc, DiagID) 8542 << Condition->getSourceRange() 8543 << BinaryOperator::getOpcodeStr(CondOpcode); 8544 8545 SuggestParentheses( 8546 Self, OpLoc, 8547 Self.PDiag(diag::note_precedence_silence) 8548 << BinaryOperator::getOpcodeStr(CondOpcode), 8549 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8550 8551 SuggestParentheses(Self, OpLoc, 8552 Self.PDiag(diag::note_precedence_conditional_first), 8553 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8554 } 8555 8556 /// Compute the nullability of a conditional expression. 8557 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8558 QualType LHSTy, QualType RHSTy, 8559 ASTContext &Ctx) { 8560 if (!ResTy->isAnyPointerType()) 8561 return ResTy; 8562 8563 auto GetNullability = [&Ctx](QualType Ty) { 8564 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8565 if (Kind) 8566 return *Kind; 8567 return NullabilityKind::Unspecified; 8568 }; 8569 8570 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8571 NullabilityKind MergedKind; 8572 8573 // Compute nullability of a binary conditional expression. 8574 if (IsBin) { 8575 if (LHSKind == NullabilityKind::NonNull) 8576 MergedKind = NullabilityKind::NonNull; 8577 else 8578 MergedKind = RHSKind; 8579 // Compute nullability of a normal conditional expression. 8580 } else { 8581 if (LHSKind == NullabilityKind::Nullable || 8582 RHSKind == NullabilityKind::Nullable) 8583 MergedKind = NullabilityKind::Nullable; 8584 else if (LHSKind == NullabilityKind::NonNull) 8585 MergedKind = RHSKind; 8586 else if (RHSKind == NullabilityKind::NonNull) 8587 MergedKind = LHSKind; 8588 else 8589 MergedKind = NullabilityKind::Unspecified; 8590 } 8591 8592 // Return if ResTy already has the correct nullability. 8593 if (GetNullability(ResTy) == MergedKind) 8594 return ResTy; 8595 8596 // Strip all nullability from ResTy. 8597 while (ResTy->getNullability(Ctx)) 8598 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8599 8600 // Create a new AttributedType with the new nullability kind. 8601 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8602 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8603 } 8604 8605 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8606 /// in the case of a the GNU conditional expr extension. 8607 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8608 SourceLocation ColonLoc, 8609 Expr *CondExpr, Expr *LHSExpr, 8610 Expr *RHSExpr) { 8611 if (!Context.isDependenceAllowed()) { 8612 // C cannot handle TypoExpr nodes in the condition because it 8613 // doesn't handle dependent types properly, so make sure any TypoExprs have 8614 // been dealt with before checking the operands. 8615 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8616 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8617 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8618 8619 if (!CondResult.isUsable()) 8620 return ExprError(); 8621 8622 if (LHSExpr) { 8623 if (!LHSResult.isUsable()) 8624 return ExprError(); 8625 } 8626 8627 if (!RHSResult.isUsable()) 8628 return ExprError(); 8629 8630 CondExpr = CondResult.get(); 8631 LHSExpr = LHSResult.get(); 8632 RHSExpr = RHSResult.get(); 8633 } 8634 8635 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8636 // was the condition. 8637 OpaqueValueExpr *opaqueValue = nullptr; 8638 Expr *commonExpr = nullptr; 8639 if (!LHSExpr) { 8640 commonExpr = CondExpr; 8641 // Lower out placeholder types first. This is important so that we don't 8642 // try to capture a placeholder. This happens in few cases in C++; such 8643 // as Objective-C++'s dictionary subscripting syntax. 8644 if (commonExpr->hasPlaceholderType()) { 8645 ExprResult result = CheckPlaceholderExpr(commonExpr); 8646 if (!result.isUsable()) return ExprError(); 8647 commonExpr = result.get(); 8648 } 8649 // We usually want to apply unary conversions *before* saving, except 8650 // in the special case of a C++ l-value conditional. 8651 if (!(getLangOpts().CPlusPlus 8652 && !commonExpr->isTypeDependent() 8653 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8654 && commonExpr->isGLValue() 8655 && commonExpr->isOrdinaryOrBitFieldObject() 8656 && RHSExpr->isOrdinaryOrBitFieldObject() 8657 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8658 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8659 if (commonRes.isInvalid()) 8660 return ExprError(); 8661 commonExpr = commonRes.get(); 8662 } 8663 8664 // If the common expression is a class or array prvalue, materialize it 8665 // so that we can safely refer to it multiple times. 8666 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8667 commonExpr->getType()->isArrayType())) { 8668 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8669 if (MatExpr.isInvalid()) 8670 return ExprError(); 8671 commonExpr = MatExpr.get(); 8672 } 8673 8674 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8675 commonExpr->getType(), 8676 commonExpr->getValueKind(), 8677 commonExpr->getObjectKind(), 8678 commonExpr); 8679 LHSExpr = CondExpr = opaqueValue; 8680 } 8681 8682 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8683 ExprValueKind VK = VK_RValue; 8684 ExprObjectKind OK = OK_Ordinary; 8685 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8686 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8687 VK, OK, QuestionLoc); 8688 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8689 RHS.isInvalid()) 8690 return ExprError(); 8691 8692 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8693 RHS.get()); 8694 8695 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8696 8697 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8698 Context); 8699 8700 if (!commonExpr) 8701 return new (Context) 8702 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8703 RHS.get(), result, VK, OK); 8704 8705 return new (Context) BinaryConditionalOperator( 8706 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8707 ColonLoc, result, VK, OK); 8708 } 8709 8710 // Check if we have a conversion between incompatible cmse function pointer 8711 // types, that is, a conversion between a function pointer with the 8712 // cmse_nonsecure_call attribute and one without. 8713 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8714 QualType ToType) { 8715 if (const auto *ToFn = 8716 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8717 if (const auto *FromFn = 8718 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8719 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8720 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8721 8722 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8723 } 8724 } 8725 return false; 8726 } 8727 8728 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8729 // being closely modeled after the C99 spec:-). The odd characteristic of this 8730 // routine is it effectively iqnores the qualifiers on the top level pointee. 8731 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8732 // FIXME: add a couple examples in this comment. 8733 static Sema::AssignConvertType 8734 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8735 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8736 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8737 8738 // get the "pointed to" type (ignoring qualifiers at the top level) 8739 const Type *lhptee, *rhptee; 8740 Qualifiers lhq, rhq; 8741 std::tie(lhptee, lhq) = 8742 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8743 std::tie(rhptee, rhq) = 8744 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8745 8746 Sema::AssignConvertType ConvTy = Sema::Compatible; 8747 8748 // C99 6.5.16.1p1: This following citation is common to constraints 8749 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8750 // qualifiers of the type *pointed to* by the right; 8751 8752 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8753 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8754 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8755 // Ignore lifetime for further calculation. 8756 lhq.removeObjCLifetime(); 8757 rhq.removeObjCLifetime(); 8758 } 8759 8760 if (!lhq.compatiblyIncludes(rhq)) { 8761 // Treat address-space mismatches as fatal. 8762 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8763 return Sema::IncompatiblePointerDiscardsQualifiers; 8764 8765 // It's okay to add or remove GC or lifetime qualifiers when converting to 8766 // and from void*. 8767 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8768 .compatiblyIncludes( 8769 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8770 && (lhptee->isVoidType() || rhptee->isVoidType())) 8771 ; // keep old 8772 8773 // Treat lifetime mismatches as fatal. 8774 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8775 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8776 8777 // For GCC/MS compatibility, other qualifier mismatches are treated 8778 // as still compatible in C. 8779 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8780 } 8781 8782 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8783 // incomplete type and the other is a pointer to a qualified or unqualified 8784 // version of void... 8785 if (lhptee->isVoidType()) { 8786 if (rhptee->isIncompleteOrObjectType()) 8787 return ConvTy; 8788 8789 // As an extension, we allow cast to/from void* to function pointer. 8790 assert(rhptee->isFunctionType()); 8791 return Sema::FunctionVoidPointer; 8792 } 8793 8794 if (rhptee->isVoidType()) { 8795 if (lhptee->isIncompleteOrObjectType()) 8796 return ConvTy; 8797 8798 // As an extension, we allow cast to/from void* to function pointer. 8799 assert(lhptee->isFunctionType()); 8800 return Sema::FunctionVoidPointer; 8801 } 8802 8803 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8804 // unqualified versions of compatible types, ... 8805 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8806 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8807 // Check if the pointee types are compatible ignoring the sign. 8808 // We explicitly check for char so that we catch "char" vs 8809 // "unsigned char" on systems where "char" is unsigned. 8810 if (lhptee->isCharType()) 8811 ltrans = S.Context.UnsignedCharTy; 8812 else if (lhptee->hasSignedIntegerRepresentation()) 8813 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8814 8815 if (rhptee->isCharType()) 8816 rtrans = S.Context.UnsignedCharTy; 8817 else if (rhptee->hasSignedIntegerRepresentation()) 8818 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8819 8820 if (ltrans == rtrans) { 8821 // Types are compatible ignoring the sign. Qualifier incompatibility 8822 // takes priority over sign incompatibility because the sign 8823 // warning can be disabled. 8824 if (ConvTy != Sema::Compatible) 8825 return ConvTy; 8826 8827 return Sema::IncompatiblePointerSign; 8828 } 8829 8830 // If we are a multi-level pointer, it's possible that our issue is simply 8831 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8832 // the eventual target type is the same and the pointers have the same 8833 // level of indirection, this must be the issue. 8834 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8835 do { 8836 std::tie(lhptee, lhq) = 8837 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8838 std::tie(rhptee, rhq) = 8839 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8840 8841 // Inconsistent address spaces at this point is invalid, even if the 8842 // address spaces would be compatible. 8843 // FIXME: This doesn't catch address space mismatches for pointers of 8844 // different nesting levels, like: 8845 // __local int *** a; 8846 // int ** b = a; 8847 // It's not clear how to actually determine when such pointers are 8848 // invalidly incompatible. 8849 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8850 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8851 8852 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8853 8854 if (lhptee == rhptee) 8855 return Sema::IncompatibleNestedPointerQualifiers; 8856 } 8857 8858 // General pointer incompatibility takes priority over qualifiers. 8859 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8860 return Sema::IncompatibleFunctionPointer; 8861 return Sema::IncompatiblePointer; 8862 } 8863 if (!S.getLangOpts().CPlusPlus && 8864 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8865 return Sema::IncompatibleFunctionPointer; 8866 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8867 return Sema::IncompatibleFunctionPointer; 8868 return ConvTy; 8869 } 8870 8871 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8872 /// block pointer types are compatible or whether a block and normal pointer 8873 /// are compatible. It is more restrict than comparing two function pointer 8874 // types. 8875 static Sema::AssignConvertType 8876 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8877 QualType RHSType) { 8878 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8879 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8880 8881 QualType lhptee, rhptee; 8882 8883 // get the "pointed to" type (ignoring qualifiers at the top level) 8884 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8885 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8886 8887 // In C++, the types have to match exactly. 8888 if (S.getLangOpts().CPlusPlus) 8889 return Sema::IncompatibleBlockPointer; 8890 8891 Sema::AssignConvertType ConvTy = Sema::Compatible; 8892 8893 // For blocks we enforce that qualifiers are identical. 8894 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8895 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8896 if (S.getLangOpts().OpenCL) { 8897 LQuals.removeAddressSpace(); 8898 RQuals.removeAddressSpace(); 8899 } 8900 if (LQuals != RQuals) 8901 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8902 8903 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8904 // assignment. 8905 // The current behavior is similar to C++ lambdas. A block might be 8906 // assigned to a variable iff its return type and parameters are compatible 8907 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8908 // an assignment. Presumably it should behave in way that a function pointer 8909 // assignment does in C, so for each parameter and return type: 8910 // * CVR and address space of LHS should be a superset of CVR and address 8911 // space of RHS. 8912 // * unqualified types should be compatible. 8913 if (S.getLangOpts().OpenCL) { 8914 if (!S.Context.typesAreBlockPointerCompatible( 8915 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8916 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8917 return Sema::IncompatibleBlockPointer; 8918 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8919 return Sema::IncompatibleBlockPointer; 8920 8921 return ConvTy; 8922 } 8923 8924 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8925 /// for assignment compatibility. 8926 static Sema::AssignConvertType 8927 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8928 QualType RHSType) { 8929 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8930 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8931 8932 if (LHSType->isObjCBuiltinType()) { 8933 // Class is not compatible with ObjC object pointers. 8934 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8935 !RHSType->isObjCQualifiedClassType()) 8936 return Sema::IncompatiblePointer; 8937 return Sema::Compatible; 8938 } 8939 if (RHSType->isObjCBuiltinType()) { 8940 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8941 !LHSType->isObjCQualifiedClassType()) 8942 return Sema::IncompatiblePointer; 8943 return Sema::Compatible; 8944 } 8945 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8946 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8947 8948 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8949 // make an exception for id<P> 8950 !LHSType->isObjCQualifiedIdType()) 8951 return Sema::CompatiblePointerDiscardsQualifiers; 8952 8953 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8954 return Sema::Compatible; 8955 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8956 return Sema::IncompatibleObjCQualifiedId; 8957 return Sema::IncompatiblePointer; 8958 } 8959 8960 Sema::AssignConvertType 8961 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8962 QualType LHSType, QualType RHSType) { 8963 // Fake up an opaque expression. We don't actually care about what 8964 // cast operations are required, so if CheckAssignmentConstraints 8965 // adds casts to this they'll be wasted, but fortunately that doesn't 8966 // usually happen on valid code. 8967 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8968 ExprResult RHSPtr = &RHSExpr; 8969 CastKind K; 8970 8971 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8972 } 8973 8974 /// This helper function returns true if QT is a vector type that has element 8975 /// type ElementType. 8976 static bool isVector(QualType QT, QualType ElementType) { 8977 if (const VectorType *VT = QT->getAs<VectorType>()) 8978 return VT->getElementType().getCanonicalType() == ElementType; 8979 return false; 8980 } 8981 8982 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8983 /// has code to accommodate several GCC extensions when type checking 8984 /// pointers. Here are some objectionable examples that GCC considers warnings: 8985 /// 8986 /// int a, *pint; 8987 /// short *pshort; 8988 /// struct foo *pfoo; 8989 /// 8990 /// pint = pshort; // warning: assignment from incompatible pointer type 8991 /// a = pint; // warning: assignment makes integer from pointer without a cast 8992 /// pint = a; // warning: assignment makes pointer from integer without a cast 8993 /// pint = pfoo; // warning: assignment from incompatible pointer type 8994 /// 8995 /// As a result, the code for dealing with pointers is more complex than the 8996 /// C99 spec dictates. 8997 /// 8998 /// Sets 'Kind' for any result kind except Incompatible. 8999 Sema::AssignConvertType 9000 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9001 CastKind &Kind, bool ConvertRHS) { 9002 QualType RHSType = RHS.get()->getType(); 9003 QualType OrigLHSType = LHSType; 9004 9005 // Get canonical types. We're not formatting these types, just comparing 9006 // them. 9007 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9008 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9009 9010 // Common case: no conversion required. 9011 if (LHSType == RHSType) { 9012 Kind = CK_NoOp; 9013 return Compatible; 9014 } 9015 9016 // If we have an atomic type, try a non-atomic assignment, then just add an 9017 // atomic qualification step. 9018 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9019 Sema::AssignConvertType result = 9020 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9021 if (result != Compatible) 9022 return result; 9023 if (Kind != CK_NoOp && ConvertRHS) 9024 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9025 Kind = CK_NonAtomicToAtomic; 9026 return Compatible; 9027 } 9028 9029 // If the left-hand side is a reference type, then we are in a 9030 // (rare!) case where we've allowed the use of references in C, 9031 // e.g., as a parameter type in a built-in function. In this case, 9032 // just make sure that the type referenced is compatible with the 9033 // right-hand side type. The caller is responsible for adjusting 9034 // LHSType so that the resulting expression does not have reference 9035 // type. 9036 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9037 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9038 Kind = CK_LValueBitCast; 9039 return Compatible; 9040 } 9041 return Incompatible; 9042 } 9043 9044 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9045 // to the same ExtVector type. 9046 if (LHSType->isExtVectorType()) { 9047 if (RHSType->isExtVectorType()) 9048 return Incompatible; 9049 if (RHSType->isArithmeticType()) { 9050 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9051 if (ConvertRHS) 9052 RHS = prepareVectorSplat(LHSType, RHS.get()); 9053 Kind = CK_VectorSplat; 9054 return Compatible; 9055 } 9056 } 9057 9058 // Conversions to or from vector type. 9059 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9060 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9061 // Allow assignments of an AltiVec vector type to an equivalent GCC 9062 // vector type and vice versa 9063 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9064 Kind = CK_BitCast; 9065 return Compatible; 9066 } 9067 9068 // If we are allowing lax vector conversions, and LHS and RHS are both 9069 // vectors, the total size only needs to be the same. This is a bitcast; 9070 // no bits are changed but the result type is different. 9071 if (isLaxVectorConversion(RHSType, LHSType)) { 9072 Kind = CK_BitCast; 9073 return IncompatibleVectors; 9074 } 9075 } 9076 9077 // When the RHS comes from another lax conversion (e.g. binops between 9078 // scalars and vectors) the result is canonicalized as a vector. When the 9079 // LHS is also a vector, the lax is allowed by the condition above. Handle 9080 // the case where LHS is a scalar. 9081 if (LHSType->isScalarType()) { 9082 const VectorType *VecType = RHSType->getAs<VectorType>(); 9083 if (VecType && VecType->getNumElements() == 1 && 9084 isLaxVectorConversion(RHSType, LHSType)) { 9085 ExprResult *VecExpr = &RHS; 9086 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9087 Kind = CK_BitCast; 9088 return Compatible; 9089 } 9090 } 9091 9092 // Allow assignments between fixed-length and sizeless SVE vectors. 9093 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9094 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9095 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9096 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9097 Kind = CK_BitCast; 9098 return Compatible; 9099 } 9100 9101 return Incompatible; 9102 } 9103 9104 // Diagnose attempts to convert between __float128 and long double where 9105 // such conversions currently can't be handled. 9106 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9107 return Incompatible; 9108 9109 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9110 // discards the imaginary part. 9111 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9112 !LHSType->getAs<ComplexType>()) 9113 return Incompatible; 9114 9115 // Arithmetic conversions. 9116 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9117 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9118 if (ConvertRHS) 9119 Kind = PrepareScalarCast(RHS, LHSType); 9120 return Compatible; 9121 } 9122 9123 // Conversions to normal pointers. 9124 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9125 // U* -> T* 9126 if (isa<PointerType>(RHSType)) { 9127 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9128 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9129 if (AddrSpaceL != AddrSpaceR) 9130 Kind = CK_AddressSpaceConversion; 9131 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9132 Kind = CK_NoOp; 9133 else 9134 Kind = CK_BitCast; 9135 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9136 } 9137 9138 // int -> T* 9139 if (RHSType->isIntegerType()) { 9140 Kind = CK_IntegralToPointer; // FIXME: null? 9141 return IntToPointer; 9142 } 9143 9144 // C pointers are not compatible with ObjC object pointers, 9145 // with two exceptions: 9146 if (isa<ObjCObjectPointerType>(RHSType)) { 9147 // - conversions to void* 9148 if (LHSPointer->getPointeeType()->isVoidType()) { 9149 Kind = CK_BitCast; 9150 return Compatible; 9151 } 9152 9153 // - conversions from 'Class' to the redefinition type 9154 if (RHSType->isObjCClassType() && 9155 Context.hasSameType(LHSType, 9156 Context.getObjCClassRedefinitionType())) { 9157 Kind = CK_BitCast; 9158 return Compatible; 9159 } 9160 9161 Kind = CK_BitCast; 9162 return IncompatiblePointer; 9163 } 9164 9165 // U^ -> void* 9166 if (RHSType->getAs<BlockPointerType>()) { 9167 if (LHSPointer->getPointeeType()->isVoidType()) { 9168 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9169 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9170 ->getPointeeType() 9171 .getAddressSpace(); 9172 Kind = 9173 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9174 return Compatible; 9175 } 9176 } 9177 9178 return Incompatible; 9179 } 9180 9181 // Conversions to block pointers. 9182 if (isa<BlockPointerType>(LHSType)) { 9183 // U^ -> T^ 9184 if (RHSType->isBlockPointerType()) { 9185 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9186 ->getPointeeType() 9187 .getAddressSpace(); 9188 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9189 ->getPointeeType() 9190 .getAddressSpace(); 9191 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9192 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9193 } 9194 9195 // int or null -> T^ 9196 if (RHSType->isIntegerType()) { 9197 Kind = CK_IntegralToPointer; // FIXME: null 9198 return IntToBlockPointer; 9199 } 9200 9201 // id -> T^ 9202 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9203 Kind = CK_AnyPointerToBlockPointerCast; 9204 return Compatible; 9205 } 9206 9207 // void* -> T^ 9208 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9209 if (RHSPT->getPointeeType()->isVoidType()) { 9210 Kind = CK_AnyPointerToBlockPointerCast; 9211 return Compatible; 9212 } 9213 9214 return Incompatible; 9215 } 9216 9217 // Conversions to Objective-C pointers. 9218 if (isa<ObjCObjectPointerType>(LHSType)) { 9219 // A* -> B* 9220 if (RHSType->isObjCObjectPointerType()) { 9221 Kind = CK_BitCast; 9222 Sema::AssignConvertType result = 9223 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9224 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9225 result == Compatible && 9226 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9227 result = IncompatibleObjCWeakRef; 9228 return result; 9229 } 9230 9231 // int or null -> A* 9232 if (RHSType->isIntegerType()) { 9233 Kind = CK_IntegralToPointer; // FIXME: null 9234 return IntToPointer; 9235 } 9236 9237 // In general, C pointers are not compatible with ObjC object pointers, 9238 // with two exceptions: 9239 if (isa<PointerType>(RHSType)) { 9240 Kind = CK_CPointerToObjCPointerCast; 9241 9242 // - conversions from 'void*' 9243 if (RHSType->isVoidPointerType()) { 9244 return Compatible; 9245 } 9246 9247 // - conversions to 'Class' from its redefinition type 9248 if (LHSType->isObjCClassType() && 9249 Context.hasSameType(RHSType, 9250 Context.getObjCClassRedefinitionType())) { 9251 return Compatible; 9252 } 9253 9254 return IncompatiblePointer; 9255 } 9256 9257 // Only under strict condition T^ is compatible with an Objective-C pointer. 9258 if (RHSType->isBlockPointerType() && 9259 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9260 if (ConvertRHS) 9261 maybeExtendBlockObject(RHS); 9262 Kind = CK_BlockPointerToObjCPointerCast; 9263 return Compatible; 9264 } 9265 9266 return Incompatible; 9267 } 9268 9269 // Conversions from pointers that are not covered by the above. 9270 if (isa<PointerType>(RHSType)) { 9271 // T* -> _Bool 9272 if (LHSType == Context.BoolTy) { 9273 Kind = CK_PointerToBoolean; 9274 return Compatible; 9275 } 9276 9277 // T* -> int 9278 if (LHSType->isIntegerType()) { 9279 Kind = CK_PointerToIntegral; 9280 return PointerToInt; 9281 } 9282 9283 return Incompatible; 9284 } 9285 9286 // Conversions from Objective-C pointers that are not covered by the above. 9287 if (isa<ObjCObjectPointerType>(RHSType)) { 9288 // T* -> _Bool 9289 if (LHSType == Context.BoolTy) { 9290 Kind = CK_PointerToBoolean; 9291 return Compatible; 9292 } 9293 9294 // T* -> int 9295 if (LHSType->isIntegerType()) { 9296 Kind = CK_PointerToIntegral; 9297 return PointerToInt; 9298 } 9299 9300 return Incompatible; 9301 } 9302 9303 // struct A -> struct B 9304 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9305 if (Context.typesAreCompatible(LHSType, RHSType)) { 9306 Kind = CK_NoOp; 9307 return Compatible; 9308 } 9309 } 9310 9311 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9312 Kind = CK_IntToOCLSampler; 9313 return Compatible; 9314 } 9315 9316 return Incompatible; 9317 } 9318 9319 /// Constructs a transparent union from an expression that is 9320 /// used to initialize the transparent union. 9321 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9322 ExprResult &EResult, QualType UnionType, 9323 FieldDecl *Field) { 9324 // Build an initializer list that designates the appropriate member 9325 // of the transparent union. 9326 Expr *E = EResult.get(); 9327 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9328 E, SourceLocation()); 9329 Initializer->setType(UnionType); 9330 Initializer->setInitializedFieldInUnion(Field); 9331 9332 // Build a compound literal constructing a value of the transparent 9333 // union type from this initializer list. 9334 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9335 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9336 VK_RValue, Initializer, false); 9337 } 9338 9339 Sema::AssignConvertType 9340 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9341 ExprResult &RHS) { 9342 QualType RHSType = RHS.get()->getType(); 9343 9344 // If the ArgType is a Union type, we want to handle a potential 9345 // transparent_union GCC extension. 9346 const RecordType *UT = ArgType->getAsUnionType(); 9347 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9348 return Incompatible; 9349 9350 // The field to initialize within the transparent union. 9351 RecordDecl *UD = UT->getDecl(); 9352 FieldDecl *InitField = nullptr; 9353 // It's compatible if the expression matches any of the fields. 9354 for (auto *it : UD->fields()) { 9355 if (it->getType()->isPointerType()) { 9356 // If the transparent union contains a pointer type, we allow: 9357 // 1) void pointer 9358 // 2) null pointer constant 9359 if (RHSType->isPointerType()) 9360 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9361 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9362 InitField = it; 9363 break; 9364 } 9365 9366 if (RHS.get()->isNullPointerConstant(Context, 9367 Expr::NPC_ValueDependentIsNull)) { 9368 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9369 CK_NullToPointer); 9370 InitField = it; 9371 break; 9372 } 9373 } 9374 9375 CastKind Kind; 9376 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9377 == Compatible) { 9378 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9379 InitField = it; 9380 break; 9381 } 9382 } 9383 9384 if (!InitField) 9385 return Incompatible; 9386 9387 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9388 return Compatible; 9389 } 9390 9391 Sema::AssignConvertType 9392 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9393 bool Diagnose, 9394 bool DiagnoseCFAudited, 9395 bool ConvertRHS) { 9396 // We need to be able to tell the caller whether we diagnosed a problem, if 9397 // they ask us to issue diagnostics. 9398 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9399 9400 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9401 // we can't avoid *all* modifications at the moment, so we need some somewhere 9402 // to put the updated value. 9403 ExprResult LocalRHS = CallerRHS; 9404 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9405 9406 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9407 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9408 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9409 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9410 Diag(RHS.get()->getExprLoc(), 9411 diag::warn_noderef_to_dereferenceable_pointer) 9412 << RHS.get()->getSourceRange(); 9413 } 9414 } 9415 } 9416 9417 if (getLangOpts().CPlusPlus) { 9418 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9419 // C++ 5.17p3: If the left operand is not of class type, the 9420 // expression is implicitly converted (C++ 4) to the 9421 // cv-unqualified type of the left operand. 9422 QualType RHSType = RHS.get()->getType(); 9423 if (Diagnose) { 9424 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9425 AA_Assigning); 9426 } else { 9427 ImplicitConversionSequence ICS = 9428 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9429 /*SuppressUserConversions=*/false, 9430 AllowedExplicit::None, 9431 /*InOverloadResolution=*/false, 9432 /*CStyle=*/false, 9433 /*AllowObjCWritebackConversion=*/false); 9434 if (ICS.isFailure()) 9435 return Incompatible; 9436 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9437 ICS, AA_Assigning); 9438 } 9439 if (RHS.isInvalid()) 9440 return Incompatible; 9441 Sema::AssignConvertType result = Compatible; 9442 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9443 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9444 result = IncompatibleObjCWeakRef; 9445 return result; 9446 } 9447 9448 // FIXME: Currently, we fall through and treat C++ classes like C 9449 // structures. 9450 // FIXME: We also fall through for atomics; not sure what should 9451 // happen there, though. 9452 } else if (RHS.get()->getType() == Context.OverloadTy) { 9453 // As a set of extensions to C, we support overloading on functions. These 9454 // functions need to be resolved here. 9455 DeclAccessPair DAP; 9456 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9457 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9458 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9459 else 9460 return Incompatible; 9461 } 9462 9463 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9464 // a null pointer constant. 9465 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9466 LHSType->isBlockPointerType()) && 9467 RHS.get()->isNullPointerConstant(Context, 9468 Expr::NPC_ValueDependentIsNull)) { 9469 if (Diagnose || ConvertRHS) { 9470 CastKind Kind; 9471 CXXCastPath Path; 9472 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9473 /*IgnoreBaseAccess=*/false, Diagnose); 9474 if (ConvertRHS) 9475 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9476 } 9477 return Compatible; 9478 } 9479 9480 // OpenCL queue_t type assignment. 9481 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9482 Context, Expr::NPC_ValueDependentIsNull)) { 9483 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9484 return Compatible; 9485 } 9486 9487 // This check seems unnatural, however it is necessary to ensure the proper 9488 // conversion of functions/arrays. If the conversion were done for all 9489 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9490 // expressions that suppress this implicit conversion (&, sizeof). 9491 // 9492 // Suppress this for references: C++ 8.5.3p5. 9493 if (!LHSType->isReferenceType()) { 9494 // FIXME: We potentially allocate here even if ConvertRHS is false. 9495 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9496 if (RHS.isInvalid()) 9497 return Incompatible; 9498 } 9499 CastKind Kind; 9500 Sema::AssignConvertType result = 9501 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9502 9503 // C99 6.5.16.1p2: The value of the right operand is converted to the 9504 // type of the assignment expression. 9505 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9506 // so that we can use references in built-in functions even in C. 9507 // The getNonReferenceType() call makes sure that the resulting expression 9508 // does not have reference type. 9509 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9510 QualType Ty = LHSType.getNonLValueExprType(Context); 9511 Expr *E = RHS.get(); 9512 9513 // Check for various Objective-C errors. If we are not reporting 9514 // diagnostics and just checking for errors, e.g., during overload 9515 // resolution, return Incompatible to indicate the failure. 9516 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9517 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9518 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9519 if (!Diagnose) 9520 return Incompatible; 9521 } 9522 if (getLangOpts().ObjC && 9523 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9524 E->getType(), E, Diagnose) || 9525 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9526 if (!Diagnose) 9527 return Incompatible; 9528 // Replace the expression with a corrected version and continue so we 9529 // can find further errors. 9530 RHS = E; 9531 return Compatible; 9532 } 9533 9534 if (ConvertRHS) 9535 RHS = ImpCastExprToType(E, Ty, Kind); 9536 } 9537 9538 return result; 9539 } 9540 9541 namespace { 9542 /// The original operand to an operator, prior to the application of the usual 9543 /// arithmetic conversions and converting the arguments of a builtin operator 9544 /// candidate. 9545 struct OriginalOperand { 9546 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9547 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9548 Op = MTE->getSubExpr(); 9549 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9550 Op = BTE->getSubExpr(); 9551 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9552 Orig = ICE->getSubExprAsWritten(); 9553 Conversion = ICE->getConversionFunction(); 9554 } 9555 } 9556 9557 QualType getType() const { return Orig->getType(); } 9558 9559 Expr *Orig; 9560 NamedDecl *Conversion; 9561 }; 9562 } 9563 9564 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9565 ExprResult &RHS) { 9566 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9567 9568 Diag(Loc, diag::err_typecheck_invalid_operands) 9569 << OrigLHS.getType() << OrigRHS.getType() 9570 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9571 9572 // If a user-defined conversion was applied to either of the operands prior 9573 // to applying the built-in operator rules, tell the user about it. 9574 if (OrigLHS.Conversion) { 9575 Diag(OrigLHS.Conversion->getLocation(), 9576 diag::note_typecheck_invalid_operands_converted) 9577 << 0 << LHS.get()->getType(); 9578 } 9579 if (OrigRHS.Conversion) { 9580 Diag(OrigRHS.Conversion->getLocation(), 9581 diag::note_typecheck_invalid_operands_converted) 9582 << 1 << RHS.get()->getType(); 9583 } 9584 9585 return QualType(); 9586 } 9587 9588 // Diagnose cases where a scalar was implicitly converted to a vector and 9589 // diagnose the underlying types. Otherwise, diagnose the error 9590 // as invalid vector logical operands for non-C++ cases. 9591 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9592 ExprResult &RHS) { 9593 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9594 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9595 9596 bool LHSNatVec = LHSType->isVectorType(); 9597 bool RHSNatVec = RHSType->isVectorType(); 9598 9599 if (!(LHSNatVec && RHSNatVec)) { 9600 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9601 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9602 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9603 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9604 << Vector->getSourceRange(); 9605 return QualType(); 9606 } 9607 9608 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9609 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9610 << RHS.get()->getSourceRange(); 9611 9612 return QualType(); 9613 } 9614 9615 /// Try to convert a value of non-vector type to a vector type by converting 9616 /// the type to the element type of the vector and then performing a splat. 9617 /// If the language is OpenCL, we only use conversions that promote scalar 9618 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9619 /// for float->int. 9620 /// 9621 /// OpenCL V2.0 6.2.6.p2: 9622 /// An error shall occur if any scalar operand type has greater rank 9623 /// than the type of the vector element. 9624 /// 9625 /// \param scalar - if non-null, actually perform the conversions 9626 /// \return true if the operation fails (but without diagnosing the failure) 9627 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9628 QualType scalarTy, 9629 QualType vectorEltTy, 9630 QualType vectorTy, 9631 unsigned &DiagID) { 9632 // The conversion to apply to the scalar before splatting it, 9633 // if necessary. 9634 CastKind scalarCast = CK_NoOp; 9635 9636 if (vectorEltTy->isIntegralType(S.Context)) { 9637 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9638 (scalarTy->isIntegerType() && 9639 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9640 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9641 return true; 9642 } 9643 if (!scalarTy->isIntegralType(S.Context)) 9644 return true; 9645 scalarCast = CK_IntegralCast; 9646 } else if (vectorEltTy->isRealFloatingType()) { 9647 if (scalarTy->isRealFloatingType()) { 9648 if (S.getLangOpts().OpenCL && 9649 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9650 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9651 return true; 9652 } 9653 scalarCast = CK_FloatingCast; 9654 } 9655 else if (scalarTy->isIntegralType(S.Context)) 9656 scalarCast = CK_IntegralToFloating; 9657 else 9658 return true; 9659 } else { 9660 return true; 9661 } 9662 9663 // Adjust scalar if desired. 9664 if (scalar) { 9665 if (scalarCast != CK_NoOp) 9666 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9667 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9668 } 9669 return false; 9670 } 9671 9672 /// Convert vector E to a vector with the same number of elements but different 9673 /// element type. 9674 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9675 const auto *VecTy = E->getType()->getAs<VectorType>(); 9676 assert(VecTy && "Expression E must be a vector"); 9677 QualType NewVecTy = S.Context.getVectorType(ElementType, 9678 VecTy->getNumElements(), 9679 VecTy->getVectorKind()); 9680 9681 // Look through the implicit cast. Return the subexpression if its type is 9682 // NewVecTy. 9683 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9684 if (ICE->getSubExpr()->getType() == NewVecTy) 9685 return ICE->getSubExpr(); 9686 9687 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9688 return S.ImpCastExprToType(E, NewVecTy, Cast); 9689 } 9690 9691 /// Test if a (constant) integer Int can be casted to another integer type 9692 /// IntTy without losing precision. 9693 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9694 QualType OtherIntTy) { 9695 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9696 9697 // Reject cases where the value of the Int is unknown as that would 9698 // possibly cause truncation, but accept cases where the scalar can be 9699 // demoted without loss of precision. 9700 Expr::EvalResult EVResult; 9701 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9702 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9703 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9704 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9705 9706 if (CstInt) { 9707 // If the scalar is constant and is of a higher order and has more active 9708 // bits that the vector element type, reject it. 9709 llvm::APSInt Result = EVResult.Val.getInt(); 9710 unsigned NumBits = IntSigned 9711 ? (Result.isNegative() ? Result.getMinSignedBits() 9712 : Result.getActiveBits()) 9713 : Result.getActiveBits(); 9714 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9715 return true; 9716 9717 // If the signedness of the scalar type and the vector element type 9718 // differs and the number of bits is greater than that of the vector 9719 // element reject it. 9720 return (IntSigned != OtherIntSigned && 9721 NumBits > S.Context.getIntWidth(OtherIntTy)); 9722 } 9723 9724 // Reject cases where the value of the scalar is not constant and it's 9725 // order is greater than that of the vector element type. 9726 return (Order < 0); 9727 } 9728 9729 /// Test if a (constant) integer Int can be casted to floating point type 9730 /// FloatTy without losing precision. 9731 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9732 QualType FloatTy) { 9733 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9734 9735 // Determine if the integer constant can be expressed as a floating point 9736 // number of the appropriate type. 9737 Expr::EvalResult EVResult; 9738 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9739 9740 uint64_t Bits = 0; 9741 if (CstInt) { 9742 // Reject constants that would be truncated if they were converted to 9743 // the floating point type. Test by simple to/from conversion. 9744 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9745 // could be avoided if there was a convertFromAPInt method 9746 // which could signal back if implicit truncation occurred. 9747 llvm::APSInt Result = EVResult.Val.getInt(); 9748 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9749 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9750 llvm::APFloat::rmTowardZero); 9751 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9752 !IntTy->hasSignedIntegerRepresentation()); 9753 bool Ignored = false; 9754 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9755 &Ignored); 9756 if (Result != ConvertBack) 9757 return true; 9758 } else { 9759 // Reject types that cannot be fully encoded into the mantissa of 9760 // the float. 9761 Bits = S.Context.getTypeSize(IntTy); 9762 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9763 S.Context.getFloatTypeSemantics(FloatTy)); 9764 if (Bits > FloatPrec) 9765 return true; 9766 } 9767 9768 return false; 9769 } 9770 9771 /// Attempt to convert and splat Scalar into a vector whose types matches 9772 /// Vector following GCC conversion rules. The rule is that implicit 9773 /// conversion can occur when Scalar can be casted to match Vector's element 9774 /// type without causing truncation of Scalar. 9775 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9776 ExprResult *Vector) { 9777 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9778 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9779 const VectorType *VT = VectorTy->getAs<VectorType>(); 9780 9781 assert(!isa<ExtVectorType>(VT) && 9782 "ExtVectorTypes should not be handled here!"); 9783 9784 QualType VectorEltTy = VT->getElementType(); 9785 9786 // Reject cases where the vector element type or the scalar element type are 9787 // not integral or floating point types. 9788 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9789 return true; 9790 9791 // The conversion to apply to the scalar before splatting it, 9792 // if necessary. 9793 CastKind ScalarCast = CK_NoOp; 9794 9795 // Accept cases where the vector elements are integers and the scalar is 9796 // an integer. 9797 // FIXME: Notionally if the scalar was a floating point value with a precise 9798 // integral representation, we could cast it to an appropriate integer 9799 // type and then perform the rest of the checks here. GCC will perform 9800 // this conversion in some cases as determined by the input language. 9801 // We should accept it on a language independent basis. 9802 if (VectorEltTy->isIntegralType(S.Context) && 9803 ScalarTy->isIntegralType(S.Context) && 9804 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9805 9806 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9807 return true; 9808 9809 ScalarCast = CK_IntegralCast; 9810 } else if (VectorEltTy->isIntegralType(S.Context) && 9811 ScalarTy->isRealFloatingType()) { 9812 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9813 ScalarCast = CK_FloatingToIntegral; 9814 else 9815 return true; 9816 } else if (VectorEltTy->isRealFloatingType()) { 9817 if (ScalarTy->isRealFloatingType()) { 9818 9819 // Reject cases where the scalar type is not a constant and has a higher 9820 // Order than the vector element type. 9821 llvm::APFloat Result(0.0); 9822 9823 // Determine whether this is a constant scalar. In the event that the 9824 // value is dependent (and thus cannot be evaluated by the constant 9825 // evaluator), skip the evaluation. This will then diagnose once the 9826 // expression is instantiated. 9827 bool CstScalar = Scalar->get()->isValueDependent() || 9828 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9829 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9830 if (!CstScalar && Order < 0) 9831 return true; 9832 9833 // If the scalar cannot be safely casted to the vector element type, 9834 // reject it. 9835 if (CstScalar) { 9836 bool Truncated = false; 9837 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9838 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9839 if (Truncated) 9840 return true; 9841 } 9842 9843 ScalarCast = CK_FloatingCast; 9844 } else if (ScalarTy->isIntegralType(S.Context)) { 9845 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9846 return true; 9847 9848 ScalarCast = CK_IntegralToFloating; 9849 } else 9850 return true; 9851 } else if (ScalarTy->isEnumeralType()) 9852 return true; 9853 9854 // Adjust scalar if desired. 9855 if (Scalar) { 9856 if (ScalarCast != CK_NoOp) 9857 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9858 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9859 } 9860 return false; 9861 } 9862 9863 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9864 SourceLocation Loc, bool IsCompAssign, 9865 bool AllowBothBool, 9866 bool AllowBoolConversions) { 9867 if (!IsCompAssign) { 9868 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9869 if (LHS.isInvalid()) 9870 return QualType(); 9871 } 9872 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9873 if (RHS.isInvalid()) 9874 return QualType(); 9875 9876 // For conversion purposes, we ignore any qualifiers. 9877 // For example, "const float" and "float" are equivalent. 9878 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9879 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9880 9881 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9882 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9883 assert(LHSVecType || RHSVecType); 9884 9885 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9886 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9887 return InvalidOperands(Loc, LHS, RHS); 9888 9889 // AltiVec-style "vector bool op vector bool" combinations are allowed 9890 // for some operators but not others. 9891 if (!AllowBothBool && 9892 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9893 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9894 return InvalidOperands(Loc, LHS, RHS); 9895 9896 // If the vector types are identical, return. 9897 if (Context.hasSameType(LHSType, RHSType)) 9898 return LHSType; 9899 9900 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9901 if (LHSVecType && RHSVecType && 9902 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9903 if (isa<ExtVectorType>(LHSVecType)) { 9904 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9905 return LHSType; 9906 } 9907 9908 if (!IsCompAssign) 9909 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9910 return RHSType; 9911 } 9912 9913 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9914 // can be mixed, with the result being the non-bool type. The non-bool 9915 // operand must have integer element type. 9916 if (AllowBoolConversions && LHSVecType && RHSVecType && 9917 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9918 (Context.getTypeSize(LHSVecType->getElementType()) == 9919 Context.getTypeSize(RHSVecType->getElementType()))) { 9920 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9921 LHSVecType->getElementType()->isIntegerType() && 9922 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9923 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9924 return LHSType; 9925 } 9926 if (!IsCompAssign && 9927 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9928 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9929 RHSVecType->getElementType()->isIntegerType()) { 9930 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9931 return RHSType; 9932 } 9933 } 9934 9935 // Expressions containing fixed-length and sizeless SVE vectors are invalid 9936 // since the ambiguity can affect the ABI. 9937 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9938 const VectorType *VecType = SecondType->getAs<VectorType>(); 9939 return FirstType->isSizelessBuiltinType() && VecType && 9940 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9941 VecType->getVectorKind() == 9942 VectorType::SveFixedLengthPredicateVector); 9943 }; 9944 9945 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9946 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 9947 return QualType(); 9948 } 9949 9950 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 9951 // since the ambiguity can affect the ABI. 9952 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 9953 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 9954 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 9955 9956 if (FirstVecType && SecondVecType) 9957 return FirstVecType->getVectorKind() == VectorType::GenericVector && 9958 (SecondVecType->getVectorKind() == 9959 VectorType::SveFixedLengthDataVector || 9960 SecondVecType->getVectorKind() == 9961 VectorType::SveFixedLengthPredicateVector); 9962 9963 return FirstType->isSizelessBuiltinType() && SecondVecType && 9964 SecondVecType->getVectorKind() == VectorType::GenericVector; 9965 }; 9966 9967 if (IsSveGnuConversion(LHSType, RHSType) || 9968 IsSveGnuConversion(RHSType, LHSType)) { 9969 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 9970 return QualType(); 9971 } 9972 9973 // If there's a vector type and a scalar, try to convert the scalar to 9974 // the vector element type and splat. 9975 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9976 if (!RHSVecType) { 9977 if (isa<ExtVectorType>(LHSVecType)) { 9978 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9979 LHSVecType->getElementType(), LHSType, 9980 DiagID)) 9981 return LHSType; 9982 } else { 9983 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9984 return LHSType; 9985 } 9986 } 9987 if (!LHSVecType) { 9988 if (isa<ExtVectorType>(RHSVecType)) { 9989 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9990 LHSType, RHSVecType->getElementType(), 9991 RHSType, DiagID)) 9992 return RHSType; 9993 } else { 9994 if (LHS.get()->getValueKind() == VK_LValue || 9995 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9996 return RHSType; 9997 } 9998 } 9999 10000 // FIXME: The code below also handles conversion between vectors and 10001 // non-scalars, we should break this down into fine grained specific checks 10002 // and emit proper diagnostics. 10003 QualType VecType = LHSVecType ? LHSType : RHSType; 10004 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10005 QualType OtherType = LHSVecType ? RHSType : LHSType; 10006 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10007 if (isLaxVectorConversion(OtherType, VecType)) { 10008 // If we're allowing lax vector conversions, only the total (data) size 10009 // needs to be the same. For non compound assignment, if one of the types is 10010 // scalar, the result is always the vector type. 10011 if (!IsCompAssign) { 10012 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10013 return VecType; 10014 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10015 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10016 // type. Note that this is already done by non-compound assignments in 10017 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10018 // <1 x T> -> T. The result is also a vector type. 10019 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10020 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10021 ExprResult *RHSExpr = &RHS; 10022 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10023 return VecType; 10024 } 10025 } 10026 10027 // Okay, the expression is invalid. 10028 10029 // If there's a non-vector, non-real operand, diagnose that. 10030 if ((!RHSVecType && !RHSType->isRealType()) || 10031 (!LHSVecType && !LHSType->isRealType())) { 10032 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10033 << LHSType << RHSType 10034 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10035 return QualType(); 10036 } 10037 10038 // OpenCL V1.1 6.2.6.p1: 10039 // If the operands are of more than one vector type, then an error shall 10040 // occur. Implicit conversions between vector types are not permitted, per 10041 // section 6.2.1. 10042 if (getLangOpts().OpenCL && 10043 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10044 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10045 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10046 << RHSType; 10047 return QualType(); 10048 } 10049 10050 10051 // If there is a vector type that is not a ExtVector and a scalar, we reach 10052 // this point if scalar could not be converted to the vector's element type 10053 // without truncation. 10054 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10055 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10056 QualType Scalar = LHSVecType ? RHSType : LHSType; 10057 QualType Vector = LHSVecType ? LHSType : RHSType; 10058 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10059 Diag(Loc, 10060 diag::err_typecheck_vector_not_convertable_implict_truncation) 10061 << ScalarOrVector << Scalar << Vector; 10062 10063 return QualType(); 10064 } 10065 10066 // Otherwise, use the generic diagnostic. 10067 Diag(Loc, DiagID) 10068 << LHSType << RHSType 10069 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10070 return QualType(); 10071 } 10072 10073 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10074 // expression. These are mainly cases where the null pointer is used as an 10075 // integer instead of a pointer. 10076 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10077 SourceLocation Loc, bool IsCompare) { 10078 // The canonical way to check for a GNU null is with isNullPointerConstant, 10079 // but we use a bit of a hack here for speed; this is a relatively 10080 // hot path, and isNullPointerConstant is slow. 10081 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10082 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10083 10084 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10085 10086 // Avoid analyzing cases where the result will either be invalid (and 10087 // diagnosed as such) or entirely valid and not something to warn about. 10088 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10089 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10090 return; 10091 10092 // Comparison operations would not make sense with a null pointer no matter 10093 // what the other expression is. 10094 if (!IsCompare) { 10095 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10096 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10097 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10098 return; 10099 } 10100 10101 // The rest of the operations only make sense with a null pointer 10102 // if the other expression is a pointer. 10103 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10104 NonNullType->canDecayToPointerType()) 10105 return; 10106 10107 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10108 << LHSNull /* LHS is NULL */ << NonNullType 10109 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10110 } 10111 10112 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10113 SourceLocation Loc) { 10114 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10115 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10116 if (!LUE || !RUE) 10117 return; 10118 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10119 RUE->getKind() != UETT_SizeOf) 10120 return; 10121 10122 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10123 QualType LHSTy = LHSArg->getType(); 10124 QualType RHSTy; 10125 10126 if (RUE->isArgumentType()) 10127 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10128 else 10129 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10130 10131 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10132 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10133 return; 10134 10135 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10136 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10137 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10138 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10139 << LHSArgDecl; 10140 } 10141 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10142 QualType ArrayElemTy = ArrayTy->getElementType(); 10143 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10144 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10145 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10146 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10147 return; 10148 S.Diag(Loc, diag::warn_division_sizeof_array) 10149 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10150 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10151 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10152 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10153 << LHSArgDecl; 10154 } 10155 10156 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10157 } 10158 } 10159 10160 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10161 ExprResult &RHS, 10162 SourceLocation Loc, bool IsDiv) { 10163 // Check for division/remainder by zero. 10164 Expr::EvalResult RHSValue; 10165 if (!RHS.get()->isValueDependent() && 10166 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10167 RHSValue.Val.getInt() == 0) 10168 S.DiagRuntimeBehavior(Loc, RHS.get(), 10169 S.PDiag(diag::warn_remainder_division_by_zero) 10170 << IsDiv << RHS.get()->getSourceRange()); 10171 } 10172 10173 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10174 SourceLocation Loc, 10175 bool IsCompAssign, bool IsDiv) { 10176 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10177 10178 if (LHS.get()->getType()->isVectorType() || 10179 RHS.get()->getType()->isVectorType()) 10180 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10181 /*AllowBothBool*/getLangOpts().AltiVec, 10182 /*AllowBoolConversions*/false); 10183 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10184 RHS.get()->getType()->isConstantMatrixType())) 10185 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10186 10187 QualType compType = UsualArithmeticConversions( 10188 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10189 if (LHS.isInvalid() || RHS.isInvalid()) 10190 return QualType(); 10191 10192 10193 if (compType.isNull() || !compType->isArithmeticType()) 10194 return InvalidOperands(Loc, LHS, RHS); 10195 if (IsDiv) { 10196 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10197 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10198 } 10199 return compType; 10200 } 10201 10202 QualType Sema::CheckRemainderOperands( 10203 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10204 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10205 10206 if (LHS.get()->getType()->isVectorType() || 10207 RHS.get()->getType()->isVectorType()) { 10208 if (LHS.get()->getType()->hasIntegerRepresentation() && 10209 RHS.get()->getType()->hasIntegerRepresentation()) 10210 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10211 /*AllowBothBool*/getLangOpts().AltiVec, 10212 /*AllowBoolConversions*/false); 10213 return InvalidOperands(Loc, LHS, RHS); 10214 } 10215 10216 QualType compType = UsualArithmeticConversions( 10217 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10218 if (LHS.isInvalid() || RHS.isInvalid()) 10219 return QualType(); 10220 10221 if (compType.isNull() || !compType->isIntegerType()) 10222 return InvalidOperands(Loc, LHS, RHS); 10223 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10224 return compType; 10225 } 10226 10227 /// Diagnose invalid arithmetic on two void pointers. 10228 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10229 Expr *LHSExpr, Expr *RHSExpr) { 10230 S.Diag(Loc, S.getLangOpts().CPlusPlus 10231 ? diag::err_typecheck_pointer_arith_void_type 10232 : diag::ext_gnu_void_ptr) 10233 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10234 << RHSExpr->getSourceRange(); 10235 } 10236 10237 /// Diagnose invalid arithmetic on a void pointer. 10238 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10239 Expr *Pointer) { 10240 S.Diag(Loc, S.getLangOpts().CPlusPlus 10241 ? diag::err_typecheck_pointer_arith_void_type 10242 : diag::ext_gnu_void_ptr) 10243 << 0 /* one pointer */ << Pointer->getSourceRange(); 10244 } 10245 10246 /// Diagnose invalid arithmetic on a null pointer. 10247 /// 10248 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10249 /// idiom, which we recognize as a GNU extension. 10250 /// 10251 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10252 Expr *Pointer, bool IsGNUIdiom) { 10253 if (IsGNUIdiom) 10254 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10255 << Pointer->getSourceRange(); 10256 else 10257 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10258 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10259 } 10260 10261 /// Diagnose invalid arithmetic on two function pointers. 10262 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10263 Expr *LHS, Expr *RHS) { 10264 assert(LHS->getType()->isAnyPointerType()); 10265 assert(RHS->getType()->isAnyPointerType()); 10266 S.Diag(Loc, S.getLangOpts().CPlusPlus 10267 ? diag::err_typecheck_pointer_arith_function_type 10268 : diag::ext_gnu_ptr_func_arith) 10269 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10270 // We only show the second type if it differs from the first. 10271 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10272 RHS->getType()) 10273 << RHS->getType()->getPointeeType() 10274 << LHS->getSourceRange() << RHS->getSourceRange(); 10275 } 10276 10277 /// Diagnose invalid arithmetic on a function pointer. 10278 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10279 Expr *Pointer) { 10280 assert(Pointer->getType()->isAnyPointerType()); 10281 S.Diag(Loc, S.getLangOpts().CPlusPlus 10282 ? diag::err_typecheck_pointer_arith_function_type 10283 : diag::ext_gnu_ptr_func_arith) 10284 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10285 << 0 /* one pointer, so only one type */ 10286 << Pointer->getSourceRange(); 10287 } 10288 10289 /// Emit error if Operand is incomplete pointer type 10290 /// 10291 /// \returns True if pointer has incomplete type 10292 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10293 Expr *Operand) { 10294 QualType ResType = Operand->getType(); 10295 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10296 ResType = ResAtomicType->getValueType(); 10297 10298 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10299 QualType PointeeTy = ResType->getPointeeType(); 10300 return S.RequireCompleteSizedType( 10301 Loc, PointeeTy, 10302 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10303 Operand->getSourceRange()); 10304 } 10305 10306 /// Check the validity of an arithmetic pointer operand. 10307 /// 10308 /// If the operand has pointer type, this code will check for pointer types 10309 /// which are invalid in arithmetic operations. These will be diagnosed 10310 /// appropriately, including whether or not the use is supported as an 10311 /// extension. 10312 /// 10313 /// \returns True when the operand is valid to use (even if as an extension). 10314 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10315 Expr *Operand) { 10316 QualType ResType = Operand->getType(); 10317 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10318 ResType = ResAtomicType->getValueType(); 10319 10320 if (!ResType->isAnyPointerType()) return true; 10321 10322 QualType PointeeTy = ResType->getPointeeType(); 10323 if (PointeeTy->isVoidType()) { 10324 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10325 return !S.getLangOpts().CPlusPlus; 10326 } 10327 if (PointeeTy->isFunctionType()) { 10328 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10329 return !S.getLangOpts().CPlusPlus; 10330 } 10331 10332 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10333 10334 return true; 10335 } 10336 10337 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10338 /// operands. 10339 /// 10340 /// This routine will diagnose any invalid arithmetic on pointer operands much 10341 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10342 /// for emitting a single diagnostic even for operations where both LHS and RHS 10343 /// are (potentially problematic) pointers. 10344 /// 10345 /// \returns True when the operand is valid to use (even if as an extension). 10346 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10347 Expr *LHSExpr, Expr *RHSExpr) { 10348 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10349 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10350 if (!isLHSPointer && !isRHSPointer) return true; 10351 10352 QualType LHSPointeeTy, RHSPointeeTy; 10353 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10354 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10355 10356 // if both are pointers check if operation is valid wrt address spaces 10357 if (isLHSPointer && isRHSPointer) { 10358 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10359 S.Diag(Loc, 10360 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10361 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10362 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10363 return false; 10364 } 10365 } 10366 10367 // Check for arithmetic on pointers to incomplete types. 10368 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10369 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10370 if (isLHSVoidPtr || isRHSVoidPtr) { 10371 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10372 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10373 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10374 10375 return !S.getLangOpts().CPlusPlus; 10376 } 10377 10378 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10379 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10380 if (isLHSFuncPtr || isRHSFuncPtr) { 10381 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10382 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10383 RHSExpr); 10384 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10385 10386 return !S.getLangOpts().CPlusPlus; 10387 } 10388 10389 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10390 return false; 10391 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10392 return false; 10393 10394 return true; 10395 } 10396 10397 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10398 /// literal. 10399 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10400 Expr *LHSExpr, Expr *RHSExpr) { 10401 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10402 Expr* IndexExpr = RHSExpr; 10403 if (!StrExpr) { 10404 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10405 IndexExpr = LHSExpr; 10406 } 10407 10408 bool IsStringPlusInt = StrExpr && 10409 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10410 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10411 return; 10412 10413 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10414 Self.Diag(OpLoc, diag::warn_string_plus_int) 10415 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10416 10417 // Only print a fixit for "str" + int, not for int + "str". 10418 if (IndexExpr == RHSExpr) { 10419 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10420 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10421 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10422 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10423 << FixItHint::CreateInsertion(EndLoc, "]"); 10424 } else 10425 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10426 } 10427 10428 /// Emit a warning when adding a char literal to a string. 10429 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10430 Expr *LHSExpr, Expr *RHSExpr) { 10431 const Expr *StringRefExpr = LHSExpr; 10432 const CharacterLiteral *CharExpr = 10433 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10434 10435 if (!CharExpr) { 10436 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10437 StringRefExpr = RHSExpr; 10438 } 10439 10440 if (!CharExpr || !StringRefExpr) 10441 return; 10442 10443 const QualType StringType = StringRefExpr->getType(); 10444 10445 // Return if not a PointerType. 10446 if (!StringType->isAnyPointerType()) 10447 return; 10448 10449 // Return if not a CharacterType. 10450 if (!StringType->getPointeeType()->isAnyCharacterType()) 10451 return; 10452 10453 ASTContext &Ctx = Self.getASTContext(); 10454 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10455 10456 const QualType CharType = CharExpr->getType(); 10457 if (!CharType->isAnyCharacterType() && 10458 CharType->isIntegerType() && 10459 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10460 Self.Diag(OpLoc, diag::warn_string_plus_char) 10461 << DiagRange << Ctx.CharTy; 10462 } else { 10463 Self.Diag(OpLoc, diag::warn_string_plus_char) 10464 << DiagRange << CharExpr->getType(); 10465 } 10466 10467 // Only print a fixit for str + char, not for char + str. 10468 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10469 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10470 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10471 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10472 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10473 << FixItHint::CreateInsertion(EndLoc, "]"); 10474 } else { 10475 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10476 } 10477 } 10478 10479 /// Emit error when two pointers are incompatible. 10480 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10481 Expr *LHSExpr, Expr *RHSExpr) { 10482 assert(LHSExpr->getType()->isAnyPointerType()); 10483 assert(RHSExpr->getType()->isAnyPointerType()); 10484 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10485 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10486 << RHSExpr->getSourceRange(); 10487 } 10488 10489 // C99 6.5.6 10490 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10491 SourceLocation Loc, BinaryOperatorKind Opc, 10492 QualType* CompLHSTy) { 10493 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10494 10495 if (LHS.get()->getType()->isVectorType() || 10496 RHS.get()->getType()->isVectorType()) { 10497 QualType compType = CheckVectorOperands( 10498 LHS, RHS, Loc, CompLHSTy, 10499 /*AllowBothBool*/getLangOpts().AltiVec, 10500 /*AllowBoolConversions*/getLangOpts().ZVector); 10501 if (CompLHSTy) *CompLHSTy = compType; 10502 return compType; 10503 } 10504 10505 if (LHS.get()->getType()->isConstantMatrixType() || 10506 RHS.get()->getType()->isConstantMatrixType()) { 10507 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10508 } 10509 10510 QualType compType = UsualArithmeticConversions( 10511 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10512 if (LHS.isInvalid() || RHS.isInvalid()) 10513 return QualType(); 10514 10515 // Diagnose "string literal" '+' int and string '+' "char literal". 10516 if (Opc == BO_Add) { 10517 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10518 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10519 } 10520 10521 // handle the common case first (both operands are arithmetic). 10522 if (!compType.isNull() && compType->isArithmeticType()) { 10523 if (CompLHSTy) *CompLHSTy = compType; 10524 return compType; 10525 } 10526 10527 // Type-checking. Ultimately the pointer's going to be in PExp; 10528 // note that we bias towards the LHS being the pointer. 10529 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10530 10531 bool isObjCPointer; 10532 if (PExp->getType()->isPointerType()) { 10533 isObjCPointer = false; 10534 } else if (PExp->getType()->isObjCObjectPointerType()) { 10535 isObjCPointer = true; 10536 } else { 10537 std::swap(PExp, IExp); 10538 if (PExp->getType()->isPointerType()) { 10539 isObjCPointer = false; 10540 } else if (PExp->getType()->isObjCObjectPointerType()) { 10541 isObjCPointer = true; 10542 } else { 10543 return InvalidOperands(Loc, LHS, RHS); 10544 } 10545 } 10546 assert(PExp->getType()->isAnyPointerType()); 10547 10548 if (!IExp->getType()->isIntegerType()) 10549 return InvalidOperands(Loc, LHS, RHS); 10550 10551 // Adding to a null pointer results in undefined behavior. 10552 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10553 Context, Expr::NPC_ValueDependentIsNotNull)) { 10554 // In C++ adding zero to a null pointer is defined. 10555 Expr::EvalResult KnownVal; 10556 if (!getLangOpts().CPlusPlus || 10557 (!IExp->isValueDependent() && 10558 (!IExp->EvaluateAsInt(KnownVal, Context) || 10559 KnownVal.Val.getInt() != 0))) { 10560 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10561 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10562 Context, BO_Add, PExp, IExp); 10563 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10564 } 10565 } 10566 10567 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10568 return QualType(); 10569 10570 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10571 return QualType(); 10572 10573 // Check array bounds for pointer arithemtic 10574 CheckArrayAccess(PExp, IExp); 10575 10576 if (CompLHSTy) { 10577 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10578 if (LHSTy.isNull()) { 10579 LHSTy = LHS.get()->getType(); 10580 if (LHSTy->isPromotableIntegerType()) 10581 LHSTy = Context.getPromotedIntegerType(LHSTy); 10582 } 10583 *CompLHSTy = LHSTy; 10584 } 10585 10586 return PExp->getType(); 10587 } 10588 10589 // C99 6.5.6 10590 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10591 SourceLocation Loc, 10592 QualType* CompLHSTy) { 10593 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10594 10595 if (LHS.get()->getType()->isVectorType() || 10596 RHS.get()->getType()->isVectorType()) { 10597 QualType compType = CheckVectorOperands( 10598 LHS, RHS, Loc, CompLHSTy, 10599 /*AllowBothBool*/getLangOpts().AltiVec, 10600 /*AllowBoolConversions*/getLangOpts().ZVector); 10601 if (CompLHSTy) *CompLHSTy = compType; 10602 return compType; 10603 } 10604 10605 if (LHS.get()->getType()->isConstantMatrixType() || 10606 RHS.get()->getType()->isConstantMatrixType()) { 10607 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10608 } 10609 10610 QualType compType = UsualArithmeticConversions( 10611 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10612 if (LHS.isInvalid() || RHS.isInvalid()) 10613 return QualType(); 10614 10615 // Enforce type constraints: C99 6.5.6p3. 10616 10617 // Handle the common case first (both operands are arithmetic). 10618 if (!compType.isNull() && compType->isArithmeticType()) { 10619 if (CompLHSTy) *CompLHSTy = compType; 10620 return compType; 10621 } 10622 10623 // Either ptr - int or ptr - ptr. 10624 if (LHS.get()->getType()->isAnyPointerType()) { 10625 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10626 10627 // Diagnose bad cases where we step over interface counts. 10628 if (LHS.get()->getType()->isObjCObjectPointerType() && 10629 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10630 return QualType(); 10631 10632 // The result type of a pointer-int computation is the pointer type. 10633 if (RHS.get()->getType()->isIntegerType()) { 10634 // Subtracting from a null pointer should produce a warning. 10635 // The last argument to the diagnose call says this doesn't match the 10636 // GNU int-to-pointer idiom. 10637 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10638 Expr::NPC_ValueDependentIsNotNull)) { 10639 // In C++ adding zero to a null pointer is defined. 10640 Expr::EvalResult KnownVal; 10641 if (!getLangOpts().CPlusPlus || 10642 (!RHS.get()->isValueDependent() && 10643 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10644 KnownVal.Val.getInt() != 0))) { 10645 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10646 } 10647 } 10648 10649 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10650 return QualType(); 10651 10652 // Check array bounds for pointer arithemtic 10653 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10654 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10655 10656 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10657 return LHS.get()->getType(); 10658 } 10659 10660 // Handle pointer-pointer subtractions. 10661 if (const PointerType *RHSPTy 10662 = RHS.get()->getType()->getAs<PointerType>()) { 10663 QualType rpointee = RHSPTy->getPointeeType(); 10664 10665 if (getLangOpts().CPlusPlus) { 10666 // Pointee types must be the same: C++ [expr.add] 10667 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10668 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10669 } 10670 } else { 10671 // Pointee types must be compatible C99 6.5.6p3 10672 if (!Context.typesAreCompatible( 10673 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10674 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10675 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10676 return QualType(); 10677 } 10678 } 10679 10680 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10681 LHS.get(), RHS.get())) 10682 return QualType(); 10683 10684 // FIXME: Add warnings for nullptr - ptr. 10685 10686 // The pointee type may have zero size. As an extension, a structure or 10687 // union may have zero size or an array may have zero length. In this 10688 // case subtraction does not make sense. 10689 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10690 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10691 if (ElementSize.isZero()) { 10692 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10693 << rpointee.getUnqualifiedType() 10694 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10695 } 10696 } 10697 10698 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10699 return Context.getPointerDiffType(); 10700 } 10701 } 10702 10703 return InvalidOperands(Loc, LHS, RHS); 10704 } 10705 10706 static bool isScopedEnumerationType(QualType T) { 10707 if (const EnumType *ET = T->getAs<EnumType>()) 10708 return ET->getDecl()->isScoped(); 10709 return false; 10710 } 10711 10712 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10713 SourceLocation Loc, BinaryOperatorKind Opc, 10714 QualType LHSType) { 10715 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10716 // so skip remaining warnings as we don't want to modify values within Sema. 10717 if (S.getLangOpts().OpenCL) 10718 return; 10719 10720 // Check right/shifter operand 10721 Expr::EvalResult RHSResult; 10722 if (RHS.get()->isValueDependent() || 10723 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10724 return; 10725 llvm::APSInt Right = RHSResult.Val.getInt(); 10726 10727 if (Right.isNegative()) { 10728 S.DiagRuntimeBehavior(Loc, RHS.get(), 10729 S.PDiag(diag::warn_shift_negative) 10730 << RHS.get()->getSourceRange()); 10731 return; 10732 } 10733 10734 QualType LHSExprType = LHS.get()->getType(); 10735 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10736 if (LHSExprType->isExtIntType()) 10737 LeftSize = S.Context.getIntWidth(LHSExprType); 10738 else if (LHSExprType->isFixedPointType()) { 10739 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10740 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10741 } 10742 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10743 if (Right.uge(LeftBits)) { 10744 S.DiagRuntimeBehavior(Loc, RHS.get(), 10745 S.PDiag(diag::warn_shift_gt_typewidth) 10746 << RHS.get()->getSourceRange()); 10747 return; 10748 } 10749 10750 // FIXME: We probably need to handle fixed point types specially here. 10751 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10752 return; 10753 10754 // When left shifting an ICE which is signed, we can check for overflow which 10755 // according to C++ standards prior to C++2a has undefined behavior 10756 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10757 // more than the maximum value representable in the result type, so never 10758 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10759 // expression is still probably a bug.) 10760 Expr::EvalResult LHSResult; 10761 if (LHS.get()->isValueDependent() || 10762 LHSType->hasUnsignedIntegerRepresentation() || 10763 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10764 return; 10765 llvm::APSInt Left = LHSResult.Val.getInt(); 10766 10767 // If LHS does not have a signed type and non-negative value 10768 // then, the behavior is undefined before C++2a. Warn about it. 10769 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10770 !S.getLangOpts().CPlusPlus20) { 10771 S.DiagRuntimeBehavior(Loc, LHS.get(), 10772 S.PDiag(diag::warn_shift_lhs_negative) 10773 << LHS.get()->getSourceRange()); 10774 return; 10775 } 10776 10777 llvm::APInt ResultBits = 10778 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10779 if (LeftBits.uge(ResultBits)) 10780 return; 10781 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10782 Result = Result.shl(Right); 10783 10784 // Print the bit representation of the signed integer as an unsigned 10785 // hexadecimal number. 10786 SmallString<40> HexResult; 10787 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10788 10789 // If we are only missing a sign bit, this is less likely to result in actual 10790 // bugs -- if the result is cast back to an unsigned type, it will have the 10791 // expected value. Thus we place this behind a different warning that can be 10792 // turned off separately if needed. 10793 if (LeftBits == ResultBits - 1) { 10794 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10795 << HexResult << LHSType 10796 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10797 return; 10798 } 10799 10800 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10801 << HexResult.str() << Result.getMinSignedBits() << LHSType 10802 << Left.getBitWidth() << LHS.get()->getSourceRange() 10803 << RHS.get()->getSourceRange(); 10804 } 10805 10806 /// Return the resulting type when a vector is shifted 10807 /// by a scalar or vector shift amount. 10808 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10809 SourceLocation Loc, bool IsCompAssign) { 10810 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10811 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10812 !LHS.get()->getType()->isVectorType()) { 10813 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10814 << RHS.get()->getType() << LHS.get()->getType() 10815 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10816 return QualType(); 10817 } 10818 10819 if (!IsCompAssign) { 10820 LHS = S.UsualUnaryConversions(LHS.get()); 10821 if (LHS.isInvalid()) return QualType(); 10822 } 10823 10824 RHS = S.UsualUnaryConversions(RHS.get()); 10825 if (RHS.isInvalid()) return QualType(); 10826 10827 QualType LHSType = LHS.get()->getType(); 10828 // Note that LHS might be a scalar because the routine calls not only in 10829 // OpenCL case. 10830 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10831 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10832 10833 // Note that RHS might not be a vector. 10834 QualType RHSType = RHS.get()->getType(); 10835 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10836 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10837 10838 // The operands need to be integers. 10839 if (!LHSEleType->isIntegerType()) { 10840 S.Diag(Loc, diag::err_typecheck_expect_int) 10841 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10842 return QualType(); 10843 } 10844 10845 if (!RHSEleType->isIntegerType()) { 10846 S.Diag(Loc, diag::err_typecheck_expect_int) 10847 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10848 return QualType(); 10849 } 10850 10851 if (!LHSVecTy) { 10852 assert(RHSVecTy); 10853 if (IsCompAssign) 10854 return RHSType; 10855 if (LHSEleType != RHSEleType) { 10856 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10857 LHSEleType = RHSEleType; 10858 } 10859 QualType VecTy = 10860 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10861 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10862 LHSType = VecTy; 10863 } else if (RHSVecTy) { 10864 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10865 // are applied component-wise. So if RHS is a vector, then ensure 10866 // that the number of elements is the same as LHS... 10867 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10868 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10869 << LHS.get()->getType() << RHS.get()->getType() 10870 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10871 return QualType(); 10872 } 10873 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10874 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10875 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10876 if (LHSBT != RHSBT && 10877 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10878 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10879 << LHS.get()->getType() << RHS.get()->getType() 10880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10881 } 10882 } 10883 } else { 10884 // ...else expand RHS to match the number of elements in LHS. 10885 QualType VecTy = 10886 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10887 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10888 } 10889 10890 return LHSType; 10891 } 10892 10893 // C99 6.5.7 10894 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10895 SourceLocation Loc, BinaryOperatorKind Opc, 10896 bool IsCompAssign) { 10897 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10898 10899 // Vector shifts promote their scalar inputs to vector type. 10900 if (LHS.get()->getType()->isVectorType() || 10901 RHS.get()->getType()->isVectorType()) { 10902 if (LangOpts.ZVector) { 10903 // The shift operators for the z vector extensions work basically 10904 // like general shifts, except that neither the LHS nor the RHS is 10905 // allowed to be a "vector bool". 10906 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10907 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10908 return InvalidOperands(Loc, LHS, RHS); 10909 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10910 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10911 return InvalidOperands(Loc, LHS, RHS); 10912 } 10913 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10914 } 10915 10916 // Shifts don't perform usual arithmetic conversions, they just do integer 10917 // promotions on each operand. C99 6.5.7p3 10918 10919 // For the LHS, do usual unary conversions, but then reset them away 10920 // if this is a compound assignment. 10921 ExprResult OldLHS = LHS; 10922 LHS = UsualUnaryConversions(LHS.get()); 10923 if (LHS.isInvalid()) 10924 return QualType(); 10925 QualType LHSType = LHS.get()->getType(); 10926 if (IsCompAssign) LHS = OldLHS; 10927 10928 // The RHS is simpler. 10929 RHS = UsualUnaryConversions(RHS.get()); 10930 if (RHS.isInvalid()) 10931 return QualType(); 10932 QualType RHSType = RHS.get()->getType(); 10933 10934 // C99 6.5.7p2: Each of the operands shall have integer type. 10935 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10936 if ((!LHSType->isFixedPointOrIntegerType() && 10937 !LHSType->hasIntegerRepresentation()) || 10938 !RHSType->hasIntegerRepresentation()) 10939 return InvalidOperands(Loc, LHS, RHS); 10940 10941 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10942 // hasIntegerRepresentation() above instead of this. 10943 if (isScopedEnumerationType(LHSType) || 10944 isScopedEnumerationType(RHSType)) { 10945 return InvalidOperands(Loc, LHS, RHS); 10946 } 10947 // Sanity-check shift operands 10948 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10949 10950 // "The type of the result is that of the promoted left operand." 10951 return LHSType; 10952 } 10953 10954 /// Diagnose bad pointer comparisons. 10955 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10956 ExprResult &LHS, ExprResult &RHS, 10957 bool IsError) { 10958 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10959 : diag::ext_typecheck_comparison_of_distinct_pointers) 10960 << LHS.get()->getType() << RHS.get()->getType() 10961 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10962 } 10963 10964 /// Returns false if the pointers are converted to a composite type, 10965 /// true otherwise. 10966 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10967 ExprResult &LHS, ExprResult &RHS) { 10968 // C++ [expr.rel]p2: 10969 // [...] Pointer conversions (4.10) and qualification 10970 // conversions (4.4) are performed on pointer operands (or on 10971 // a pointer operand and a null pointer constant) to bring 10972 // them to their composite pointer type. [...] 10973 // 10974 // C++ [expr.eq]p1 uses the same notion for (in)equality 10975 // comparisons of pointers. 10976 10977 QualType LHSType = LHS.get()->getType(); 10978 QualType RHSType = RHS.get()->getType(); 10979 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10980 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10981 10982 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10983 if (T.isNull()) { 10984 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10985 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10986 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10987 else 10988 S.InvalidOperands(Loc, LHS, RHS); 10989 return true; 10990 } 10991 10992 return false; 10993 } 10994 10995 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10996 ExprResult &LHS, 10997 ExprResult &RHS, 10998 bool IsError) { 10999 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11000 : diag::ext_typecheck_comparison_of_fptr_to_void) 11001 << LHS.get()->getType() << RHS.get()->getType() 11002 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11003 } 11004 11005 static bool isObjCObjectLiteral(ExprResult &E) { 11006 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11007 case Stmt::ObjCArrayLiteralClass: 11008 case Stmt::ObjCDictionaryLiteralClass: 11009 case Stmt::ObjCStringLiteralClass: 11010 case Stmt::ObjCBoxedExprClass: 11011 return true; 11012 default: 11013 // Note that ObjCBoolLiteral is NOT an object literal! 11014 return false; 11015 } 11016 } 11017 11018 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11019 const ObjCObjectPointerType *Type = 11020 LHS->getType()->getAs<ObjCObjectPointerType>(); 11021 11022 // If this is not actually an Objective-C object, bail out. 11023 if (!Type) 11024 return false; 11025 11026 // Get the LHS object's interface type. 11027 QualType InterfaceType = Type->getPointeeType(); 11028 11029 // If the RHS isn't an Objective-C object, bail out. 11030 if (!RHS->getType()->isObjCObjectPointerType()) 11031 return false; 11032 11033 // Try to find the -isEqual: method. 11034 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11035 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11036 InterfaceType, 11037 /*IsInstance=*/true); 11038 if (!Method) { 11039 if (Type->isObjCIdType()) { 11040 // For 'id', just check the global pool. 11041 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11042 /*receiverId=*/true); 11043 } else { 11044 // Check protocols. 11045 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11046 /*IsInstance=*/true); 11047 } 11048 } 11049 11050 if (!Method) 11051 return false; 11052 11053 QualType T = Method->parameters()[0]->getType(); 11054 if (!T->isObjCObjectPointerType()) 11055 return false; 11056 11057 QualType R = Method->getReturnType(); 11058 if (!R->isScalarType()) 11059 return false; 11060 11061 return true; 11062 } 11063 11064 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11065 FromE = FromE->IgnoreParenImpCasts(); 11066 switch (FromE->getStmtClass()) { 11067 default: 11068 break; 11069 case Stmt::ObjCStringLiteralClass: 11070 // "string literal" 11071 return LK_String; 11072 case Stmt::ObjCArrayLiteralClass: 11073 // "array literal" 11074 return LK_Array; 11075 case Stmt::ObjCDictionaryLiteralClass: 11076 // "dictionary literal" 11077 return LK_Dictionary; 11078 case Stmt::BlockExprClass: 11079 return LK_Block; 11080 case Stmt::ObjCBoxedExprClass: { 11081 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11082 switch (Inner->getStmtClass()) { 11083 case Stmt::IntegerLiteralClass: 11084 case Stmt::FloatingLiteralClass: 11085 case Stmt::CharacterLiteralClass: 11086 case Stmt::ObjCBoolLiteralExprClass: 11087 case Stmt::CXXBoolLiteralExprClass: 11088 // "numeric literal" 11089 return LK_Numeric; 11090 case Stmt::ImplicitCastExprClass: { 11091 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11092 // Boolean literals can be represented by implicit casts. 11093 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11094 return LK_Numeric; 11095 break; 11096 } 11097 default: 11098 break; 11099 } 11100 return LK_Boxed; 11101 } 11102 } 11103 return LK_None; 11104 } 11105 11106 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11107 ExprResult &LHS, ExprResult &RHS, 11108 BinaryOperator::Opcode Opc){ 11109 Expr *Literal; 11110 Expr *Other; 11111 if (isObjCObjectLiteral(LHS)) { 11112 Literal = LHS.get(); 11113 Other = RHS.get(); 11114 } else { 11115 Literal = RHS.get(); 11116 Other = LHS.get(); 11117 } 11118 11119 // Don't warn on comparisons against nil. 11120 Other = Other->IgnoreParenCasts(); 11121 if (Other->isNullPointerConstant(S.getASTContext(), 11122 Expr::NPC_ValueDependentIsNotNull)) 11123 return; 11124 11125 // This should be kept in sync with warn_objc_literal_comparison. 11126 // LK_String should always be after the other literals, since it has its own 11127 // warning flag. 11128 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11129 assert(LiteralKind != Sema::LK_Block); 11130 if (LiteralKind == Sema::LK_None) { 11131 llvm_unreachable("Unknown Objective-C object literal kind"); 11132 } 11133 11134 if (LiteralKind == Sema::LK_String) 11135 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11136 << Literal->getSourceRange(); 11137 else 11138 S.Diag(Loc, diag::warn_objc_literal_comparison) 11139 << LiteralKind << Literal->getSourceRange(); 11140 11141 if (BinaryOperator::isEqualityOp(Opc) && 11142 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11143 SourceLocation Start = LHS.get()->getBeginLoc(); 11144 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11145 CharSourceRange OpRange = 11146 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11147 11148 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11149 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11150 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11151 << FixItHint::CreateInsertion(End, "]"); 11152 } 11153 } 11154 11155 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11156 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11157 ExprResult &RHS, SourceLocation Loc, 11158 BinaryOperatorKind Opc) { 11159 // Check that left hand side is !something. 11160 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11161 if (!UO || UO->getOpcode() != UO_LNot) return; 11162 11163 // Only check if the right hand side is non-bool arithmetic type. 11164 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11165 11166 // Make sure that the something in !something is not bool. 11167 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11168 if (SubExpr->isKnownToHaveBooleanValue()) return; 11169 11170 // Emit warning. 11171 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11172 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11173 << Loc << IsBitwiseOp; 11174 11175 // First note suggest !(x < y) 11176 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11177 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11178 FirstClose = S.getLocForEndOfToken(FirstClose); 11179 if (FirstClose.isInvalid()) 11180 FirstOpen = SourceLocation(); 11181 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11182 << IsBitwiseOp 11183 << FixItHint::CreateInsertion(FirstOpen, "(") 11184 << FixItHint::CreateInsertion(FirstClose, ")"); 11185 11186 // Second note suggests (!x) < y 11187 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11188 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11189 SecondClose = S.getLocForEndOfToken(SecondClose); 11190 if (SecondClose.isInvalid()) 11191 SecondOpen = SourceLocation(); 11192 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11193 << FixItHint::CreateInsertion(SecondOpen, "(") 11194 << FixItHint::CreateInsertion(SecondClose, ")"); 11195 } 11196 11197 // Returns true if E refers to a non-weak array. 11198 static bool checkForArray(const Expr *E) { 11199 const ValueDecl *D = nullptr; 11200 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11201 D = DR->getDecl(); 11202 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11203 if (Mem->isImplicitAccess()) 11204 D = Mem->getMemberDecl(); 11205 } 11206 if (!D) 11207 return false; 11208 return D->getType()->isArrayType() && !D->isWeak(); 11209 } 11210 11211 /// Diagnose some forms of syntactically-obvious tautological comparison. 11212 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11213 Expr *LHS, Expr *RHS, 11214 BinaryOperatorKind Opc) { 11215 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11216 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11217 11218 QualType LHSType = LHS->getType(); 11219 QualType RHSType = RHS->getType(); 11220 if (LHSType->hasFloatingRepresentation() || 11221 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11222 S.inTemplateInstantiation()) 11223 return; 11224 11225 // Comparisons between two array types are ill-formed for operator<=>, so 11226 // we shouldn't emit any additional warnings about it. 11227 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11228 return; 11229 11230 // For non-floating point types, check for self-comparisons of the form 11231 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11232 // often indicate logic errors in the program. 11233 // 11234 // NOTE: Don't warn about comparison expressions resulting from macro 11235 // expansion. Also don't warn about comparisons which are only self 11236 // comparisons within a template instantiation. The warnings should catch 11237 // obvious cases in the definition of the template anyways. The idea is to 11238 // warn when the typed comparison operator will always evaluate to the same 11239 // result. 11240 11241 // Used for indexing into %select in warn_comparison_always 11242 enum { 11243 AlwaysConstant, 11244 AlwaysTrue, 11245 AlwaysFalse, 11246 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11247 }; 11248 11249 // C++2a [depr.array.comp]: 11250 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11251 // operands of array type are deprecated. 11252 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11253 RHSStripped->getType()->isArrayType()) { 11254 S.Diag(Loc, diag::warn_depr_array_comparison) 11255 << LHS->getSourceRange() << RHS->getSourceRange() 11256 << LHSStripped->getType() << RHSStripped->getType(); 11257 // Carry on to produce the tautological comparison warning, if this 11258 // expression is potentially-evaluated, we can resolve the array to a 11259 // non-weak declaration, and so on. 11260 } 11261 11262 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11263 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11264 unsigned Result; 11265 switch (Opc) { 11266 case BO_EQ: 11267 case BO_LE: 11268 case BO_GE: 11269 Result = AlwaysTrue; 11270 break; 11271 case BO_NE: 11272 case BO_LT: 11273 case BO_GT: 11274 Result = AlwaysFalse; 11275 break; 11276 case BO_Cmp: 11277 Result = AlwaysEqual; 11278 break; 11279 default: 11280 Result = AlwaysConstant; 11281 break; 11282 } 11283 S.DiagRuntimeBehavior(Loc, nullptr, 11284 S.PDiag(diag::warn_comparison_always) 11285 << 0 /*self-comparison*/ 11286 << Result); 11287 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11288 // What is it always going to evaluate to? 11289 unsigned Result; 11290 switch (Opc) { 11291 case BO_EQ: // e.g. array1 == array2 11292 Result = AlwaysFalse; 11293 break; 11294 case BO_NE: // e.g. array1 != array2 11295 Result = AlwaysTrue; 11296 break; 11297 default: // e.g. array1 <= array2 11298 // The best we can say is 'a constant' 11299 Result = AlwaysConstant; 11300 break; 11301 } 11302 S.DiagRuntimeBehavior(Loc, nullptr, 11303 S.PDiag(diag::warn_comparison_always) 11304 << 1 /*array comparison*/ 11305 << Result); 11306 } 11307 } 11308 11309 if (isa<CastExpr>(LHSStripped)) 11310 LHSStripped = LHSStripped->IgnoreParenCasts(); 11311 if (isa<CastExpr>(RHSStripped)) 11312 RHSStripped = RHSStripped->IgnoreParenCasts(); 11313 11314 // Warn about comparisons against a string constant (unless the other 11315 // operand is null); the user probably wants string comparison function. 11316 Expr *LiteralString = nullptr; 11317 Expr *LiteralStringStripped = nullptr; 11318 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11319 !RHSStripped->isNullPointerConstant(S.Context, 11320 Expr::NPC_ValueDependentIsNull)) { 11321 LiteralString = LHS; 11322 LiteralStringStripped = LHSStripped; 11323 } else if ((isa<StringLiteral>(RHSStripped) || 11324 isa<ObjCEncodeExpr>(RHSStripped)) && 11325 !LHSStripped->isNullPointerConstant(S.Context, 11326 Expr::NPC_ValueDependentIsNull)) { 11327 LiteralString = RHS; 11328 LiteralStringStripped = RHSStripped; 11329 } 11330 11331 if (LiteralString) { 11332 S.DiagRuntimeBehavior(Loc, nullptr, 11333 S.PDiag(diag::warn_stringcompare) 11334 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11335 << LiteralString->getSourceRange()); 11336 } 11337 } 11338 11339 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11340 switch (CK) { 11341 default: { 11342 #ifndef NDEBUG 11343 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11344 << "\n"; 11345 #endif 11346 llvm_unreachable("unhandled cast kind"); 11347 } 11348 case CK_UserDefinedConversion: 11349 return ICK_Identity; 11350 case CK_LValueToRValue: 11351 return ICK_Lvalue_To_Rvalue; 11352 case CK_ArrayToPointerDecay: 11353 return ICK_Array_To_Pointer; 11354 case CK_FunctionToPointerDecay: 11355 return ICK_Function_To_Pointer; 11356 case CK_IntegralCast: 11357 return ICK_Integral_Conversion; 11358 case CK_FloatingCast: 11359 return ICK_Floating_Conversion; 11360 case CK_IntegralToFloating: 11361 case CK_FloatingToIntegral: 11362 return ICK_Floating_Integral; 11363 case CK_IntegralComplexCast: 11364 case CK_FloatingComplexCast: 11365 case CK_FloatingComplexToIntegralComplex: 11366 case CK_IntegralComplexToFloatingComplex: 11367 return ICK_Complex_Conversion; 11368 case CK_FloatingComplexToReal: 11369 case CK_FloatingRealToComplex: 11370 case CK_IntegralComplexToReal: 11371 case CK_IntegralRealToComplex: 11372 return ICK_Complex_Real; 11373 } 11374 } 11375 11376 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11377 QualType FromType, 11378 SourceLocation Loc) { 11379 // Check for a narrowing implicit conversion. 11380 StandardConversionSequence SCS; 11381 SCS.setAsIdentityConversion(); 11382 SCS.setToType(0, FromType); 11383 SCS.setToType(1, ToType); 11384 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11385 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11386 11387 APValue PreNarrowingValue; 11388 QualType PreNarrowingType; 11389 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11390 PreNarrowingType, 11391 /*IgnoreFloatToIntegralConversion*/ true)) { 11392 case NK_Dependent_Narrowing: 11393 // Implicit conversion to a narrower type, but the expression is 11394 // value-dependent so we can't tell whether it's actually narrowing. 11395 case NK_Not_Narrowing: 11396 return false; 11397 11398 case NK_Constant_Narrowing: 11399 // Implicit conversion to a narrower type, and the value is not a constant 11400 // expression. 11401 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11402 << /*Constant*/ 1 11403 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11404 return true; 11405 11406 case NK_Variable_Narrowing: 11407 // Implicit conversion to a narrower type, and the value is not a constant 11408 // expression. 11409 case NK_Type_Narrowing: 11410 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11411 << /*Constant*/ 0 << FromType << ToType; 11412 // TODO: It's not a constant expression, but what if the user intended it 11413 // to be? Can we produce notes to help them figure out why it isn't? 11414 return true; 11415 } 11416 llvm_unreachable("unhandled case in switch"); 11417 } 11418 11419 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11420 ExprResult &LHS, 11421 ExprResult &RHS, 11422 SourceLocation Loc) { 11423 QualType LHSType = LHS.get()->getType(); 11424 QualType RHSType = RHS.get()->getType(); 11425 // Dig out the original argument type and expression before implicit casts 11426 // were applied. These are the types/expressions we need to check the 11427 // [expr.spaceship] requirements against. 11428 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11429 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11430 QualType LHSStrippedType = LHSStripped.get()->getType(); 11431 QualType RHSStrippedType = RHSStripped.get()->getType(); 11432 11433 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11434 // other is not, the program is ill-formed. 11435 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11436 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11437 return QualType(); 11438 } 11439 11440 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11441 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11442 RHSStrippedType->isEnumeralType(); 11443 if (NumEnumArgs == 1) { 11444 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11445 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11446 if (OtherTy->hasFloatingRepresentation()) { 11447 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11448 return QualType(); 11449 } 11450 } 11451 if (NumEnumArgs == 2) { 11452 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11453 // type E, the operator yields the result of converting the operands 11454 // to the underlying type of E and applying <=> to the converted operands. 11455 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11456 S.InvalidOperands(Loc, LHS, RHS); 11457 return QualType(); 11458 } 11459 QualType IntType = 11460 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11461 assert(IntType->isArithmeticType()); 11462 11463 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11464 // promote the boolean type, and all other promotable integer types, to 11465 // avoid this. 11466 if (IntType->isPromotableIntegerType()) 11467 IntType = S.Context.getPromotedIntegerType(IntType); 11468 11469 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11470 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11471 LHSType = RHSType = IntType; 11472 } 11473 11474 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11475 // usual arithmetic conversions are applied to the operands. 11476 QualType Type = 11477 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11478 if (LHS.isInvalid() || RHS.isInvalid()) 11479 return QualType(); 11480 if (Type.isNull()) 11481 return S.InvalidOperands(Loc, LHS, RHS); 11482 11483 Optional<ComparisonCategoryType> CCT = 11484 getComparisonCategoryForBuiltinCmp(Type); 11485 if (!CCT) 11486 return S.InvalidOperands(Loc, LHS, RHS); 11487 11488 bool HasNarrowing = checkThreeWayNarrowingConversion( 11489 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11490 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11491 RHS.get()->getBeginLoc()); 11492 if (HasNarrowing) 11493 return QualType(); 11494 11495 assert(!Type.isNull() && "composite type for <=> has not been set"); 11496 11497 return S.CheckComparisonCategoryType( 11498 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11499 } 11500 11501 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11502 ExprResult &RHS, 11503 SourceLocation Loc, 11504 BinaryOperatorKind Opc) { 11505 if (Opc == BO_Cmp) 11506 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11507 11508 // C99 6.5.8p3 / C99 6.5.9p4 11509 QualType Type = 11510 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11511 if (LHS.isInvalid() || RHS.isInvalid()) 11512 return QualType(); 11513 if (Type.isNull()) 11514 return S.InvalidOperands(Loc, LHS, RHS); 11515 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11516 11517 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11518 return S.InvalidOperands(Loc, LHS, RHS); 11519 11520 // Check for comparisons of floating point operands using != and ==. 11521 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11522 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11523 11524 // The result of comparisons is 'bool' in C++, 'int' in C. 11525 return S.Context.getLogicalOperationType(); 11526 } 11527 11528 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11529 if (!NullE.get()->getType()->isAnyPointerType()) 11530 return; 11531 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11532 if (!E.get()->getType()->isAnyPointerType() && 11533 E.get()->isNullPointerConstant(Context, 11534 Expr::NPC_ValueDependentIsNotNull) == 11535 Expr::NPCK_ZeroExpression) { 11536 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11537 if (CL->getValue() == 0) 11538 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11539 << NullValue 11540 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11541 NullValue ? "NULL" : "(void *)0"); 11542 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11543 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11544 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11545 if (T == Context.CharTy) 11546 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11547 << NullValue 11548 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11549 NullValue ? "NULL" : "(void *)0"); 11550 } 11551 } 11552 } 11553 11554 // C99 6.5.8, C++ [expr.rel] 11555 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11556 SourceLocation Loc, 11557 BinaryOperatorKind Opc) { 11558 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11559 bool IsThreeWay = Opc == BO_Cmp; 11560 bool IsOrdered = IsRelational || IsThreeWay; 11561 auto IsAnyPointerType = [](ExprResult E) { 11562 QualType Ty = E.get()->getType(); 11563 return Ty->isPointerType() || Ty->isMemberPointerType(); 11564 }; 11565 11566 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11567 // type, array-to-pointer, ..., conversions are performed on both operands to 11568 // bring them to their composite type. 11569 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11570 // any type-related checks. 11571 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11572 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11573 if (LHS.isInvalid()) 11574 return QualType(); 11575 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11576 if (RHS.isInvalid()) 11577 return QualType(); 11578 } else { 11579 LHS = DefaultLvalueConversion(LHS.get()); 11580 if (LHS.isInvalid()) 11581 return QualType(); 11582 RHS = DefaultLvalueConversion(RHS.get()); 11583 if (RHS.isInvalid()) 11584 return QualType(); 11585 } 11586 11587 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11588 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11589 CheckPtrComparisonWithNullChar(LHS, RHS); 11590 CheckPtrComparisonWithNullChar(RHS, LHS); 11591 } 11592 11593 // Handle vector comparisons separately. 11594 if (LHS.get()->getType()->isVectorType() || 11595 RHS.get()->getType()->isVectorType()) 11596 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11597 11598 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11599 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11600 11601 QualType LHSType = LHS.get()->getType(); 11602 QualType RHSType = RHS.get()->getType(); 11603 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11604 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11605 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11606 11607 const Expr::NullPointerConstantKind LHSNullKind = 11608 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11609 const Expr::NullPointerConstantKind RHSNullKind = 11610 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11611 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11612 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11613 11614 auto computeResultTy = [&]() { 11615 if (Opc != BO_Cmp) 11616 return Context.getLogicalOperationType(); 11617 assert(getLangOpts().CPlusPlus); 11618 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11619 11620 QualType CompositeTy = LHS.get()->getType(); 11621 assert(!CompositeTy->isReferenceType()); 11622 11623 Optional<ComparisonCategoryType> CCT = 11624 getComparisonCategoryForBuiltinCmp(CompositeTy); 11625 if (!CCT) 11626 return InvalidOperands(Loc, LHS, RHS); 11627 11628 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11629 // P0946R0: Comparisons between a null pointer constant and an object 11630 // pointer result in std::strong_equality, which is ill-formed under 11631 // P1959R0. 11632 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11633 << (LHSIsNull ? LHS.get()->getSourceRange() 11634 : RHS.get()->getSourceRange()); 11635 return QualType(); 11636 } 11637 11638 return CheckComparisonCategoryType( 11639 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11640 }; 11641 11642 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11643 bool IsEquality = Opc == BO_EQ; 11644 if (RHSIsNull) 11645 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11646 RHS.get()->getSourceRange()); 11647 else 11648 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11649 LHS.get()->getSourceRange()); 11650 } 11651 11652 if ((LHSType->isIntegerType() && !LHSIsNull) || 11653 (RHSType->isIntegerType() && !RHSIsNull)) { 11654 // Skip normal pointer conversion checks in this case; we have better 11655 // diagnostics for this below. 11656 } else if (getLangOpts().CPlusPlus) { 11657 // Equality comparison of a function pointer to a void pointer is invalid, 11658 // but we allow it as an extension. 11659 // FIXME: If we really want to allow this, should it be part of composite 11660 // pointer type computation so it works in conditionals too? 11661 if (!IsOrdered && 11662 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11663 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11664 // This is a gcc extension compatibility comparison. 11665 // In a SFINAE context, we treat this as a hard error to maintain 11666 // conformance with the C++ standard. 11667 diagnoseFunctionPointerToVoidComparison( 11668 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11669 11670 if (isSFINAEContext()) 11671 return QualType(); 11672 11673 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11674 return computeResultTy(); 11675 } 11676 11677 // C++ [expr.eq]p2: 11678 // If at least one operand is a pointer [...] bring them to their 11679 // composite pointer type. 11680 // C++ [expr.spaceship]p6 11681 // If at least one of the operands is of pointer type, [...] bring them 11682 // to their composite pointer type. 11683 // C++ [expr.rel]p2: 11684 // If both operands are pointers, [...] bring them to their composite 11685 // pointer type. 11686 // For <=>, the only valid non-pointer types are arrays and functions, and 11687 // we already decayed those, so this is really the same as the relational 11688 // comparison rule. 11689 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11690 (IsOrdered ? 2 : 1) && 11691 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11692 RHSType->isObjCObjectPointerType()))) { 11693 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11694 return QualType(); 11695 return computeResultTy(); 11696 } 11697 } else if (LHSType->isPointerType() && 11698 RHSType->isPointerType()) { // C99 6.5.8p2 11699 // All of the following pointer-related warnings are GCC extensions, except 11700 // when handling null pointer constants. 11701 QualType LCanPointeeTy = 11702 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11703 QualType RCanPointeeTy = 11704 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11705 11706 // C99 6.5.9p2 and C99 6.5.8p2 11707 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11708 RCanPointeeTy.getUnqualifiedType())) { 11709 if (IsRelational) { 11710 // Pointers both need to point to complete or incomplete types 11711 if ((LCanPointeeTy->isIncompleteType() != 11712 RCanPointeeTy->isIncompleteType()) && 11713 !getLangOpts().C11) { 11714 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11715 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11716 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11717 << RCanPointeeTy->isIncompleteType(); 11718 } 11719 if (LCanPointeeTy->isFunctionType()) { 11720 // Valid unless a relational comparison of function pointers 11721 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11722 << LHSType << RHSType << LHS.get()->getSourceRange() 11723 << RHS.get()->getSourceRange(); 11724 } 11725 } 11726 } else if (!IsRelational && 11727 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11728 // Valid unless comparison between non-null pointer and function pointer 11729 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11730 && !LHSIsNull && !RHSIsNull) 11731 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11732 /*isError*/false); 11733 } else { 11734 // Invalid 11735 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11736 } 11737 if (LCanPointeeTy != RCanPointeeTy) { 11738 // Treat NULL constant as a special case in OpenCL. 11739 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11740 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11741 Diag(Loc, 11742 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11743 << LHSType << RHSType << 0 /* comparison */ 11744 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11745 } 11746 } 11747 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11748 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11749 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11750 : CK_BitCast; 11751 if (LHSIsNull && !RHSIsNull) 11752 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11753 else 11754 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11755 } 11756 return computeResultTy(); 11757 } 11758 11759 if (getLangOpts().CPlusPlus) { 11760 // C++ [expr.eq]p4: 11761 // Two operands of type std::nullptr_t or one operand of type 11762 // std::nullptr_t and the other a null pointer constant compare equal. 11763 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11764 if (LHSType->isNullPtrType()) { 11765 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11766 return computeResultTy(); 11767 } 11768 if (RHSType->isNullPtrType()) { 11769 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11770 return computeResultTy(); 11771 } 11772 } 11773 11774 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11775 // These aren't covered by the composite pointer type rules. 11776 if (!IsOrdered && RHSType->isNullPtrType() && 11777 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11778 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11779 return computeResultTy(); 11780 } 11781 if (!IsOrdered && LHSType->isNullPtrType() && 11782 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11783 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11784 return computeResultTy(); 11785 } 11786 11787 if (IsRelational && 11788 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11789 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11790 // HACK: Relational comparison of nullptr_t against a pointer type is 11791 // invalid per DR583, but we allow it within std::less<> and friends, 11792 // since otherwise common uses of it break. 11793 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11794 // friends to have std::nullptr_t overload candidates. 11795 DeclContext *DC = CurContext; 11796 if (isa<FunctionDecl>(DC)) 11797 DC = DC->getParent(); 11798 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11799 if (CTSD->isInStdNamespace() && 11800 llvm::StringSwitch<bool>(CTSD->getName()) 11801 .Cases("less", "less_equal", "greater", "greater_equal", true) 11802 .Default(false)) { 11803 if (RHSType->isNullPtrType()) 11804 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11805 else 11806 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11807 return computeResultTy(); 11808 } 11809 } 11810 } 11811 11812 // C++ [expr.eq]p2: 11813 // If at least one operand is a pointer to member, [...] bring them to 11814 // their composite pointer type. 11815 if (!IsOrdered && 11816 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11817 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11818 return QualType(); 11819 else 11820 return computeResultTy(); 11821 } 11822 } 11823 11824 // Handle block pointer types. 11825 if (!IsOrdered && LHSType->isBlockPointerType() && 11826 RHSType->isBlockPointerType()) { 11827 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11828 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11829 11830 if (!LHSIsNull && !RHSIsNull && 11831 !Context.typesAreCompatible(lpointee, rpointee)) { 11832 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11833 << LHSType << RHSType << LHS.get()->getSourceRange() 11834 << RHS.get()->getSourceRange(); 11835 } 11836 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11837 return computeResultTy(); 11838 } 11839 11840 // Allow block pointers to be compared with null pointer constants. 11841 if (!IsOrdered 11842 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11843 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11844 if (!LHSIsNull && !RHSIsNull) { 11845 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11846 ->getPointeeType()->isVoidType()) 11847 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11848 ->getPointeeType()->isVoidType()))) 11849 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11850 << LHSType << RHSType << LHS.get()->getSourceRange() 11851 << RHS.get()->getSourceRange(); 11852 } 11853 if (LHSIsNull && !RHSIsNull) 11854 LHS = ImpCastExprToType(LHS.get(), RHSType, 11855 RHSType->isPointerType() ? CK_BitCast 11856 : CK_AnyPointerToBlockPointerCast); 11857 else 11858 RHS = ImpCastExprToType(RHS.get(), LHSType, 11859 LHSType->isPointerType() ? CK_BitCast 11860 : CK_AnyPointerToBlockPointerCast); 11861 return computeResultTy(); 11862 } 11863 11864 if (LHSType->isObjCObjectPointerType() || 11865 RHSType->isObjCObjectPointerType()) { 11866 const PointerType *LPT = LHSType->getAs<PointerType>(); 11867 const PointerType *RPT = RHSType->getAs<PointerType>(); 11868 if (LPT || RPT) { 11869 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11870 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11871 11872 if (!LPtrToVoid && !RPtrToVoid && 11873 !Context.typesAreCompatible(LHSType, RHSType)) { 11874 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11875 /*isError*/false); 11876 } 11877 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11878 // the RHS, but we have test coverage for this behavior. 11879 // FIXME: Consider using convertPointersToCompositeType in C++. 11880 if (LHSIsNull && !RHSIsNull) { 11881 Expr *E = LHS.get(); 11882 if (getLangOpts().ObjCAutoRefCount) 11883 CheckObjCConversion(SourceRange(), RHSType, E, 11884 CCK_ImplicitConversion); 11885 LHS = ImpCastExprToType(E, RHSType, 11886 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11887 } 11888 else { 11889 Expr *E = RHS.get(); 11890 if (getLangOpts().ObjCAutoRefCount) 11891 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11892 /*Diagnose=*/true, 11893 /*DiagnoseCFAudited=*/false, Opc); 11894 RHS = ImpCastExprToType(E, LHSType, 11895 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11896 } 11897 return computeResultTy(); 11898 } 11899 if (LHSType->isObjCObjectPointerType() && 11900 RHSType->isObjCObjectPointerType()) { 11901 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11902 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11903 /*isError*/false); 11904 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11905 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11906 11907 if (LHSIsNull && !RHSIsNull) 11908 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11909 else 11910 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11911 return computeResultTy(); 11912 } 11913 11914 if (!IsOrdered && LHSType->isBlockPointerType() && 11915 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11916 LHS = ImpCastExprToType(LHS.get(), RHSType, 11917 CK_BlockPointerToObjCPointerCast); 11918 return computeResultTy(); 11919 } else if (!IsOrdered && 11920 LHSType->isBlockCompatibleObjCPointerType(Context) && 11921 RHSType->isBlockPointerType()) { 11922 RHS = ImpCastExprToType(RHS.get(), LHSType, 11923 CK_BlockPointerToObjCPointerCast); 11924 return computeResultTy(); 11925 } 11926 } 11927 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11928 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11929 unsigned DiagID = 0; 11930 bool isError = false; 11931 if (LangOpts.DebuggerSupport) { 11932 // Under a debugger, allow the comparison of pointers to integers, 11933 // since users tend to want to compare addresses. 11934 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11935 (RHSIsNull && RHSType->isIntegerType())) { 11936 if (IsOrdered) { 11937 isError = getLangOpts().CPlusPlus; 11938 DiagID = 11939 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11940 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11941 } 11942 } else if (getLangOpts().CPlusPlus) { 11943 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11944 isError = true; 11945 } else if (IsOrdered) 11946 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11947 else 11948 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11949 11950 if (DiagID) { 11951 Diag(Loc, DiagID) 11952 << LHSType << RHSType << LHS.get()->getSourceRange() 11953 << RHS.get()->getSourceRange(); 11954 if (isError) 11955 return QualType(); 11956 } 11957 11958 if (LHSType->isIntegerType()) 11959 LHS = ImpCastExprToType(LHS.get(), RHSType, 11960 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11961 else 11962 RHS = ImpCastExprToType(RHS.get(), LHSType, 11963 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11964 return computeResultTy(); 11965 } 11966 11967 // Handle block pointers. 11968 if (!IsOrdered && RHSIsNull 11969 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11970 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11971 return computeResultTy(); 11972 } 11973 if (!IsOrdered && LHSIsNull 11974 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11975 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11976 return computeResultTy(); 11977 } 11978 11979 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11980 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11981 return computeResultTy(); 11982 } 11983 11984 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11985 return computeResultTy(); 11986 } 11987 11988 if (LHSIsNull && RHSType->isQueueT()) { 11989 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11990 return computeResultTy(); 11991 } 11992 11993 if (LHSType->isQueueT() && RHSIsNull) { 11994 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11995 return computeResultTy(); 11996 } 11997 } 11998 11999 return InvalidOperands(Loc, LHS, RHS); 12000 } 12001 12002 // Return a signed ext_vector_type that is of identical size and number of 12003 // elements. For floating point vectors, return an integer type of identical 12004 // size and number of elements. In the non ext_vector_type case, search from 12005 // the largest type to the smallest type to avoid cases where long long == long, 12006 // where long gets picked over long long. 12007 QualType Sema::GetSignedVectorType(QualType V) { 12008 const VectorType *VTy = V->castAs<VectorType>(); 12009 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12010 12011 if (isa<ExtVectorType>(VTy)) { 12012 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12013 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12014 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12015 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12016 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12017 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12018 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12019 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12020 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12021 "Unhandled vector element size in vector compare"); 12022 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12023 } 12024 12025 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12026 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12027 VectorType::GenericVector); 12028 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12029 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12030 VectorType::GenericVector); 12031 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12032 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12033 VectorType::GenericVector); 12034 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12035 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12036 VectorType::GenericVector); 12037 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12038 "Unhandled vector element size in vector compare"); 12039 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12040 VectorType::GenericVector); 12041 } 12042 12043 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12044 /// operates on extended vector types. Instead of producing an IntTy result, 12045 /// like a scalar comparison, a vector comparison produces a vector of integer 12046 /// types. 12047 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12048 SourceLocation Loc, 12049 BinaryOperatorKind Opc) { 12050 if (Opc == BO_Cmp) { 12051 Diag(Loc, diag::err_three_way_vector_comparison); 12052 return QualType(); 12053 } 12054 12055 // Check to make sure we're operating on vectors of the same type and width, 12056 // Allowing one side to be a scalar of element type. 12057 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12058 /*AllowBothBool*/true, 12059 /*AllowBoolConversions*/getLangOpts().ZVector); 12060 if (vType.isNull()) 12061 return vType; 12062 12063 QualType LHSType = LHS.get()->getType(); 12064 12065 // If AltiVec, the comparison results in a numeric type, i.e. 12066 // bool for C++, int for C 12067 if (getLangOpts().AltiVec && 12068 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12069 return Context.getLogicalOperationType(); 12070 12071 // For non-floating point types, check for self-comparisons of the form 12072 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12073 // often indicate logic errors in the program. 12074 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12075 12076 // Check for comparisons of floating point operands using != and ==. 12077 if (BinaryOperator::isEqualityOp(Opc) && 12078 LHSType->hasFloatingRepresentation()) { 12079 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12080 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12081 } 12082 12083 // Return a signed type for the vector. 12084 return GetSignedVectorType(vType); 12085 } 12086 12087 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12088 const ExprResult &XorRHS, 12089 const SourceLocation Loc) { 12090 // Do not diagnose macros. 12091 if (Loc.isMacroID()) 12092 return; 12093 12094 bool Negative = false; 12095 bool ExplicitPlus = false; 12096 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12097 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12098 12099 if (!LHSInt) 12100 return; 12101 if (!RHSInt) { 12102 // Check negative literals. 12103 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12104 UnaryOperatorKind Opc = UO->getOpcode(); 12105 if (Opc != UO_Minus && Opc != UO_Plus) 12106 return; 12107 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12108 if (!RHSInt) 12109 return; 12110 Negative = (Opc == UO_Minus); 12111 ExplicitPlus = !Negative; 12112 } else { 12113 return; 12114 } 12115 } 12116 12117 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12118 llvm::APInt RightSideValue = RHSInt->getValue(); 12119 if (LeftSideValue != 2 && LeftSideValue != 10) 12120 return; 12121 12122 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12123 return; 12124 12125 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12126 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12127 llvm::StringRef ExprStr = 12128 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12129 12130 CharSourceRange XorRange = 12131 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12132 llvm::StringRef XorStr = 12133 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12134 // Do not diagnose if xor keyword/macro is used. 12135 if (XorStr == "xor") 12136 return; 12137 12138 std::string LHSStr = std::string(Lexer::getSourceText( 12139 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12140 S.getSourceManager(), S.getLangOpts())); 12141 std::string RHSStr = std::string(Lexer::getSourceText( 12142 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12143 S.getSourceManager(), S.getLangOpts())); 12144 12145 if (Negative) { 12146 RightSideValue = -RightSideValue; 12147 RHSStr = "-" + RHSStr; 12148 } else if (ExplicitPlus) { 12149 RHSStr = "+" + RHSStr; 12150 } 12151 12152 StringRef LHSStrRef = LHSStr; 12153 StringRef RHSStrRef = RHSStr; 12154 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12155 // literals. 12156 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12157 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12158 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12159 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12160 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12161 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12162 LHSStrRef.find('\'') != StringRef::npos || 12163 RHSStrRef.find('\'') != StringRef::npos) 12164 return; 12165 12166 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12167 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12168 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12169 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12170 std::string SuggestedExpr = "1 << " + RHSStr; 12171 bool Overflow = false; 12172 llvm::APInt One = (LeftSideValue - 1); 12173 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12174 if (Overflow) { 12175 if (RightSideIntValue < 64) 12176 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12177 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12178 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12179 else if (RightSideIntValue == 64) 12180 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12181 else 12182 return; 12183 } else { 12184 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12185 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12186 << PowValue.toString(10, true) 12187 << FixItHint::CreateReplacement( 12188 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12189 } 12190 12191 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12192 } else if (LeftSideValue == 10) { 12193 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12194 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12195 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12196 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12197 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12198 } 12199 } 12200 12201 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12202 SourceLocation Loc) { 12203 // Ensure that either both operands are of the same vector type, or 12204 // one operand is of a vector type and the other is of its element type. 12205 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12206 /*AllowBothBool*/true, 12207 /*AllowBoolConversions*/false); 12208 if (vType.isNull()) 12209 return InvalidOperands(Loc, LHS, RHS); 12210 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12211 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12212 return InvalidOperands(Loc, LHS, RHS); 12213 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12214 // usage of the logical operators && and || with vectors in C. This 12215 // check could be notionally dropped. 12216 if (!getLangOpts().CPlusPlus && 12217 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12218 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12219 12220 return GetSignedVectorType(LHS.get()->getType()); 12221 } 12222 12223 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12224 SourceLocation Loc, 12225 bool IsCompAssign) { 12226 if (!IsCompAssign) { 12227 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12228 if (LHS.isInvalid()) 12229 return QualType(); 12230 } 12231 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12232 if (RHS.isInvalid()) 12233 return QualType(); 12234 12235 // For conversion purposes, we ignore any qualifiers. 12236 // For example, "const float" and "float" are equivalent. 12237 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12238 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12239 12240 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12241 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12242 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12243 12244 if (Context.hasSameType(LHSType, RHSType)) 12245 return LHSType; 12246 12247 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12248 // case we have to return InvalidOperands. 12249 ExprResult OriginalLHS = LHS; 12250 ExprResult OriginalRHS = RHS; 12251 if (LHSMatType && !RHSMatType) { 12252 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12253 if (!RHS.isInvalid()) 12254 return LHSType; 12255 12256 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12257 } 12258 12259 if (!LHSMatType && RHSMatType) { 12260 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12261 if (!LHS.isInvalid()) 12262 return RHSType; 12263 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12264 } 12265 12266 return InvalidOperands(Loc, LHS, RHS); 12267 } 12268 12269 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12270 SourceLocation Loc, 12271 bool IsCompAssign) { 12272 if (!IsCompAssign) { 12273 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12274 if (LHS.isInvalid()) 12275 return QualType(); 12276 } 12277 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12278 if (RHS.isInvalid()) 12279 return QualType(); 12280 12281 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12282 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12283 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12284 12285 if (LHSMatType && RHSMatType) { 12286 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12287 return InvalidOperands(Loc, LHS, RHS); 12288 12289 if (!Context.hasSameType(LHSMatType->getElementType(), 12290 RHSMatType->getElementType())) 12291 return InvalidOperands(Loc, LHS, RHS); 12292 12293 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12294 LHSMatType->getNumRows(), 12295 RHSMatType->getNumColumns()); 12296 } 12297 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12298 } 12299 12300 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12301 SourceLocation Loc, 12302 BinaryOperatorKind Opc) { 12303 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12304 12305 bool IsCompAssign = 12306 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12307 12308 if (LHS.get()->getType()->isVectorType() || 12309 RHS.get()->getType()->isVectorType()) { 12310 if (LHS.get()->getType()->hasIntegerRepresentation() && 12311 RHS.get()->getType()->hasIntegerRepresentation()) 12312 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12313 /*AllowBothBool*/true, 12314 /*AllowBoolConversions*/getLangOpts().ZVector); 12315 return InvalidOperands(Loc, LHS, RHS); 12316 } 12317 12318 if (Opc == BO_And) 12319 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12320 12321 if (LHS.get()->getType()->hasFloatingRepresentation() || 12322 RHS.get()->getType()->hasFloatingRepresentation()) 12323 return InvalidOperands(Loc, LHS, RHS); 12324 12325 ExprResult LHSResult = LHS, RHSResult = RHS; 12326 QualType compType = UsualArithmeticConversions( 12327 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12328 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12329 return QualType(); 12330 LHS = LHSResult.get(); 12331 RHS = RHSResult.get(); 12332 12333 if (Opc == BO_Xor) 12334 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12335 12336 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12337 return compType; 12338 return InvalidOperands(Loc, LHS, RHS); 12339 } 12340 12341 // C99 6.5.[13,14] 12342 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12343 SourceLocation Loc, 12344 BinaryOperatorKind Opc) { 12345 // Check vector operands differently. 12346 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12347 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12348 12349 bool EnumConstantInBoolContext = false; 12350 for (const ExprResult &HS : {LHS, RHS}) { 12351 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12352 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12353 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12354 EnumConstantInBoolContext = true; 12355 } 12356 } 12357 12358 if (EnumConstantInBoolContext) 12359 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12360 12361 // Diagnose cases where the user write a logical and/or but probably meant a 12362 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12363 // is a constant. 12364 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12365 !LHS.get()->getType()->isBooleanType() && 12366 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12367 // Don't warn in macros or template instantiations. 12368 !Loc.isMacroID() && !inTemplateInstantiation()) { 12369 // If the RHS can be constant folded, and if it constant folds to something 12370 // that isn't 0 or 1 (which indicate a potential logical operation that 12371 // happened to fold to true/false) then warn. 12372 // Parens on the RHS are ignored. 12373 Expr::EvalResult EVResult; 12374 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12375 llvm::APSInt Result = EVResult.Val.getInt(); 12376 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12377 !RHS.get()->getExprLoc().isMacroID()) || 12378 (Result != 0 && Result != 1)) { 12379 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12380 << RHS.get()->getSourceRange() 12381 << (Opc == BO_LAnd ? "&&" : "||"); 12382 // Suggest replacing the logical operator with the bitwise version 12383 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12384 << (Opc == BO_LAnd ? "&" : "|") 12385 << FixItHint::CreateReplacement(SourceRange( 12386 Loc, getLocForEndOfToken(Loc)), 12387 Opc == BO_LAnd ? "&" : "|"); 12388 if (Opc == BO_LAnd) 12389 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12390 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12391 << FixItHint::CreateRemoval( 12392 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12393 RHS.get()->getEndLoc())); 12394 } 12395 } 12396 } 12397 12398 if (!Context.getLangOpts().CPlusPlus) { 12399 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12400 // not operate on the built-in scalar and vector float types. 12401 if (Context.getLangOpts().OpenCL && 12402 Context.getLangOpts().OpenCLVersion < 120) { 12403 if (LHS.get()->getType()->isFloatingType() || 12404 RHS.get()->getType()->isFloatingType()) 12405 return InvalidOperands(Loc, LHS, RHS); 12406 } 12407 12408 LHS = UsualUnaryConversions(LHS.get()); 12409 if (LHS.isInvalid()) 12410 return QualType(); 12411 12412 RHS = UsualUnaryConversions(RHS.get()); 12413 if (RHS.isInvalid()) 12414 return QualType(); 12415 12416 if (!LHS.get()->getType()->isScalarType() || 12417 !RHS.get()->getType()->isScalarType()) 12418 return InvalidOperands(Loc, LHS, RHS); 12419 12420 return Context.IntTy; 12421 } 12422 12423 // The following is safe because we only use this method for 12424 // non-overloadable operands. 12425 12426 // C++ [expr.log.and]p1 12427 // C++ [expr.log.or]p1 12428 // The operands are both contextually converted to type bool. 12429 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12430 if (LHSRes.isInvalid()) 12431 return InvalidOperands(Loc, LHS, RHS); 12432 LHS = LHSRes; 12433 12434 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12435 if (RHSRes.isInvalid()) 12436 return InvalidOperands(Loc, LHS, RHS); 12437 RHS = RHSRes; 12438 12439 // C++ [expr.log.and]p2 12440 // C++ [expr.log.or]p2 12441 // The result is a bool. 12442 return Context.BoolTy; 12443 } 12444 12445 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12446 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12447 if (!ME) return false; 12448 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12449 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12450 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12451 if (!Base) return false; 12452 return Base->getMethodDecl() != nullptr; 12453 } 12454 12455 /// Is the given expression (which must be 'const') a reference to a 12456 /// variable which was originally non-const, but which has become 12457 /// 'const' due to being captured within a block? 12458 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12459 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12460 assert(E->isLValue() && E->getType().isConstQualified()); 12461 E = E->IgnoreParens(); 12462 12463 // Must be a reference to a declaration from an enclosing scope. 12464 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12465 if (!DRE) return NCCK_None; 12466 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12467 12468 // The declaration must be a variable which is not declared 'const'. 12469 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12470 if (!var) return NCCK_None; 12471 if (var->getType().isConstQualified()) return NCCK_None; 12472 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12473 12474 // Decide whether the first capture was for a block or a lambda. 12475 DeclContext *DC = S.CurContext, *Prev = nullptr; 12476 // Decide whether the first capture was for a block or a lambda. 12477 while (DC) { 12478 // For init-capture, it is possible that the variable belongs to the 12479 // template pattern of the current context. 12480 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12481 if (var->isInitCapture() && 12482 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12483 break; 12484 if (DC == var->getDeclContext()) 12485 break; 12486 Prev = DC; 12487 DC = DC->getParent(); 12488 } 12489 // Unless we have an init-capture, we've gone one step too far. 12490 if (!var->isInitCapture()) 12491 DC = Prev; 12492 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12493 } 12494 12495 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12496 Ty = Ty.getNonReferenceType(); 12497 if (IsDereference && Ty->isPointerType()) 12498 Ty = Ty->getPointeeType(); 12499 return !Ty.isConstQualified(); 12500 } 12501 12502 // Update err_typecheck_assign_const and note_typecheck_assign_const 12503 // when this enum is changed. 12504 enum { 12505 ConstFunction, 12506 ConstVariable, 12507 ConstMember, 12508 ConstMethod, 12509 NestedConstMember, 12510 ConstUnknown, // Keep as last element 12511 }; 12512 12513 /// Emit the "read-only variable not assignable" error and print notes to give 12514 /// more information about why the variable is not assignable, such as pointing 12515 /// to the declaration of a const variable, showing that a method is const, or 12516 /// that the function is returning a const reference. 12517 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12518 SourceLocation Loc) { 12519 SourceRange ExprRange = E->getSourceRange(); 12520 12521 // Only emit one error on the first const found. All other consts will emit 12522 // a note to the error. 12523 bool DiagnosticEmitted = false; 12524 12525 // Track if the current expression is the result of a dereference, and if the 12526 // next checked expression is the result of a dereference. 12527 bool IsDereference = false; 12528 bool NextIsDereference = false; 12529 12530 // Loop to process MemberExpr chains. 12531 while (true) { 12532 IsDereference = NextIsDereference; 12533 12534 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12535 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12536 NextIsDereference = ME->isArrow(); 12537 const ValueDecl *VD = ME->getMemberDecl(); 12538 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12539 // Mutable fields can be modified even if the class is const. 12540 if (Field->isMutable()) { 12541 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12542 break; 12543 } 12544 12545 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12546 if (!DiagnosticEmitted) { 12547 S.Diag(Loc, diag::err_typecheck_assign_const) 12548 << ExprRange << ConstMember << false /*static*/ << Field 12549 << Field->getType(); 12550 DiagnosticEmitted = true; 12551 } 12552 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12553 << ConstMember << false /*static*/ << Field << Field->getType() 12554 << Field->getSourceRange(); 12555 } 12556 E = ME->getBase(); 12557 continue; 12558 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12559 if (VDecl->getType().isConstQualified()) { 12560 if (!DiagnosticEmitted) { 12561 S.Diag(Loc, diag::err_typecheck_assign_const) 12562 << ExprRange << ConstMember << true /*static*/ << VDecl 12563 << VDecl->getType(); 12564 DiagnosticEmitted = true; 12565 } 12566 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12567 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12568 << VDecl->getSourceRange(); 12569 } 12570 // Static fields do not inherit constness from parents. 12571 break; 12572 } 12573 break; // End MemberExpr 12574 } else if (const ArraySubscriptExpr *ASE = 12575 dyn_cast<ArraySubscriptExpr>(E)) { 12576 E = ASE->getBase()->IgnoreParenImpCasts(); 12577 continue; 12578 } else if (const ExtVectorElementExpr *EVE = 12579 dyn_cast<ExtVectorElementExpr>(E)) { 12580 E = EVE->getBase()->IgnoreParenImpCasts(); 12581 continue; 12582 } 12583 break; 12584 } 12585 12586 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12587 // Function calls 12588 const FunctionDecl *FD = CE->getDirectCallee(); 12589 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12590 if (!DiagnosticEmitted) { 12591 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12592 << ConstFunction << FD; 12593 DiagnosticEmitted = true; 12594 } 12595 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12596 diag::note_typecheck_assign_const) 12597 << ConstFunction << FD << FD->getReturnType() 12598 << FD->getReturnTypeSourceRange(); 12599 } 12600 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12601 // Point to variable declaration. 12602 if (const ValueDecl *VD = DRE->getDecl()) { 12603 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12604 if (!DiagnosticEmitted) { 12605 S.Diag(Loc, diag::err_typecheck_assign_const) 12606 << ExprRange << ConstVariable << VD << VD->getType(); 12607 DiagnosticEmitted = true; 12608 } 12609 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12610 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12611 } 12612 } 12613 } else if (isa<CXXThisExpr>(E)) { 12614 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12615 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12616 if (MD->isConst()) { 12617 if (!DiagnosticEmitted) { 12618 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12619 << ConstMethod << MD; 12620 DiagnosticEmitted = true; 12621 } 12622 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12623 << ConstMethod << MD << MD->getSourceRange(); 12624 } 12625 } 12626 } 12627 } 12628 12629 if (DiagnosticEmitted) 12630 return; 12631 12632 // Can't determine a more specific message, so display the generic error. 12633 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12634 } 12635 12636 enum OriginalExprKind { 12637 OEK_Variable, 12638 OEK_Member, 12639 OEK_LValue 12640 }; 12641 12642 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12643 const RecordType *Ty, 12644 SourceLocation Loc, SourceRange Range, 12645 OriginalExprKind OEK, 12646 bool &DiagnosticEmitted) { 12647 std::vector<const RecordType *> RecordTypeList; 12648 RecordTypeList.push_back(Ty); 12649 unsigned NextToCheckIndex = 0; 12650 // We walk the record hierarchy breadth-first to ensure that we print 12651 // diagnostics in field nesting order. 12652 while (RecordTypeList.size() > NextToCheckIndex) { 12653 bool IsNested = NextToCheckIndex > 0; 12654 for (const FieldDecl *Field : 12655 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12656 // First, check every field for constness. 12657 QualType FieldTy = Field->getType(); 12658 if (FieldTy.isConstQualified()) { 12659 if (!DiagnosticEmitted) { 12660 S.Diag(Loc, diag::err_typecheck_assign_const) 12661 << Range << NestedConstMember << OEK << VD 12662 << IsNested << Field; 12663 DiagnosticEmitted = true; 12664 } 12665 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12666 << NestedConstMember << IsNested << Field 12667 << FieldTy << Field->getSourceRange(); 12668 } 12669 12670 // Then we append it to the list to check next in order. 12671 FieldTy = FieldTy.getCanonicalType(); 12672 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12673 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12674 RecordTypeList.push_back(FieldRecTy); 12675 } 12676 } 12677 ++NextToCheckIndex; 12678 } 12679 } 12680 12681 /// Emit an error for the case where a record we are trying to assign to has a 12682 /// const-qualified field somewhere in its hierarchy. 12683 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12684 SourceLocation Loc) { 12685 QualType Ty = E->getType(); 12686 assert(Ty->isRecordType() && "lvalue was not record?"); 12687 SourceRange Range = E->getSourceRange(); 12688 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12689 bool DiagEmitted = false; 12690 12691 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12692 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12693 Range, OEK_Member, DiagEmitted); 12694 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12695 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12696 Range, OEK_Variable, DiagEmitted); 12697 else 12698 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12699 Range, OEK_LValue, DiagEmitted); 12700 if (!DiagEmitted) 12701 DiagnoseConstAssignment(S, E, Loc); 12702 } 12703 12704 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12705 /// emit an error and return true. If so, return false. 12706 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12707 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12708 12709 S.CheckShadowingDeclModification(E, Loc); 12710 12711 SourceLocation OrigLoc = Loc; 12712 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12713 &Loc); 12714 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12715 IsLV = Expr::MLV_InvalidMessageExpression; 12716 if (IsLV == Expr::MLV_Valid) 12717 return false; 12718 12719 unsigned DiagID = 0; 12720 bool NeedType = false; 12721 switch (IsLV) { // C99 6.5.16p2 12722 case Expr::MLV_ConstQualified: 12723 // Use a specialized diagnostic when we're assigning to an object 12724 // from an enclosing function or block. 12725 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12726 if (NCCK == NCCK_Block) 12727 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12728 else 12729 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12730 break; 12731 } 12732 12733 // In ARC, use some specialized diagnostics for occasions where we 12734 // infer 'const'. These are always pseudo-strong variables. 12735 if (S.getLangOpts().ObjCAutoRefCount) { 12736 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12737 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12738 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12739 12740 // Use the normal diagnostic if it's pseudo-__strong but the 12741 // user actually wrote 'const'. 12742 if (var->isARCPseudoStrong() && 12743 (!var->getTypeSourceInfo() || 12744 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12745 // There are three pseudo-strong cases: 12746 // - self 12747 ObjCMethodDecl *method = S.getCurMethodDecl(); 12748 if (method && var == method->getSelfDecl()) { 12749 DiagID = method->isClassMethod() 12750 ? diag::err_typecheck_arc_assign_self_class_method 12751 : diag::err_typecheck_arc_assign_self; 12752 12753 // - Objective-C externally_retained attribute. 12754 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12755 isa<ParmVarDecl>(var)) { 12756 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12757 12758 // - fast enumeration variables 12759 } else { 12760 DiagID = diag::err_typecheck_arr_assign_enumeration; 12761 } 12762 12763 SourceRange Assign; 12764 if (Loc != OrigLoc) 12765 Assign = SourceRange(OrigLoc, OrigLoc); 12766 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12767 // We need to preserve the AST regardless, so migration tool 12768 // can do its job. 12769 return false; 12770 } 12771 } 12772 } 12773 12774 // If none of the special cases above are triggered, then this is a 12775 // simple const assignment. 12776 if (DiagID == 0) { 12777 DiagnoseConstAssignment(S, E, Loc); 12778 return true; 12779 } 12780 12781 break; 12782 case Expr::MLV_ConstAddrSpace: 12783 DiagnoseConstAssignment(S, E, Loc); 12784 return true; 12785 case Expr::MLV_ConstQualifiedField: 12786 DiagnoseRecursiveConstFields(S, E, Loc); 12787 return true; 12788 case Expr::MLV_ArrayType: 12789 case Expr::MLV_ArrayTemporary: 12790 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12791 NeedType = true; 12792 break; 12793 case Expr::MLV_NotObjectType: 12794 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12795 NeedType = true; 12796 break; 12797 case Expr::MLV_LValueCast: 12798 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12799 break; 12800 case Expr::MLV_Valid: 12801 llvm_unreachable("did not take early return for MLV_Valid"); 12802 case Expr::MLV_InvalidExpression: 12803 case Expr::MLV_MemberFunction: 12804 case Expr::MLV_ClassTemporary: 12805 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12806 break; 12807 case Expr::MLV_IncompleteType: 12808 case Expr::MLV_IncompleteVoidType: 12809 return S.RequireCompleteType(Loc, E->getType(), 12810 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12811 case Expr::MLV_DuplicateVectorComponents: 12812 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12813 break; 12814 case Expr::MLV_NoSetterProperty: 12815 llvm_unreachable("readonly properties should be processed differently"); 12816 case Expr::MLV_InvalidMessageExpression: 12817 DiagID = diag::err_readonly_message_assignment; 12818 break; 12819 case Expr::MLV_SubObjCPropertySetting: 12820 DiagID = diag::err_no_subobject_property_setting; 12821 break; 12822 } 12823 12824 SourceRange Assign; 12825 if (Loc != OrigLoc) 12826 Assign = SourceRange(OrigLoc, OrigLoc); 12827 if (NeedType) 12828 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12829 else 12830 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12831 return true; 12832 } 12833 12834 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12835 SourceLocation Loc, 12836 Sema &Sema) { 12837 if (Sema.inTemplateInstantiation()) 12838 return; 12839 if (Sema.isUnevaluatedContext()) 12840 return; 12841 if (Loc.isInvalid() || Loc.isMacroID()) 12842 return; 12843 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12844 return; 12845 12846 // C / C++ fields 12847 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12848 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12849 if (ML && MR) { 12850 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12851 return; 12852 const ValueDecl *LHSDecl = 12853 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12854 const ValueDecl *RHSDecl = 12855 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12856 if (LHSDecl != RHSDecl) 12857 return; 12858 if (LHSDecl->getType().isVolatileQualified()) 12859 return; 12860 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12861 if (RefTy->getPointeeType().isVolatileQualified()) 12862 return; 12863 12864 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12865 } 12866 12867 // Objective-C instance variables 12868 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12869 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12870 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12871 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12872 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12873 if (RL && RR && RL->getDecl() == RR->getDecl()) 12874 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12875 } 12876 } 12877 12878 // C99 6.5.16.1 12879 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12880 SourceLocation Loc, 12881 QualType CompoundType) { 12882 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12883 12884 // Verify that LHS is a modifiable lvalue, and emit error if not. 12885 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12886 return QualType(); 12887 12888 QualType LHSType = LHSExpr->getType(); 12889 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12890 CompoundType; 12891 // OpenCL v1.2 s6.1.1.1 p2: 12892 // The half data type can only be used to declare a pointer to a buffer that 12893 // contains half values 12894 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12895 LHSType->isHalfType()) { 12896 Diag(Loc, diag::err_opencl_half_load_store) << 1 12897 << LHSType.getUnqualifiedType(); 12898 return QualType(); 12899 } 12900 12901 AssignConvertType ConvTy; 12902 if (CompoundType.isNull()) { 12903 Expr *RHSCheck = RHS.get(); 12904 12905 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12906 12907 QualType LHSTy(LHSType); 12908 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12909 if (RHS.isInvalid()) 12910 return QualType(); 12911 // Special case of NSObject attributes on c-style pointer types. 12912 if (ConvTy == IncompatiblePointer && 12913 ((Context.isObjCNSObjectType(LHSType) && 12914 RHSType->isObjCObjectPointerType()) || 12915 (Context.isObjCNSObjectType(RHSType) && 12916 LHSType->isObjCObjectPointerType()))) 12917 ConvTy = Compatible; 12918 12919 if (ConvTy == Compatible && 12920 LHSType->isObjCObjectType()) 12921 Diag(Loc, diag::err_objc_object_assignment) 12922 << LHSType; 12923 12924 // If the RHS is a unary plus or minus, check to see if they = and + are 12925 // right next to each other. If so, the user may have typo'd "x =+ 4" 12926 // instead of "x += 4". 12927 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12928 RHSCheck = ICE->getSubExpr(); 12929 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12930 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12931 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12932 // Only if the two operators are exactly adjacent. 12933 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12934 // And there is a space or other character before the subexpr of the 12935 // unary +/-. We don't want to warn on "x=-1". 12936 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12937 UO->getSubExpr()->getBeginLoc().isFileID()) { 12938 Diag(Loc, diag::warn_not_compound_assign) 12939 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12940 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12941 } 12942 } 12943 12944 if (ConvTy == Compatible) { 12945 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12946 // Warn about retain cycles where a block captures the LHS, but 12947 // not if the LHS is a simple variable into which the block is 12948 // being stored...unless that variable can be captured by reference! 12949 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12950 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12951 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12952 checkRetainCycles(LHSExpr, RHS.get()); 12953 } 12954 12955 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12956 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12957 // It is safe to assign a weak reference into a strong variable. 12958 // Although this code can still have problems: 12959 // id x = self.weakProp; 12960 // id y = self.weakProp; 12961 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12962 // paths through the function. This should be revisited if 12963 // -Wrepeated-use-of-weak is made flow-sensitive. 12964 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12965 // variable, which will be valid for the current autorelease scope. 12966 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12967 RHS.get()->getBeginLoc())) 12968 getCurFunction()->markSafeWeakUse(RHS.get()); 12969 12970 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12971 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12972 } 12973 } 12974 } else { 12975 // Compound assignment "x += y" 12976 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12977 } 12978 12979 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12980 RHS.get(), AA_Assigning)) 12981 return QualType(); 12982 12983 CheckForNullPointerDereference(*this, LHSExpr); 12984 12985 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 12986 if (CompoundType.isNull()) { 12987 // C++2a [expr.ass]p5: 12988 // A simple-assignment whose left operand is of a volatile-qualified 12989 // type is deprecated unless the assignment is either a discarded-value 12990 // expression or an unevaluated operand 12991 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12992 } else { 12993 // C++2a [expr.ass]p6: 12994 // [Compound-assignment] expressions are deprecated if E1 has 12995 // volatile-qualified type 12996 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12997 } 12998 } 12999 13000 // C99 6.5.16p3: The type of an assignment expression is the type of the 13001 // left operand unless the left operand has qualified type, in which case 13002 // it is the unqualified version of the type of the left operand. 13003 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13004 // is converted to the type of the assignment expression (above). 13005 // C++ 5.17p1: the type of the assignment expression is that of its left 13006 // operand. 13007 return (getLangOpts().CPlusPlus 13008 ? LHSType : LHSType.getUnqualifiedType()); 13009 } 13010 13011 // Only ignore explicit casts to void. 13012 static bool IgnoreCommaOperand(const Expr *E) { 13013 E = E->IgnoreParens(); 13014 13015 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13016 if (CE->getCastKind() == CK_ToVoid) { 13017 return true; 13018 } 13019 13020 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13021 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13022 CE->getSubExpr()->getType()->isDependentType()) { 13023 return true; 13024 } 13025 } 13026 13027 return false; 13028 } 13029 13030 // Look for instances where it is likely the comma operator is confused with 13031 // another operator. There is an explicit list of acceptable expressions for 13032 // the left hand side of the comma operator, otherwise emit a warning. 13033 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13034 // No warnings in macros 13035 if (Loc.isMacroID()) 13036 return; 13037 13038 // Don't warn in template instantiations. 13039 if (inTemplateInstantiation()) 13040 return; 13041 13042 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13043 // instead, skip more than needed, then call back into here with the 13044 // CommaVisitor in SemaStmt.cpp. 13045 // The listed locations are the initialization and increment portions 13046 // of a for loop. The additional checks are on the condition of 13047 // if statements, do/while loops, and for loops. 13048 // Differences in scope flags for C89 mode requires the extra logic. 13049 const unsigned ForIncrementFlags = 13050 getLangOpts().C99 || getLangOpts().CPlusPlus 13051 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13052 : Scope::ContinueScope | Scope::BreakScope; 13053 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13054 const unsigned ScopeFlags = getCurScope()->getFlags(); 13055 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13056 (ScopeFlags & ForInitFlags) == ForInitFlags) 13057 return; 13058 13059 // If there are multiple comma operators used together, get the RHS of the 13060 // of the comma operator as the LHS. 13061 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13062 if (BO->getOpcode() != BO_Comma) 13063 break; 13064 LHS = BO->getRHS(); 13065 } 13066 13067 // Only allow some expressions on LHS to not warn. 13068 if (IgnoreCommaOperand(LHS)) 13069 return; 13070 13071 Diag(Loc, diag::warn_comma_operator); 13072 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13073 << LHS->getSourceRange() 13074 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13075 LangOpts.CPlusPlus ? "static_cast<void>(" 13076 : "(void)(") 13077 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13078 ")"); 13079 } 13080 13081 // C99 6.5.17 13082 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13083 SourceLocation Loc) { 13084 LHS = S.CheckPlaceholderExpr(LHS.get()); 13085 RHS = S.CheckPlaceholderExpr(RHS.get()); 13086 if (LHS.isInvalid() || RHS.isInvalid()) 13087 return QualType(); 13088 13089 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13090 // operands, but not unary promotions. 13091 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13092 13093 // So we treat the LHS as a ignored value, and in C++ we allow the 13094 // containing site to determine what should be done with the RHS. 13095 LHS = S.IgnoredValueConversions(LHS.get()); 13096 if (LHS.isInvalid()) 13097 return QualType(); 13098 13099 S.DiagnoseUnusedExprResult(LHS.get()); 13100 13101 if (!S.getLangOpts().CPlusPlus) { 13102 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13103 if (RHS.isInvalid()) 13104 return QualType(); 13105 if (!RHS.get()->getType()->isVoidType()) 13106 S.RequireCompleteType(Loc, RHS.get()->getType(), 13107 diag::err_incomplete_type); 13108 } 13109 13110 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13111 S.DiagnoseCommaOperator(LHS.get(), Loc); 13112 13113 return RHS.get()->getType(); 13114 } 13115 13116 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13117 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13118 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13119 ExprValueKind &VK, 13120 ExprObjectKind &OK, 13121 SourceLocation OpLoc, 13122 bool IsInc, bool IsPrefix) { 13123 if (Op->isTypeDependent()) 13124 return S.Context.DependentTy; 13125 13126 QualType ResType = Op->getType(); 13127 // Atomic types can be used for increment / decrement where the non-atomic 13128 // versions can, so ignore the _Atomic() specifier for the purpose of 13129 // checking. 13130 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13131 ResType = ResAtomicType->getValueType(); 13132 13133 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13134 13135 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13136 // Decrement of bool is not allowed. 13137 if (!IsInc) { 13138 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13139 return QualType(); 13140 } 13141 // Increment of bool sets it to true, but is deprecated. 13142 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13143 : diag::warn_increment_bool) 13144 << Op->getSourceRange(); 13145 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13146 // Error on enum increments and decrements in C++ mode 13147 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13148 return QualType(); 13149 } else if (ResType->isRealType()) { 13150 // OK! 13151 } else if (ResType->isPointerType()) { 13152 // C99 6.5.2.4p2, 6.5.6p2 13153 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13154 return QualType(); 13155 } else if (ResType->isObjCObjectPointerType()) { 13156 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13157 // Otherwise, we just need a complete type. 13158 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13159 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13160 return QualType(); 13161 } else if (ResType->isAnyComplexType()) { 13162 // C99 does not support ++/-- on complex types, we allow as an extension. 13163 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13164 << ResType << Op->getSourceRange(); 13165 } else if (ResType->isPlaceholderType()) { 13166 ExprResult PR = S.CheckPlaceholderExpr(Op); 13167 if (PR.isInvalid()) return QualType(); 13168 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13169 IsInc, IsPrefix); 13170 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13171 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13172 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13173 (ResType->castAs<VectorType>()->getVectorKind() != 13174 VectorType::AltiVecBool)) { 13175 // The z vector extensions allow ++ and -- for non-bool vectors. 13176 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13177 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13178 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13179 } else { 13180 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13181 << ResType << int(IsInc) << Op->getSourceRange(); 13182 return QualType(); 13183 } 13184 // At this point, we know we have a real, complex or pointer type. 13185 // Now make sure the operand is a modifiable lvalue. 13186 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13187 return QualType(); 13188 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13189 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13190 // An operand with volatile-qualified type is deprecated 13191 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13192 << IsInc << ResType; 13193 } 13194 // In C++, a prefix increment is the same type as the operand. Otherwise 13195 // (in C or with postfix), the increment is the unqualified type of the 13196 // operand. 13197 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13198 VK = VK_LValue; 13199 OK = Op->getObjectKind(); 13200 return ResType; 13201 } else { 13202 VK = VK_RValue; 13203 return ResType.getUnqualifiedType(); 13204 } 13205 } 13206 13207 13208 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13209 /// This routine allows us to typecheck complex/recursive expressions 13210 /// where the declaration is needed for type checking. We only need to 13211 /// handle cases when the expression references a function designator 13212 /// or is an lvalue. Here are some examples: 13213 /// - &(x) => x 13214 /// - &*****f => f for f a function designator. 13215 /// - &s.xx => s 13216 /// - &s.zz[1].yy -> s, if zz is an array 13217 /// - *(x + 1) -> x, if x is an array 13218 /// - &"123"[2] -> 0 13219 /// - & __real__ x -> x 13220 /// 13221 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13222 /// members. 13223 static ValueDecl *getPrimaryDecl(Expr *E) { 13224 switch (E->getStmtClass()) { 13225 case Stmt::DeclRefExprClass: 13226 return cast<DeclRefExpr>(E)->getDecl(); 13227 case Stmt::MemberExprClass: 13228 // If this is an arrow operator, the address is an offset from 13229 // the base's value, so the object the base refers to is 13230 // irrelevant. 13231 if (cast<MemberExpr>(E)->isArrow()) 13232 return nullptr; 13233 // Otherwise, the expression refers to a part of the base 13234 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13235 case Stmt::ArraySubscriptExprClass: { 13236 // FIXME: This code shouldn't be necessary! We should catch the implicit 13237 // promotion of register arrays earlier. 13238 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13239 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13240 if (ICE->getSubExpr()->getType()->isArrayType()) 13241 return getPrimaryDecl(ICE->getSubExpr()); 13242 } 13243 return nullptr; 13244 } 13245 case Stmt::UnaryOperatorClass: { 13246 UnaryOperator *UO = cast<UnaryOperator>(E); 13247 13248 switch(UO->getOpcode()) { 13249 case UO_Real: 13250 case UO_Imag: 13251 case UO_Extension: 13252 return getPrimaryDecl(UO->getSubExpr()); 13253 default: 13254 return nullptr; 13255 } 13256 } 13257 case Stmt::ParenExprClass: 13258 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13259 case Stmt::ImplicitCastExprClass: 13260 // If the result of an implicit cast is an l-value, we care about 13261 // the sub-expression; otherwise, the result here doesn't matter. 13262 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13263 case Stmt::CXXUuidofExprClass: 13264 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13265 default: 13266 return nullptr; 13267 } 13268 } 13269 13270 namespace { 13271 enum { 13272 AO_Bit_Field = 0, 13273 AO_Vector_Element = 1, 13274 AO_Property_Expansion = 2, 13275 AO_Register_Variable = 3, 13276 AO_Matrix_Element = 4, 13277 AO_No_Error = 5 13278 }; 13279 } 13280 /// Diagnose invalid operand for address of operations. 13281 /// 13282 /// \param Type The type of operand which cannot have its address taken. 13283 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13284 Expr *E, unsigned Type) { 13285 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13286 } 13287 13288 /// CheckAddressOfOperand - The operand of & must be either a function 13289 /// designator or an lvalue designating an object. If it is an lvalue, the 13290 /// object cannot be declared with storage class register or be a bit field. 13291 /// Note: The usual conversions are *not* applied to the operand of the & 13292 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13293 /// In C++, the operand might be an overloaded function name, in which case 13294 /// we allow the '&' but retain the overloaded-function type. 13295 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13296 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13297 if (PTy->getKind() == BuiltinType::Overload) { 13298 Expr *E = OrigOp.get()->IgnoreParens(); 13299 if (!isa<OverloadExpr>(E)) { 13300 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13301 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13302 << OrigOp.get()->getSourceRange(); 13303 return QualType(); 13304 } 13305 13306 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13307 if (isa<UnresolvedMemberExpr>(Ovl)) 13308 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13309 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13310 << OrigOp.get()->getSourceRange(); 13311 return QualType(); 13312 } 13313 13314 return Context.OverloadTy; 13315 } 13316 13317 if (PTy->getKind() == BuiltinType::UnknownAny) 13318 return Context.UnknownAnyTy; 13319 13320 if (PTy->getKind() == BuiltinType::BoundMember) { 13321 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13322 << OrigOp.get()->getSourceRange(); 13323 return QualType(); 13324 } 13325 13326 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13327 if (OrigOp.isInvalid()) return QualType(); 13328 } 13329 13330 if (OrigOp.get()->isTypeDependent()) 13331 return Context.DependentTy; 13332 13333 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13334 13335 // Make sure to ignore parentheses in subsequent checks 13336 Expr *op = OrigOp.get()->IgnoreParens(); 13337 13338 // In OpenCL captures for blocks called as lambda functions 13339 // are located in the private address space. Blocks used in 13340 // enqueue_kernel can be located in a different address space 13341 // depending on a vendor implementation. Thus preventing 13342 // taking an address of the capture to avoid invalid AS casts. 13343 if (LangOpts.OpenCL) { 13344 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13345 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13346 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13347 return QualType(); 13348 } 13349 } 13350 13351 if (getLangOpts().C99) { 13352 // Implement C99-only parts of addressof rules. 13353 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13354 if (uOp->getOpcode() == UO_Deref) 13355 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13356 // (assuming the deref expression is valid). 13357 return uOp->getSubExpr()->getType(); 13358 } 13359 // Technically, there should be a check for array subscript 13360 // expressions here, but the result of one is always an lvalue anyway. 13361 } 13362 ValueDecl *dcl = getPrimaryDecl(op); 13363 13364 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13365 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13366 op->getBeginLoc())) 13367 return QualType(); 13368 13369 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13370 unsigned AddressOfError = AO_No_Error; 13371 13372 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13373 bool sfinae = (bool)isSFINAEContext(); 13374 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13375 : diag::ext_typecheck_addrof_temporary) 13376 << op->getType() << op->getSourceRange(); 13377 if (sfinae) 13378 return QualType(); 13379 // Materialize the temporary as an lvalue so that we can take its address. 13380 OrigOp = op = 13381 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13382 } else if (isa<ObjCSelectorExpr>(op)) { 13383 return Context.getPointerType(op->getType()); 13384 } else if (lval == Expr::LV_MemberFunction) { 13385 // If it's an instance method, make a member pointer. 13386 // The expression must have exactly the form &A::foo. 13387 13388 // If the underlying expression isn't a decl ref, give up. 13389 if (!isa<DeclRefExpr>(op)) { 13390 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13391 << OrigOp.get()->getSourceRange(); 13392 return QualType(); 13393 } 13394 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13395 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13396 13397 // The id-expression was parenthesized. 13398 if (OrigOp.get() != DRE) { 13399 Diag(OpLoc, diag::err_parens_pointer_member_function) 13400 << OrigOp.get()->getSourceRange(); 13401 13402 // The method was named without a qualifier. 13403 } else if (!DRE->getQualifier()) { 13404 if (MD->getParent()->getName().empty()) 13405 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13406 << op->getSourceRange(); 13407 else { 13408 SmallString<32> Str; 13409 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13410 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13411 << op->getSourceRange() 13412 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13413 } 13414 } 13415 13416 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13417 if (isa<CXXDestructorDecl>(MD)) 13418 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13419 13420 QualType MPTy = Context.getMemberPointerType( 13421 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13422 // Under the MS ABI, lock down the inheritance model now. 13423 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13424 (void)isCompleteType(OpLoc, MPTy); 13425 return MPTy; 13426 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13427 // C99 6.5.3.2p1 13428 // The operand must be either an l-value or a function designator 13429 if (!op->getType()->isFunctionType()) { 13430 // Use a special diagnostic for loads from property references. 13431 if (isa<PseudoObjectExpr>(op)) { 13432 AddressOfError = AO_Property_Expansion; 13433 } else { 13434 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13435 << op->getType() << op->getSourceRange(); 13436 return QualType(); 13437 } 13438 } 13439 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13440 // The operand cannot be a bit-field 13441 AddressOfError = AO_Bit_Field; 13442 } else if (op->getObjectKind() == OK_VectorComponent) { 13443 // The operand cannot be an element of a vector 13444 AddressOfError = AO_Vector_Element; 13445 } else if (op->getObjectKind() == OK_MatrixComponent) { 13446 // The operand cannot be an element of a matrix. 13447 AddressOfError = AO_Matrix_Element; 13448 } else if (dcl) { // C99 6.5.3.2p1 13449 // We have an lvalue with a decl. Make sure the decl is not declared 13450 // with the register storage-class specifier. 13451 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13452 // in C++ it is not error to take address of a register 13453 // variable (c++03 7.1.1P3) 13454 if (vd->getStorageClass() == SC_Register && 13455 !getLangOpts().CPlusPlus) { 13456 AddressOfError = AO_Register_Variable; 13457 } 13458 } else if (isa<MSPropertyDecl>(dcl)) { 13459 AddressOfError = AO_Property_Expansion; 13460 } else if (isa<FunctionTemplateDecl>(dcl)) { 13461 return Context.OverloadTy; 13462 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13463 // Okay: we can take the address of a field. 13464 // Could be a pointer to member, though, if there is an explicit 13465 // scope qualifier for the class. 13466 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13467 DeclContext *Ctx = dcl->getDeclContext(); 13468 if (Ctx && Ctx->isRecord()) { 13469 if (dcl->getType()->isReferenceType()) { 13470 Diag(OpLoc, 13471 diag::err_cannot_form_pointer_to_member_of_reference_type) 13472 << dcl->getDeclName() << dcl->getType(); 13473 return QualType(); 13474 } 13475 13476 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13477 Ctx = Ctx->getParent(); 13478 13479 QualType MPTy = Context.getMemberPointerType( 13480 op->getType(), 13481 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13482 // Under the MS ABI, lock down the inheritance model now. 13483 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13484 (void)isCompleteType(OpLoc, MPTy); 13485 return MPTy; 13486 } 13487 } 13488 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13489 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13490 llvm_unreachable("Unknown/unexpected decl type"); 13491 } 13492 13493 if (AddressOfError != AO_No_Error) { 13494 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13495 return QualType(); 13496 } 13497 13498 if (lval == Expr::LV_IncompleteVoidType) { 13499 // Taking the address of a void variable is technically illegal, but we 13500 // allow it in cases which are otherwise valid. 13501 // Example: "extern void x; void* y = &x;". 13502 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13503 } 13504 13505 // If the operand has type "type", the result has type "pointer to type". 13506 if (op->getType()->isObjCObjectType()) 13507 return Context.getObjCObjectPointerType(op->getType()); 13508 13509 CheckAddressOfPackedMember(op); 13510 13511 return Context.getPointerType(op->getType()); 13512 } 13513 13514 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13515 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13516 if (!DRE) 13517 return; 13518 const Decl *D = DRE->getDecl(); 13519 if (!D) 13520 return; 13521 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13522 if (!Param) 13523 return; 13524 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13525 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13526 return; 13527 if (FunctionScopeInfo *FD = S.getCurFunction()) 13528 if (!FD->ModifiedNonNullParams.count(Param)) 13529 FD->ModifiedNonNullParams.insert(Param); 13530 } 13531 13532 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13533 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13534 SourceLocation OpLoc) { 13535 if (Op->isTypeDependent()) 13536 return S.Context.DependentTy; 13537 13538 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13539 if (ConvResult.isInvalid()) 13540 return QualType(); 13541 Op = ConvResult.get(); 13542 QualType OpTy = Op->getType(); 13543 QualType Result; 13544 13545 if (isa<CXXReinterpretCastExpr>(Op)) { 13546 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13547 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13548 Op->getSourceRange()); 13549 } 13550 13551 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13552 { 13553 Result = PT->getPointeeType(); 13554 } 13555 else if (const ObjCObjectPointerType *OPT = 13556 OpTy->getAs<ObjCObjectPointerType>()) 13557 Result = OPT->getPointeeType(); 13558 else { 13559 ExprResult PR = S.CheckPlaceholderExpr(Op); 13560 if (PR.isInvalid()) return QualType(); 13561 if (PR.get() != Op) 13562 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13563 } 13564 13565 if (Result.isNull()) { 13566 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13567 << OpTy << Op->getSourceRange(); 13568 return QualType(); 13569 } 13570 13571 // Note that per both C89 and C99, indirection is always legal, even if Result 13572 // is an incomplete type or void. It would be possible to warn about 13573 // dereferencing a void pointer, but it's completely well-defined, and such a 13574 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13575 // for pointers to 'void' but is fine for any other pointer type: 13576 // 13577 // C++ [expr.unary.op]p1: 13578 // [...] the expression to which [the unary * operator] is applied shall 13579 // be a pointer to an object type, or a pointer to a function type 13580 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13581 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13582 << OpTy << Op->getSourceRange(); 13583 13584 // Dereferences are usually l-values... 13585 VK = VK_LValue; 13586 13587 // ...except that certain expressions are never l-values in C. 13588 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13589 VK = VK_RValue; 13590 13591 return Result; 13592 } 13593 13594 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13595 BinaryOperatorKind Opc; 13596 switch (Kind) { 13597 default: llvm_unreachable("Unknown binop!"); 13598 case tok::periodstar: Opc = BO_PtrMemD; break; 13599 case tok::arrowstar: Opc = BO_PtrMemI; break; 13600 case tok::star: Opc = BO_Mul; break; 13601 case tok::slash: Opc = BO_Div; break; 13602 case tok::percent: Opc = BO_Rem; break; 13603 case tok::plus: Opc = BO_Add; break; 13604 case tok::minus: Opc = BO_Sub; break; 13605 case tok::lessless: Opc = BO_Shl; break; 13606 case tok::greatergreater: Opc = BO_Shr; break; 13607 case tok::lessequal: Opc = BO_LE; break; 13608 case tok::less: Opc = BO_LT; break; 13609 case tok::greaterequal: Opc = BO_GE; break; 13610 case tok::greater: Opc = BO_GT; break; 13611 case tok::exclaimequal: Opc = BO_NE; break; 13612 case tok::equalequal: Opc = BO_EQ; break; 13613 case tok::spaceship: Opc = BO_Cmp; break; 13614 case tok::amp: Opc = BO_And; break; 13615 case tok::caret: Opc = BO_Xor; break; 13616 case tok::pipe: Opc = BO_Or; break; 13617 case tok::ampamp: Opc = BO_LAnd; break; 13618 case tok::pipepipe: Opc = BO_LOr; break; 13619 case tok::equal: Opc = BO_Assign; break; 13620 case tok::starequal: Opc = BO_MulAssign; break; 13621 case tok::slashequal: Opc = BO_DivAssign; break; 13622 case tok::percentequal: Opc = BO_RemAssign; break; 13623 case tok::plusequal: Opc = BO_AddAssign; break; 13624 case tok::minusequal: Opc = BO_SubAssign; break; 13625 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13626 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13627 case tok::ampequal: Opc = BO_AndAssign; break; 13628 case tok::caretequal: Opc = BO_XorAssign; break; 13629 case tok::pipeequal: Opc = BO_OrAssign; break; 13630 case tok::comma: Opc = BO_Comma; break; 13631 } 13632 return Opc; 13633 } 13634 13635 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13636 tok::TokenKind Kind) { 13637 UnaryOperatorKind Opc; 13638 switch (Kind) { 13639 default: llvm_unreachable("Unknown unary op!"); 13640 case tok::plusplus: Opc = UO_PreInc; break; 13641 case tok::minusminus: Opc = UO_PreDec; break; 13642 case tok::amp: Opc = UO_AddrOf; break; 13643 case tok::star: Opc = UO_Deref; break; 13644 case tok::plus: Opc = UO_Plus; break; 13645 case tok::minus: Opc = UO_Minus; break; 13646 case tok::tilde: Opc = UO_Not; break; 13647 case tok::exclaim: Opc = UO_LNot; break; 13648 case tok::kw___real: Opc = UO_Real; break; 13649 case tok::kw___imag: Opc = UO_Imag; break; 13650 case tok::kw___extension__: Opc = UO_Extension; break; 13651 } 13652 return Opc; 13653 } 13654 13655 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13656 /// This warning suppressed in the event of macro expansions. 13657 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13658 SourceLocation OpLoc, bool IsBuiltin) { 13659 if (S.inTemplateInstantiation()) 13660 return; 13661 if (S.isUnevaluatedContext()) 13662 return; 13663 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13664 return; 13665 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13666 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13667 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13668 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13669 if (!LHSDeclRef || !RHSDeclRef || 13670 LHSDeclRef->getLocation().isMacroID() || 13671 RHSDeclRef->getLocation().isMacroID()) 13672 return; 13673 const ValueDecl *LHSDecl = 13674 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13675 const ValueDecl *RHSDecl = 13676 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13677 if (LHSDecl != RHSDecl) 13678 return; 13679 if (LHSDecl->getType().isVolatileQualified()) 13680 return; 13681 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13682 if (RefTy->getPointeeType().isVolatileQualified()) 13683 return; 13684 13685 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13686 : diag::warn_self_assignment_overloaded) 13687 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13688 << RHSExpr->getSourceRange(); 13689 } 13690 13691 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13692 /// is usually indicative of introspection within the Objective-C pointer. 13693 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13694 SourceLocation OpLoc) { 13695 if (!S.getLangOpts().ObjC) 13696 return; 13697 13698 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13699 const Expr *LHS = L.get(); 13700 const Expr *RHS = R.get(); 13701 13702 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13703 ObjCPointerExpr = LHS; 13704 OtherExpr = RHS; 13705 } 13706 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13707 ObjCPointerExpr = RHS; 13708 OtherExpr = LHS; 13709 } 13710 13711 // This warning is deliberately made very specific to reduce false 13712 // positives with logic that uses '&' for hashing. This logic mainly 13713 // looks for code trying to introspect into tagged pointers, which 13714 // code should generally never do. 13715 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13716 unsigned Diag = diag::warn_objc_pointer_masking; 13717 // Determine if we are introspecting the result of performSelectorXXX. 13718 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13719 // Special case messages to -performSelector and friends, which 13720 // can return non-pointer values boxed in a pointer value. 13721 // Some clients may wish to silence warnings in this subcase. 13722 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13723 Selector S = ME->getSelector(); 13724 StringRef SelArg0 = S.getNameForSlot(0); 13725 if (SelArg0.startswith("performSelector")) 13726 Diag = diag::warn_objc_pointer_masking_performSelector; 13727 } 13728 13729 S.Diag(OpLoc, Diag) 13730 << ObjCPointerExpr->getSourceRange(); 13731 } 13732 } 13733 13734 static NamedDecl *getDeclFromExpr(Expr *E) { 13735 if (!E) 13736 return nullptr; 13737 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13738 return DRE->getDecl(); 13739 if (auto *ME = dyn_cast<MemberExpr>(E)) 13740 return ME->getMemberDecl(); 13741 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13742 return IRE->getDecl(); 13743 return nullptr; 13744 } 13745 13746 // This helper function promotes a binary operator's operands (which are of a 13747 // half vector type) to a vector of floats and then truncates the result to 13748 // a vector of either half or short. 13749 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13750 BinaryOperatorKind Opc, QualType ResultTy, 13751 ExprValueKind VK, ExprObjectKind OK, 13752 bool IsCompAssign, SourceLocation OpLoc, 13753 FPOptionsOverride FPFeatures) { 13754 auto &Context = S.getASTContext(); 13755 assert((isVector(ResultTy, Context.HalfTy) || 13756 isVector(ResultTy, Context.ShortTy)) && 13757 "Result must be a vector of half or short"); 13758 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13759 isVector(RHS.get()->getType(), Context.HalfTy) && 13760 "both operands expected to be a half vector"); 13761 13762 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13763 QualType BinOpResTy = RHS.get()->getType(); 13764 13765 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13766 // change BinOpResTy to a vector of ints. 13767 if (isVector(ResultTy, Context.ShortTy)) 13768 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13769 13770 if (IsCompAssign) 13771 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13772 ResultTy, VK, OK, OpLoc, FPFeatures, 13773 BinOpResTy, BinOpResTy); 13774 13775 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13776 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13777 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13778 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13779 } 13780 13781 static std::pair<ExprResult, ExprResult> 13782 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13783 Expr *RHSExpr) { 13784 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13785 if (!S.Context.isDependenceAllowed()) { 13786 // C cannot handle TypoExpr nodes on either side of a binop because it 13787 // doesn't handle dependent types properly, so make sure any TypoExprs have 13788 // been dealt with before checking the operands. 13789 LHS = S.CorrectDelayedTyposInExpr(LHS); 13790 RHS = S.CorrectDelayedTyposInExpr( 13791 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13792 [Opc, LHS](Expr *E) { 13793 if (Opc != BO_Assign) 13794 return ExprResult(E); 13795 // Avoid correcting the RHS to the same Expr as the LHS. 13796 Decl *D = getDeclFromExpr(E); 13797 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13798 }); 13799 } 13800 return std::make_pair(LHS, RHS); 13801 } 13802 13803 /// Returns true if conversion between vectors of halfs and vectors of floats 13804 /// is needed. 13805 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13806 Expr *E0, Expr *E1 = nullptr) { 13807 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13808 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13809 return false; 13810 13811 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13812 QualType Ty = E->IgnoreImplicit()->getType(); 13813 13814 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13815 // to vectors of floats. Although the element type of the vectors is __fp16, 13816 // the vectors shouldn't be treated as storage-only types. See the 13817 // discussion here: https://reviews.llvm.org/rG825235c140e7 13818 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13819 if (VT->getVectorKind() == VectorType::NeonVector) 13820 return false; 13821 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13822 } 13823 return false; 13824 }; 13825 13826 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13827 } 13828 13829 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13830 /// operator @p Opc at location @c TokLoc. This routine only supports 13831 /// built-in operations; ActOnBinOp handles overloaded operators. 13832 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13833 BinaryOperatorKind Opc, 13834 Expr *LHSExpr, Expr *RHSExpr) { 13835 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13836 // The syntax only allows initializer lists on the RHS of assignment, 13837 // so we don't need to worry about accepting invalid code for 13838 // non-assignment operators. 13839 // C++11 5.17p9: 13840 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13841 // of x = {} is x = T(). 13842 InitializationKind Kind = InitializationKind::CreateDirectList( 13843 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13844 InitializedEntity Entity = 13845 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13846 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13847 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13848 if (Init.isInvalid()) 13849 return Init; 13850 RHSExpr = Init.get(); 13851 } 13852 13853 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13854 QualType ResultTy; // Result type of the binary operator. 13855 // The following two variables are used for compound assignment operators 13856 QualType CompLHSTy; // Type of LHS after promotions for computation 13857 QualType CompResultTy; // Type of computation result 13858 ExprValueKind VK = VK_RValue; 13859 ExprObjectKind OK = OK_Ordinary; 13860 bool ConvertHalfVec = false; 13861 13862 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13863 if (!LHS.isUsable() || !RHS.isUsable()) 13864 return ExprError(); 13865 13866 if (getLangOpts().OpenCL) { 13867 QualType LHSTy = LHSExpr->getType(); 13868 QualType RHSTy = RHSExpr->getType(); 13869 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13870 // the ATOMIC_VAR_INIT macro. 13871 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13872 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13873 if (BO_Assign == Opc) 13874 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13875 else 13876 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13877 return ExprError(); 13878 } 13879 13880 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13881 // only with a builtin functions and therefore should be disallowed here. 13882 if (LHSTy->isImageType() || RHSTy->isImageType() || 13883 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13884 LHSTy->isPipeType() || RHSTy->isPipeType() || 13885 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13886 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13887 return ExprError(); 13888 } 13889 } 13890 13891 switch (Opc) { 13892 case BO_Assign: 13893 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13894 if (getLangOpts().CPlusPlus && 13895 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13896 VK = LHS.get()->getValueKind(); 13897 OK = LHS.get()->getObjectKind(); 13898 } 13899 if (!ResultTy.isNull()) { 13900 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13901 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13902 13903 // Avoid copying a block to the heap if the block is assigned to a local 13904 // auto variable that is declared in the same scope as the block. This 13905 // optimization is unsafe if the local variable is declared in an outer 13906 // scope. For example: 13907 // 13908 // BlockTy b; 13909 // { 13910 // b = ^{...}; 13911 // } 13912 // // It is unsafe to invoke the block here if it wasn't copied to the 13913 // // heap. 13914 // b(); 13915 13916 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13917 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13918 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13919 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13920 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13921 13922 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13923 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13924 NTCUC_Assignment, NTCUK_Copy); 13925 } 13926 RecordModifiableNonNullParam(*this, LHS.get()); 13927 break; 13928 case BO_PtrMemD: 13929 case BO_PtrMemI: 13930 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13931 Opc == BO_PtrMemI); 13932 break; 13933 case BO_Mul: 13934 case BO_Div: 13935 ConvertHalfVec = true; 13936 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13937 Opc == BO_Div); 13938 break; 13939 case BO_Rem: 13940 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13941 break; 13942 case BO_Add: 13943 ConvertHalfVec = true; 13944 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13945 break; 13946 case BO_Sub: 13947 ConvertHalfVec = true; 13948 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13949 break; 13950 case BO_Shl: 13951 case BO_Shr: 13952 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13953 break; 13954 case BO_LE: 13955 case BO_LT: 13956 case BO_GE: 13957 case BO_GT: 13958 ConvertHalfVec = true; 13959 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13960 break; 13961 case BO_EQ: 13962 case BO_NE: 13963 ConvertHalfVec = true; 13964 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13965 break; 13966 case BO_Cmp: 13967 ConvertHalfVec = true; 13968 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13969 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13970 break; 13971 case BO_And: 13972 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13973 LLVM_FALLTHROUGH; 13974 case BO_Xor: 13975 case BO_Or: 13976 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13977 break; 13978 case BO_LAnd: 13979 case BO_LOr: 13980 ConvertHalfVec = true; 13981 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13982 break; 13983 case BO_MulAssign: 13984 case BO_DivAssign: 13985 ConvertHalfVec = true; 13986 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13987 Opc == BO_DivAssign); 13988 CompLHSTy = CompResultTy; 13989 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13990 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13991 break; 13992 case BO_RemAssign: 13993 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13994 CompLHSTy = CompResultTy; 13995 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13997 break; 13998 case BO_AddAssign: 13999 ConvertHalfVec = true; 14000 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14001 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14002 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14003 break; 14004 case BO_SubAssign: 14005 ConvertHalfVec = true; 14006 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14007 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14008 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14009 break; 14010 case BO_ShlAssign: 14011 case BO_ShrAssign: 14012 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14013 CompLHSTy = CompResultTy; 14014 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14015 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14016 break; 14017 case BO_AndAssign: 14018 case BO_OrAssign: // fallthrough 14019 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14020 LLVM_FALLTHROUGH; 14021 case BO_XorAssign: 14022 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14023 CompLHSTy = CompResultTy; 14024 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14025 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14026 break; 14027 case BO_Comma: 14028 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14029 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14030 VK = RHS.get()->getValueKind(); 14031 OK = RHS.get()->getObjectKind(); 14032 } 14033 break; 14034 } 14035 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14036 return ExprError(); 14037 14038 // Some of the binary operations require promoting operands of half vector to 14039 // float vectors and truncating the result back to half vector. For now, we do 14040 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14041 // arm64). 14042 assert( 14043 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14044 isVector(LHS.get()->getType(), Context.HalfTy)) && 14045 "both sides are half vectors or neither sides are"); 14046 ConvertHalfVec = 14047 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14048 14049 // Check for array bounds violations for both sides of the BinaryOperator 14050 CheckArrayAccess(LHS.get()); 14051 CheckArrayAccess(RHS.get()); 14052 14053 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14054 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14055 &Context.Idents.get("object_setClass"), 14056 SourceLocation(), LookupOrdinaryName); 14057 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14058 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14059 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14060 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14061 "object_setClass(") 14062 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14063 ",") 14064 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14065 } 14066 else 14067 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14068 } 14069 else if (const ObjCIvarRefExpr *OIRE = 14070 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14071 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14072 14073 // Opc is not a compound assignment if CompResultTy is null. 14074 if (CompResultTy.isNull()) { 14075 if (ConvertHalfVec) 14076 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14077 OpLoc, CurFPFeatureOverrides()); 14078 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14079 VK, OK, OpLoc, CurFPFeatureOverrides()); 14080 } 14081 14082 // Handle compound assignments. 14083 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14084 OK_ObjCProperty) { 14085 VK = VK_LValue; 14086 OK = LHS.get()->getObjectKind(); 14087 } 14088 14089 // The LHS is not converted to the result type for fixed-point compound 14090 // assignment as the common type is computed on demand. Reset the CompLHSTy 14091 // to the LHS type we would have gotten after unary conversions. 14092 if (CompResultTy->isFixedPointType()) 14093 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14094 14095 if (ConvertHalfVec) 14096 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14097 OpLoc, CurFPFeatureOverrides()); 14098 14099 return CompoundAssignOperator::Create( 14100 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14101 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14102 } 14103 14104 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14105 /// operators are mixed in a way that suggests that the programmer forgot that 14106 /// comparison operators have higher precedence. The most typical example of 14107 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14108 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14109 SourceLocation OpLoc, Expr *LHSExpr, 14110 Expr *RHSExpr) { 14111 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14112 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14113 14114 // Check that one of the sides is a comparison operator and the other isn't. 14115 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14116 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14117 if (isLeftComp == isRightComp) 14118 return; 14119 14120 // Bitwise operations are sometimes used as eager logical ops. 14121 // Don't diagnose this. 14122 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14123 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14124 if (isLeftBitwise || isRightBitwise) 14125 return; 14126 14127 SourceRange DiagRange = isLeftComp 14128 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14129 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14130 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14131 SourceRange ParensRange = 14132 isLeftComp 14133 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14134 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14135 14136 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14137 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14138 SuggestParentheses(Self, OpLoc, 14139 Self.PDiag(diag::note_precedence_silence) << OpStr, 14140 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14141 SuggestParentheses(Self, OpLoc, 14142 Self.PDiag(diag::note_precedence_bitwise_first) 14143 << BinaryOperator::getOpcodeStr(Opc), 14144 ParensRange); 14145 } 14146 14147 /// It accepts a '&&' expr that is inside a '||' one. 14148 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14149 /// in parentheses. 14150 static void 14151 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14152 BinaryOperator *Bop) { 14153 assert(Bop->getOpcode() == BO_LAnd); 14154 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14155 << Bop->getSourceRange() << OpLoc; 14156 SuggestParentheses(Self, Bop->getOperatorLoc(), 14157 Self.PDiag(diag::note_precedence_silence) 14158 << Bop->getOpcodeStr(), 14159 Bop->getSourceRange()); 14160 } 14161 14162 /// Returns true if the given expression can be evaluated as a constant 14163 /// 'true'. 14164 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14165 bool Res; 14166 return !E->isValueDependent() && 14167 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14168 } 14169 14170 /// Returns true if the given expression can be evaluated as a constant 14171 /// 'false'. 14172 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14173 bool Res; 14174 return !E->isValueDependent() && 14175 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14176 } 14177 14178 /// Look for '&&' in the left hand of a '||' expr. 14179 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14180 Expr *LHSExpr, Expr *RHSExpr) { 14181 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14182 if (Bop->getOpcode() == BO_LAnd) { 14183 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14184 if (EvaluatesAsFalse(S, RHSExpr)) 14185 return; 14186 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14187 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14188 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14189 } else if (Bop->getOpcode() == BO_LOr) { 14190 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14191 // If it's "a || b && 1 || c" we didn't warn earlier for 14192 // "a || b && 1", but warn now. 14193 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14194 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14195 } 14196 } 14197 } 14198 } 14199 14200 /// Look for '&&' in the right hand of a '||' expr. 14201 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14202 Expr *LHSExpr, Expr *RHSExpr) { 14203 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14204 if (Bop->getOpcode() == BO_LAnd) { 14205 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14206 if (EvaluatesAsFalse(S, LHSExpr)) 14207 return; 14208 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14209 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14210 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14211 } 14212 } 14213 } 14214 14215 /// Look for bitwise op in the left or right hand of a bitwise op with 14216 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14217 /// the '&' expression in parentheses. 14218 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14219 SourceLocation OpLoc, Expr *SubExpr) { 14220 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14221 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14222 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14223 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14224 << Bop->getSourceRange() << OpLoc; 14225 SuggestParentheses(S, Bop->getOperatorLoc(), 14226 S.PDiag(diag::note_precedence_silence) 14227 << Bop->getOpcodeStr(), 14228 Bop->getSourceRange()); 14229 } 14230 } 14231 } 14232 14233 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14234 Expr *SubExpr, StringRef Shift) { 14235 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14236 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14237 StringRef Op = Bop->getOpcodeStr(); 14238 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14239 << Bop->getSourceRange() << OpLoc << Shift << Op; 14240 SuggestParentheses(S, Bop->getOperatorLoc(), 14241 S.PDiag(diag::note_precedence_silence) << Op, 14242 Bop->getSourceRange()); 14243 } 14244 } 14245 } 14246 14247 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14248 Expr *LHSExpr, Expr *RHSExpr) { 14249 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14250 if (!OCE) 14251 return; 14252 14253 FunctionDecl *FD = OCE->getDirectCallee(); 14254 if (!FD || !FD->isOverloadedOperator()) 14255 return; 14256 14257 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14258 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14259 return; 14260 14261 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14262 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14263 << (Kind == OO_LessLess); 14264 SuggestParentheses(S, OCE->getOperatorLoc(), 14265 S.PDiag(diag::note_precedence_silence) 14266 << (Kind == OO_LessLess ? "<<" : ">>"), 14267 OCE->getSourceRange()); 14268 SuggestParentheses( 14269 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14270 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14271 } 14272 14273 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14274 /// precedence. 14275 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14276 SourceLocation OpLoc, Expr *LHSExpr, 14277 Expr *RHSExpr){ 14278 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14279 if (BinaryOperator::isBitwiseOp(Opc)) 14280 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14281 14282 // Diagnose "arg1 & arg2 | arg3" 14283 if ((Opc == BO_Or || Opc == BO_Xor) && 14284 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14285 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14286 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14287 } 14288 14289 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14290 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14291 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14292 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14293 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14294 } 14295 14296 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14297 || Opc == BO_Shr) { 14298 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14299 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14300 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14301 } 14302 14303 // Warn on overloaded shift operators and comparisons, such as: 14304 // cout << 5 == 4; 14305 if (BinaryOperator::isComparisonOp(Opc)) 14306 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14307 } 14308 14309 // Binary Operators. 'Tok' is the token for the operator. 14310 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14311 tok::TokenKind Kind, 14312 Expr *LHSExpr, Expr *RHSExpr) { 14313 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14314 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14315 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14316 14317 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14318 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14319 14320 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14321 } 14322 14323 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14324 UnresolvedSetImpl &Functions) { 14325 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14326 if (OverOp != OO_None && OverOp != OO_Equal) 14327 LookupOverloadedOperatorName(OverOp, S, Functions); 14328 14329 // In C++20 onwards, we may have a second operator to look up. 14330 if (getLangOpts().CPlusPlus20) { 14331 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14332 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14333 } 14334 } 14335 14336 /// Build an overloaded binary operator expression in the given scope. 14337 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14338 BinaryOperatorKind Opc, 14339 Expr *LHS, Expr *RHS) { 14340 switch (Opc) { 14341 case BO_Assign: 14342 case BO_DivAssign: 14343 case BO_RemAssign: 14344 case BO_SubAssign: 14345 case BO_AndAssign: 14346 case BO_OrAssign: 14347 case BO_XorAssign: 14348 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14349 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14350 break; 14351 default: 14352 break; 14353 } 14354 14355 // Find all of the overloaded operators visible from this point. 14356 UnresolvedSet<16> Functions; 14357 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14358 14359 // Build the (potentially-overloaded, potentially-dependent) 14360 // binary operation. 14361 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14362 } 14363 14364 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14365 BinaryOperatorKind Opc, 14366 Expr *LHSExpr, Expr *RHSExpr) { 14367 ExprResult LHS, RHS; 14368 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14369 if (!LHS.isUsable() || !RHS.isUsable()) 14370 return ExprError(); 14371 LHSExpr = LHS.get(); 14372 RHSExpr = RHS.get(); 14373 14374 // We want to end up calling one of checkPseudoObjectAssignment 14375 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14376 // both expressions are overloadable or either is type-dependent), 14377 // or CreateBuiltinBinOp (in any other case). We also want to get 14378 // any placeholder types out of the way. 14379 14380 // Handle pseudo-objects in the LHS. 14381 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14382 // Assignments with a pseudo-object l-value need special analysis. 14383 if (pty->getKind() == BuiltinType::PseudoObject && 14384 BinaryOperator::isAssignmentOp(Opc)) 14385 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14386 14387 // Don't resolve overloads if the other type is overloadable. 14388 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14389 // We can't actually test that if we still have a placeholder, 14390 // though. Fortunately, none of the exceptions we see in that 14391 // code below are valid when the LHS is an overload set. Note 14392 // that an overload set can be dependently-typed, but it never 14393 // instantiates to having an overloadable type. 14394 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14395 if (resolvedRHS.isInvalid()) return ExprError(); 14396 RHSExpr = resolvedRHS.get(); 14397 14398 if (RHSExpr->isTypeDependent() || 14399 RHSExpr->getType()->isOverloadableType()) 14400 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14401 } 14402 14403 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14404 // template, diagnose the missing 'template' keyword instead of diagnosing 14405 // an invalid use of a bound member function. 14406 // 14407 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14408 // to C++1z [over.over]/1.4, but we already checked for that case above. 14409 if (Opc == BO_LT && inTemplateInstantiation() && 14410 (pty->getKind() == BuiltinType::BoundMember || 14411 pty->getKind() == BuiltinType::Overload)) { 14412 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14413 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14414 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14415 return isa<FunctionTemplateDecl>(ND); 14416 })) { 14417 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14418 : OE->getNameLoc(), 14419 diag::err_template_kw_missing) 14420 << OE->getName().getAsString() << ""; 14421 return ExprError(); 14422 } 14423 } 14424 14425 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14426 if (LHS.isInvalid()) return ExprError(); 14427 LHSExpr = LHS.get(); 14428 } 14429 14430 // Handle pseudo-objects in the RHS. 14431 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14432 // An overload in the RHS can potentially be resolved by the type 14433 // being assigned to. 14434 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14435 if (getLangOpts().CPlusPlus && 14436 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14437 LHSExpr->getType()->isOverloadableType())) 14438 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14439 14440 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14441 } 14442 14443 // Don't resolve overloads if the other type is overloadable. 14444 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14445 LHSExpr->getType()->isOverloadableType()) 14446 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14447 14448 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14449 if (!resolvedRHS.isUsable()) return ExprError(); 14450 RHSExpr = resolvedRHS.get(); 14451 } 14452 14453 if (getLangOpts().CPlusPlus) { 14454 // If either expression is type-dependent, always build an 14455 // overloaded op. 14456 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14457 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14458 14459 // Otherwise, build an overloaded op if either expression has an 14460 // overloadable type. 14461 if (LHSExpr->getType()->isOverloadableType() || 14462 RHSExpr->getType()->isOverloadableType()) 14463 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14464 } 14465 14466 if (getLangOpts().RecoveryAST && 14467 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14468 assert(!getLangOpts().CPlusPlus); 14469 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14470 "Should only occur in error-recovery path."); 14471 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14472 // C [6.15.16] p3: 14473 // An assignment expression has the value of the left operand after the 14474 // assignment, but is not an lvalue. 14475 return CompoundAssignOperator::Create( 14476 Context, LHSExpr, RHSExpr, Opc, 14477 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14478 OpLoc, CurFPFeatureOverrides()); 14479 QualType ResultType; 14480 switch (Opc) { 14481 case BO_Assign: 14482 ResultType = LHSExpr->getType().getUnqualifiedType(); 14483 break; 14484 case BO_LT: 14485 case BO_GT: 14486 case BO_LE: 14487 case BO_GE: 14488 case BO_EQ: 14489 case BO_NE: 14490 case BO_LAnd: 14491 case BO_LOr: 14492 // These operators have a fixed result type regardless of operands. 14493 ResultType = Context.IntTy; 14494 break; 14495 case BO_Comma: 14496 ResultType = RHSExpr->getType(); 14497 break; 14498 default: 14499 ResultType = Context.DependentTy; 14500 break; 14501 } 14502 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14503 VK_RValue, OK_Ordinary, OpLoc, 14504 CurFPFeatureOverrides()); 14505 } 14506 14507 // Build a built-in binary operation. 14508 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14509 } 14510 14511 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14512 if (T.isNull() || T->isDependentType()) 14513 return false; 14514 14515 if (!T->isPromotableIntegerType()) 14516 return true; 14517 14518 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14519 } 14520 14521 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14522 UnaryOperatorKind Opc, 14523 Expr *InputExpr) { 14524 ExprResult Input = InputExpr; 14525 ExprValueKind VK = VK_RValue; 14526 ExprObjectKind OK = OK_Ordinary; 14527 QualType resultType; 14528 bool CanOverflow = false; 14529 14530 bool ConvertHalfVec = false; 14531 if (getLangOpts().OpenCL) { 14532 QualType Ty = InputExpr->getType(); 14533 // The only legal unary operation for atomics is '&'. 14534 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14535 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14536 // only with a builtin functions and therefore should be disallowed here. 14537 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14538 || Ty->isBlockPointerType())) { 14539 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14540 << InputExpr->getType() 14541 << Input.get()->getSourceRange()); 14542 } 14543 } 14544 14545 switch (Opc) { 14546 case UO_PreInc: 14547 case UO_PreDec: 14548 case UO_PostInc: 14549 case UO_PostDec: 14550 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14551 OpLoc, 14552 Opc == UO_PreInc || 14553 Opc == UO_PostInc, 14554 Opc == UO_PreInc || 14555 Opc == UO_PreDec); 14556 CanOverflow = isOverflowingIntegerType(Context, resultType); 14557 break; 14558 case UO_AddrOf: 14559 resultType = CheckAddressOfOperand(Input, OpLoc); 14560 CheckAddressOfNoDeref(InputExpr); 14561 RecordModifiableNonNullParam(*this, InputExpr); 14562 break; 14563 case UO_Deref: { 14564 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14565 if (Input.isInvalid()) return ExprError(); 14566 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14567 break; 14568 } 14569 case UO_Plus: 14570 case UO_Minus: 14571 CanOverflow = Opc == UO_Minus && 14572 isOverflowingIntegerType(Context, Input.get()->getType()); 14573 Input = UsualUnaryConversions(Input.get()); 14574 if (Input.isInvalid()) return ExprError(); 14575 // Unary plus and minus require promoting an operand of half vector to a 14576 // float vector and truncating the result back to a half vector. For now, we 14577 // do this only when HalfArgsAndReturns is set (that is, when the target is 14578 // arm or arm64). 14579 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14580 14581 // If the operand is a half vector, promote it to a float vector. 14582 if (ConvertHalfVec) 14583 Input = convertVector(Input.get(), Context.FloatTy, *this); 14584 resultType = Input.get()->getType(); 14585 if (resultType->isDependentType()) 14586 break; 14587 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14588 break; 14589 else if (resultType->isVectorType() && 14590 // The z vector extensions don't allow + or - with bool vectors. 14591 (!Context.getLangOpts().ZVector || 14592 resultType->castAs<VectorType>()->getVectorKind() != 14593 VectorType::AltiVecBool)) 14594 break; 14595 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14596 Opc == UO_Plus && 14597 resultType->isPointerType()) 14598 break; 14599 14600 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14601 << resultType << Input.get()->getSourceRange()); 14602 14603 case UO_Not: // bitwise complement 14604 Input = UsualUnaryConversions(Input.get()); 14605 if (Input.isInvalid()) 14606 return ExprError(); 14607 resultType = Input.get()->getType(); 14608 if (resultType->isDependentType()) 14609 break; 14610 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14611 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14612 // C99 does not support '~' for complex conjugation. 14613 Diag(OpLoc, diag::ext_integer_complement_complex) 14614 << resultType << Input.get()->getSourceRange(); 14615 else if (resultType->hasIntegerRepresentation()) 14616 break; 14617 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14618 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14619 // on vector float types. 14620 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14621 if (!T->isIntegerType()) 14622 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14623 << resultType << Input.get()->getSourceRange()); 14624 } else { 14625 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14626 << resultType << Input.get()->getSourceRange()); 14627 } 14628 break; 14629 14630 case UO_LNot: // logical negation 14631 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14632 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14633 if (Input.isInvalid()) return ExprError(); 14634 resultType = Input.get()->getType(); 14635 14636 // Though we still have to promote half FP to float... 14637 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14638 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14639 resultType = Context.FloatTy; 14640 } 14641 14642 if (resultType->isDependentType()) 14643 break; 14644 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14645 // C99 6.5.3.3p1: ok, fallthrough; 14646 if (Context.getLangOpts().CPlusPlus) { 14647 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14648 // operand contextually converted to bool. 14649 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14650 ScalarTypeToBooleanCastKind(resultType)); 14651 } else if (Context.getLangOpts().OpenCL && 14652 Context.getLangOpts().OpenCLVersion < 120) { 14653 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14654 // operate on scalar float types. 14655 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14656 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14657 << resultType << Input.get()->getSourceRange()); 14658 } 14659 } else if (resultType->isExtVectorType()) { 14660 if (Context.getLangOpts().OpenCL && 14661 Context.getLangOpts().OpenCLVersion < 120 && 14662 !Context.getLangOpts().OpenCLCPlusPlus) { 14663 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14664 // operate on vector float types. 14665 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14666 if (!T->isIntegerType()) 14667 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14668 << resultType << Input.get()->getSourceRange()); 14669 } 14670 // Vector logical not returns the signed variant of the operand type. 14671 resultType = GetSignedVectorType(resultType); 14672 break; 14673 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14674 const VectorType *VTy = resultType->castAs<VectorType>(); 14675 if (VTy->getVectorKind() != VectorType::GenericVector) 14676 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14677 << resultType << Input.get()->getSourceRange()); 14678 14679 // Vector logical not returns the signed variant of the operand type. 14680 resultType = GetSignedVectorType(resultType); 14681 break; 14682 } else { 14683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14684 << resultType << Input.get()->getSourceRange()); 14685 } 14686 14687 // LNot always has type int. C99 6.5.3.3p5. 14688 // In C++, it's bool. C++ 5.3.1p8 14689 resultType = Context.getLogicalOperationType(); 14690 break; 14691 case UO_Real: 14692 case UO_Imag: 14693 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14694 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14695 // complex l-values to ordinary l-values and all other values to r-values. 14696 if (Input.isInvalid()) return ExprError(); 14697 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14698 if (Input.get()->getValueKind() != VK_RValue && 14699 Input.get()->getObjectKind() == OK_Ordinary) 14700 VK = Input.get()->getValueKind(); 14701 } else if (!getLangOpts().CPlusPlus) { 14702 // In C, a volatile scalar is read by __imag. In C++, it is not. 14703 Input = DefaultLvalueConversion(Input.get()); 14704 } 14705 break; 14706 case UO_Extension: 14707 resultType = Input.get()->getType(); 14708 VK = Input.get()->getValueKind(); 14709 OK = Input.get()->getObjectKind(); 14710 break; 14711 case UO_Coawait: 14712 // It's unnecessary to represent the pass-through operator co_await in the 14713 // AST; just return the input expression instead. 14714 assert(!Input.get()->getType()->isDependentType() && 14715 "the co_await expression must be non-dependant before " 14716 "building operator co_await"); 14717 return Input; 14718 } 14719 if (resultType.isNull() || Input.isInvalid()) 14720 return ExprError(); 14721 14722 // Check for array bounds violations in the operand of the UnaryOperator, 14723 // except for the '*' and '&' operators that have to be handled specially 14724 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14725 // that are explicitly defined as valid by the standard). 14726 if (Opc != UO_AddrOf && Opc != UO_Deref) 14727 CheckArrayAccess(Input.get()); 14728 14729 auto *UO = 14730 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14731 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14732 14733 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14734 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14735 !isUnevaluatedContext()) 14736 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14737 14738 // Convert the result back to a half vector. 14739 if (ConvertHalfVec) 14740 return convertVector(UO, Context.HalfTy, *this); 14741 return UO; 14742 } 14743 14744 /// Determine whether the given expression is a qualified member 14745 /// access expression, of a form that could be turned into a pointer to member 14746 /// with the address-of operator. 14747 bool Sema::isQualifiedMemberAccess(Expr *E) { 14748 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14749 if (!DRE->getQualifier()) 14750 return false; 14751 14752 ValueDecl *VD = DRE->getDecl(); 14753 if (!VD->isCXXClassMember()) 14754 return false; 14755 14756 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14757 return true; 14758 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14759 return Method->isInstance(); 14760 14761 return false; 14762 } 14763 14764 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14765 if (!ULE->getQualifier()) 14766 return false; 14767 14768 for (NamedDecl *D : ULE->decls()) { 14769 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14770 if (Method->isInstance()) 14771 return true; 14772 } else { 14773 // Overload set does not contain methods. 14774 break; 14775 } 14776 } 14777 14778 return false; 14779 } 14780 14781 return false; 14782 } 14783 14784 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14785 UnaryOperatorKind Opc, Expr *Input) { 14786 // First things first: handle placeholders so that the 14787 // overloaded-operator check considers the right type. 14788 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14789 // Increment and decrement of pseudo-object references. 14790 if (pty->getKind() == BuiltinType::PseudoObject && 14791 UnaryOperator::isIncrementDecrementOp(Opc)) 14792 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14793 14794 // extension is always a builtin operator. 14795 if (Opc == UO_Extension) 14796 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14797 14798 // & gets special logic for several kinds of placeholder. 14799 // The builtin code knows what to do. 14800 if (Opc == UO_AddrOf && 14801 (pty->getKind() == BuiltinType::Overload || 14802 pty->getKind() == BuiltinType::UnknownAny || 14803 pty->getKind() == BuiltinType::BoundMember)) 14804 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14805 14806 // Anything else needs to be handled now. 14807 ExprResult Result = CheckPlaceholderExpr(Input); 14808 if (Result.isInvalid()) return ExprError(); 14809 Input = Result.get(); 14810 } 14811 14812 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14813 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14814 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14815 // Find all of the overloaded operators visible from this point. 14816 UnresolvedSet<16> Functions; 14817 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14818 if (S && OverOp != OO_None) 14819 LookupOverloadedOperatorName(OverOp, S, Functions); 14820 14821 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14822 } 14823 14824 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14825 } 14826 14827 // Unary Operators. 'Tok' is the token for the operator. 14828 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14829 tok::TokenKind Op, Expr *Input) { 14830 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14831 } 14832 14833 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14834 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14835 LabelDecl *TheDecl) { 14836 TheDecl->markUsed(Context); 14837 // Create the AST node. The address of a label always has type 'void*'. 14838 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14839 Context.getPointerType(Context.VoidTy)); 14840 } 14841 14842 void Sema::ActOnStartStmtExpr() { 14843 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14844 } 14845 14846 void Sema::ActOnStmtExprError() { 14847 // Note that function is also called by TreeTransform when leaving a 14848 // StmtExpr scope without rebuilding anything. 14849 14850 DiscardCleanupsInEvaluationContext(); 14851 PopExpressionEvaluationContext(); 14852 } 14853 14854 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14855 SourceLocation RPLoc) { 14856 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14857 } 14858 14859 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14860 SourceLocation RPLoc, unsigned TemplateDepth) { 14861 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14862 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14863 14864 if (hasAnyUnrecoverableErrorsInThisFunction()) 14865 DiscardCleanupsInEvaluationContext(); 14866 assert(!Cleanup.exprNeedsCleanups() && 14867 "cleanups within StmtExpr not correctly bound!"); 14868 PopExpressionEvaluationContext(); 14869 14870 // FIXME: there are a variety of strange constraints to enforce here, for 14871 // example, it is not possible to goto into a stmt expression apparently. 14872 // More semantic analysis is needed. 14873 14874 // If there are sub-stmts in the compound stmt, take the type of the last one 14875 // as the type of the stmtexpr. 14876 QualType Ty = Context.VoidTy; 14877 bool StmtExprMayBindToTemp = false; 14878 if (!Compound->body_empty()) { 14879 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14880 if (const auto *LastStmt = 14881 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14882 if (const Expr *Value = LastStmt->getExprStmt()) { 14883 StmtExprMayBindToTemp = true; 14884 Ty = Value->getType(); 14885 } 14886 } 14887 } 14888 14889 // FIXME: Check that expression type is complete/non-abstract; statement 14890 // expressions are not lvalues. 14891 Expr *ResStmtExpr = 14892 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14893 if (StmtExprMayBindToTemp) 14894 return MaybeBindToTemporary(ResStmtExpr); 14895 return ResStmtExpr; 14896 } 14897 14898 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14899 if (ER.isInvalid()) 14900 return ExprError(); 14901 14902 // Do function/array conversion on the last expression, but not 14903 // lvalue-to-rvalue. However, initialize an unqualified type. 14904 ER = DefaultFunctionArrayConversion(ER.get()); 14905 if (ER.isInvalid()) 14906 return ExprError(); 14907 Expr *E = ER.get(); 14908 14909 if (E->isTypeDependent()) 14910 return E; 14911 14912 // In ARC, if the final expression ends in a consume, splice 14913 // the consume out and bind it later. In the alternate case 14914 // (when dealing with a retainable type), the result 14915 // initialization will create a produce. In both cases the 14916 // result will be +1, and we'll need to balance that out with 14917 // a bind. 14918 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14919 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14920 return Cast->getSubExpr(); 14921 14922 // FIXME: Provide a better location for the initialization. 14923 return PerformCopyInitialization( 14924 InitializedEntity::InitializeStmtExprResult( 14925 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14926 SourceLocation(), E); 14927 } 14928 14929 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14930 TypeSourceInfo *TInfo, 14931 ArrayRef<OffsetOfComponent> Components, 14932 SourceLocation RParenLoc) { 14933 QualType ArgTy = TInfo->getType(); 14934 bool Dependent = ArgTy->isDependentType(); 14935 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14936 14937 // We must have at least one component that refers to the type, and the first 14938 // one is known to be a field designator. Verify that the ArgTy represents 14939 // a struct/union/class. 14940 if (!Dependent && !ArgTy->isRecordType()) 14941 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14942 << ArgTy << TypeRange); 14943 14944 // Type must be complete per C99 7.17p3 because a declaring a variable 14945 // with an incomplete type would be ill-formed. 14946 if (!Dependent 14947 && RequireCompleteType(BuiltinLoc, ArgTy, 14948 diag::err_offsetof_incomplete_type, TypeRange)) 14949 return ExprError(); 14950 14951 bool DidWarnAboutNonPOD = false; 14952 QualType CurrentType = ArgTy; 14953 SmallVector<OffsetOfNode, 4> Comps; 14954 SmallVector<Expr*, 4> Exprs; 14955 for (const OffsetOfComponent &OC : Components) { 14956 if (OC.isBrackets) { 14957 // Offset of an array sub-field. TODO: Should we allow vector elements? 14958 if (!CurrentType->isDependentType()) { 14959 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14960 if(!AT) 14961 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14962 << CurrentType); 14963 CurrentType = AT->getElementType(); 14964 } else 14965 CurrentType = Context.DependentTy; 14966 14967 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14968 if (IdxRval.isInvalid()) 14969 return ExprError(); 14970 Expr *Idx = IdxRval.get(); 14971 14972 // The expression must be an integral expression. 14973 // FIXME: An integral constant expression? 14974 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14975 !Idx->getType()->isIntegerType()) 14976 return ExprError( 14977 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14978 << Idx->getSourceRange()); 14979 14980 // Record this array index. 14981 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14982 Exprs.push_back(Idx); 14983 continue; 14984 } 14985 14986 // Offset of a field. 14987 if (CurrentType->isDependentType()) { 14988 // We have the offset of a field, but we can't look into the dependent 14989 // type. Just record the identifier of the field. 14990 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14991 CurrentType = Context.DependentTy; 14992 continue; 14993 } 14994 14995 // We need to have a complete type to look into. 14996 if (RequireCompleteType(OC.LocStart, CurrentType, 14997 diag::err_offsetof_incomplete_type)) 14998 return ExprError(); 14999 15000 // Look for the designated field. 15001 const RecordType *RC = CurrentType->getAs<RecordType>(); 15002 if (!RC) 15003 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15004 << CurrentType); 15005 RecordDecl *RD = RC->getDecl(); 15006 15007 // C++ [lib.support.types]p5: 15008 // The macro offsetof accepts a restricted set of type arguments in this 15009 // International Standard. type shall be a POD structure or a POD union 15010 // (clause 9). 15011 // C++11 [support.types]p4: 15012 // If type is not a standard-layout class (Clause 9), the results are 15013 // undefined. 15014 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15015 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15016 unsigned DiagID = 15017 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15018 : diag::ext_offsetof_non_pod_type; 15019 15020 if (!IsSafe && !DidWarnAboutNonPOD && 15021 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15022 PDiag(DiagID) 15023 << SourceRange(Components[0].LocStart, OC.LocEnd) 15024 << CurrentType)) 15025 DidWarnAboutNonPOD = true; 15026 } 15027 15028 // Look for the field. 15029 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15030 LookupQualifiedName(R, RD); 15031 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15032 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15033 if (!MemberDecl) { 15034 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15035 MemberDecl = IndirectMemberDecl->getAnonField(); 15036 } 15037 15038 if (!MemberDecl) 15039 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15040 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15041 OC.LocEnd)); 15042 15043 // C99 7.17p3: 15044 // (If the specified member is a bit-field, the behavior is undefined.) 15045 // 15046 // We diagnose this as an error. 15047 if (MemberDecl->isBitField()) { 15048 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15049 << MemberDecl->getDeclName() 15050 << SourceRange(BuiltinLoc, RParenLoc); 15051 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15052 return ExprError(); 15053 } 15054 15055 RecordDecl *Parent = MemberDecl->getParent(); 15056 if (IndirectMemberDecl) 15057 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15058 15059 // If the member was found in a base class, introduce OffsetOfNodes for 15060 // the base class indirections. 15061 CXXBasePaths Paths; 15062 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15063 Paths)) { 15064 if (Paths.getDetectedVirtual()) { 15065 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15066 << MemberDecl->getDeclName() 15067 << SourceRange(BuiltinLoc, RParenLoc); 15068 return ExprError(); 15069 } 15070 15071 CXXBasePath &Path = Paths.front(); 15072 for (const CXXBasePathElement &B : Path) 15073 Comps.push_back(OffsetOfNode(B.Base)); 15074 } 15075 15076 if (IndirectMemberDecl) { 15077 for (auto *FI : IndirectMemberDecl->chain()) { 15078 assert(isa<FieldDecl>(FI)); 15079 Comps.push_back(OffsetOfNode(OC.LocStart, 15080 cast<FieldDecl>(FI), OC.LocEnd)); 15081 } 15082 } else 15083 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15084 15085 CurrentType = MemberDecl->getType().getNonReferenceType(); 15086 } 15087 15088 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15089 Comps, Exprs, RParenLoc); 15090 } 15091 15092 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15093 SourceLocation BuiltinLoc, 15094 SourceLocation TypeLoc, 15095 ParsedType ParsedArgTy, 15096 ArrayRef<OffsetOfComponent> Components, 15097 SourceLocation RParenLoc) { 15098 15099 TypeSourceInfo *ArgTInfo; 15100 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15101 if (ArgTy.isNull()) 15102 return ExprError(); 15103 15104 if (!ArgTInfo) 15105 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15106 15107 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15108 } 15109 15110 15111 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15112 Expr *CondExpr, 15113 Expr *LHSExpr, Expr *RHSExpr, 15114 SourceLocation RPLoc) { 15115 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15116 15117 ExprValueKind VK = VK_RValue; 15118 ExprObjectKind OK = OK_Ordinary; 15119 QualType resType; 15120 bool CondIsTrue = false; 15121 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15122 resType = Context.DependentTy; 15123 } else { 15124 // The conditional expression is required to be a constant expression. 15125 llvm::APSInt condEval(32); 15126 ExprResult CondICE = VerifyIntegerConstantExpression( 15127 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15128 if (CondICE.isInvalid()) 15129 return ExprError(); 15130 CondExpr = CondICE.get(); 15131 CondIsTrue = condEval.getZExtValue(); 15132 15133 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15134 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15135 15136 resType = ActiveExpr->getType(); 15137 VK = ActiveExpr->getValueKind(); 15138 OK = ActiveExpr->getObjectKind(); 15139 } 15140 15141 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15142 resType, VK, OK, RPLoc, CondIsTrue); 15143 } 15144 15145 //===----------------------------------------------------------------------===// 15146 // Clang Extensions. 15147 //===----------------------------------------------------------------------===// 15148 15149 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15150 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15151 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15152 15153 if (LangOpts.CPlusPlus) { 15154 MangleNumberingContext *MCtx; 15155 Decl *ManglingContextDecl; 15156 std::tie(MCtx, ManglingContextDecl) = 15157 getCurrentMangleNumberContext(Block->getDeclContext()); 15158 if (MCtx) { 15159 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15160 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15161 } 15162 } 15163 15164 PushBlockScope(CurScope, Block); 15165 CurContext->addDecl(Block); 15166 if (CurScope) 15167 PushDeclContext(CurScope, Block); 15168 else 15169 CurContext = Block; 15170 15171 getCurBlock()->HasImplicitReturnType = true; 15172 15173 // Enter a new evaluation context to insulate the block from any 15174 // cleanups from the enclosing full-expression. 15175 PushExpressionEvaluationContext( 15176 ExpressionEvaluationContext::PotentiallyEvaluated); 15177 } 15178 15179 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15180 Scope *CurScope) { 15181 assert(ParamInfo.getIdentifier() == nullptr && 15182 "block-id should have no identifier!"); 15183 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15184 BlockScopeInfo *CurBlock = getCurBlock(); 15185 15186 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15187 QualType T = Sig->getType(); 15188 15189 // FIXME: We should allow unexpanded parameter packs here, but that would, 15190 // in turn, make the block expression contain unexpanded parameter packs. 15191 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15192 // Drop the parameters. 15193 FunctionProtoType::ExtProtoInfo EPI; 15194 EPI.HasTrailingReturn = false; 15195 EPI.TypeQuals.addConst(); 15196 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15197 Sig = Context.getTrivialTypeSourceInfo(T); 15198 } 15199 15200 // GetTypeForDeclarator always produces a function type for a block 15201 // literal signature. Furthermore, it is always a FunctionProtoType 15202 // unless the function was written with a typedef. 15203 assert(T->isFunctionType() && 15204 "GetTypeForDeclarator made a non-function block signature"); 15205 15206 // Look for an explicit signature in that function type. 15207 FunctionProtoTypeLoc ExplicitSignature; 15208 15209 if ((ExplicitSignature = Sig->getTypeLoc() 15210 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15211 15212 // Check whether that explicit signature was synthesized by 15213 // GetTypeForDeclarator. If so, don't save that as part of the 15214 // written signature. 15215 if (ExplicitSignature.getLocalRangeBegin() == 15216 ExplicitSignature.getLocalRangeEnd()) { 15217 // This would be much cheaper if we stored TypeLocs instead of 15218 // TypeSourceInfos. 15219 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15220 unsigned Size = Result.getFullDataSize(); 15221 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15222 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15223 15224 ExplicitSignature = FunctionProtoTypeLoc(); 15225 } 15226 } 15227 15228 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15229 CurBlock->FunctionType = T; 15230 15231 const auto *Fn = T->castAs<FunctionType>(); 15232 QualType RetTy = Fn->getReturnType(); 15233 bool isVariadic = 15234 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15235 15236 CurBlock->TheDecl->setIsVariadic(isVariadic); 15237 15238 // Context.DependentTy is used as a placeholder for a missing block 15239 // return type. TODO: what should we do with declarators like: 15240 // ^ * { ... } 15241 // If the answer is "apply template argument deduction".... 15242 if (RetTy != Context.DependentTy) { 15243 CurBlock->ReturnType = RetTy; 15244 CurBlock->TheDecl->setBlockMissingReturnType(false); 15245 CurBlock->HasImplicitReturnType = false; 15246 } 15247 15248 // Push block parameters from the declarator if we had them. 15249 SmallVector<ParmVarDecl*, 8> Params; 15250 if (ExplicitSignature) { 15251 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15252 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15253 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15254 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15255 // Diagnose this as an extension in C17 and earlier. 15256 if (!getLangOpts().C2x) 15257 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15258 } 15259 Params.push_back(Param); 15260 } 15261 15262 // Fake up parameter variables if we have a typedef, like 15263 // ^ fntype { ... } 15264 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15265 for (const auto &I : Fn->param_types()) { 15266 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15267 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15268 Params.push_back(Param); 15269 } 15270 } 15271 15272 // Set the parameters on the block decl. 15273 if (!Params.empty()) { 15274 CurBlock->TheDecl->setParams(Params); 15275 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15276 /*CheckParameterNames=*/false); 15277 } 15278 15279 // Finally we can process decl attributes. 15280 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15281 15282 // Put the parameter variables in scope. 15283 for (auto AI : CurBlock->TheDecl->parameters()) { 15284 AI->setOwningFunction(CurBlock->TheDecl); 15285 15286 // If this has an identifier, add it to the scope stack. 15287 if (AI->getIdentifier()) { 15288 CheckShadow(CurBlock->TheScope, AI); 15289 15290 PushOnScopeChains(AI, CurBlock->TheScope); 15291 } 15292 } 15293 } 15294 15295 /// ActOnBlockError - If there is an error parsing a block, this callback 15296 /// is invoked to pop the information about the block from the action impl. 15297 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15298 // Leave the expression-evaluation context. 15299 DiscardCleanupsInEvaluationContext(); 15300 PopExpressionEvaluationContext(); 15301 15302 // Pop off CurBlock, handle nested blocks. 15303 PopDeclContext(); 15304 PopFunctionScopeInfo(); 15305 } 15306 15307 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15308 /// literal was successfully completed. ^(int x){...} 15309 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15310 Stmt *Body, Scope *CurScope) { 15311 // If blocks are disabled, emit an error. 15312 if (!LangOpts.Blocks) 15313 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15314 15315 // Leave the expression-evaluation context. 15316 if (hasAnyUnrecoverableErrorsInThisFunction()) 15317 DiscardCleanupsInEvaluationContext(); 15318 assert(!Cleanup.exprNeedsCleanups() && 15319 "cleanups within block not correctly bound!"); 15320 PopExpressionEvaluationContext(); 15321 15322 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15323 BlockDecl *BD = BSI->TheDecl; 15324 15325 if (BSI->HasImplicitReturnType) 15326 deduceClosureReturnType(*BSI); 15327 15328 QualType RetTy = Context.VoidTy; 15329 if (!BSI->ReturnType.isNull()) 15330 RetTy = BSI->ReturnType; 15331 15332 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15333 QualType BlockTy; 15334 15335 // If the user wrote a function type in some form, try to use that. 15336 if (!BSI->FunctionType.isNull()) { 15337 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15338 15339 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15340 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15341 15342 // Turn protoless block types into nullary block types. 15343 if (isa<FunctionNoProtoType>(FTy)) { 15344 FunctionProtoType::ExtProtoInfo EPI; 15345 EPI.ExtInfo = Ext; 15346 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15347 15348 // Otherwise, if we don't need to change anything about the function type, 15349 // preserve its sugar structure. 15350 } else if (FTy->getReturnType() == RetTy && 15351 (!NoReturn || FTy->getNoReturnAttr())) { 15352 BlockTy = BSI->FunctionType; 15353 15354 // Otherwise, make the minimal modifications to the function type. 15355 } else { 15356 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15357 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15358 EPI.TypeQuals = Qualifiers(); 15359 EPI.ExtInfo = Ext; 15360 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15361 } 15362 15363 // If we don't have a function type, just build one from nothing. 15364 } else { 15365 FunctionProtoType::ExtProtoInfo EPI; 15366 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15367 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15368 } 15369 15370 DiagnoseUnusedParameters(BD->parameters()); 15371 BlockTy = Context.getBlockPointerType(BlockTy); 15372 15373 // If needed, diagnose invalid gotos and switches in the block. 15374 if (getCurFunction()->NeedsScopeChecking() && 15375 !PP.isCodeCompletionEnabled()) 15376 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15377 15378 BD->setBody(cast<CompoundStmt>(Body)); 15379 15380 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15381 DiagnoseUnguardedAvailabilityViolations(BD); 15382 15383 // Try to apply the named return value optimization. We have to check again 15384 // if we can do this, though, because blocks keep return statements around 15385 // to deduce an implicit return type. 15386 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15387 !BD->isDependentContext()) 15388 computeNRVO(Body, BSI); 15389 15390 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15391 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15392 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15393 NTCUK_Destruct|NTCUK_Copy); 15394 15395 PopDeclContext(); 15396 15397 // Pop the block scope now but keep it alive to the end of this function. 15398 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15399 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15400 15401 // Set the captured variables on the block. 15402 SmallVector<BlockDecl::Capture, 4> Captures; 15403 for (Capture &Cap : BSI->Captures) { 15404 if (Cap.isInvalid() || Cap.isThisCapture()) 15405 continue; 15406 15407 VarDecl *Var = Cap.getVariable(); 15408 Expr *CopyExpr = nullptr; 15409 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15410 if (const RecordType *Record = 15411 Cap.getCaptureType()->getAs<RecordType>()) { 15412 // The capture logic needs the destructor, so make sure we mark it. 15413 // Usually this is unnecessary because most local variables have 15414 // their destructors marked at declaration time, but parameters are 15415 // an exception because it's technically only the call site that 15416 // actually requires the destructor. 15417 if (isa<ParmVarDecl>(Var)) 15418 FinalizeVarWithDestructor(Var, Record); 15419 15420 // Enter a separate potentially-evaluated context while building block 15421 // initializers to isolate their cleanups from those of the block 15422 // itself. 15423 // FIXME: Is this appropriate even when the block itself occurs in an 15424 // unevaluated operand? 15425 EnterExpressionEvaluationContext EvalContext( 15426 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15427 15428 SourceLocation Loc = Cap.getLocation(); 15429 15430 ExprResult Result = BuildDeclarationNameExpr( 15431 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15432 15433 // According to the blocks spec, the capture of a variable from 15434 // the stack requires a const copy constructor. This is not true 15435 // of the copy/move done to move a __block variable to the heap. 15436 if (!Result.isInvalid() && 15437 !Result.get()->getType().isConstQualified()) { 15438 Result = ImpCastExprToType(Result.get(), 15439 Result.get()->getType().withConst(), 15440 CK_NoOp, VK_LValue); 15441 } 15442 15443 if (!Result.isInvalid()) { 15444 Result = PerformCopyInitialization( 15445 InitializedEntity::InitializeBlock(Var->getLocation(), 15446 Cap.getCaptureType(), false), 15447 Loc, Result.get()); 15448 } 15449 15450 // Build a full-expression copy expression if initialization 15451 // succeeded and used a non-trivial constructor. Recover from 15452 // errors by pretending that the copy isn't necessary. 15453 if (!Result.isInvalid() && 15454 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15455 ->isTrivial()) { 15456 Result = MaybeCreateExprWithCleanups(Result); 15457 CopyExpr = Result.get(); 15458 } 15459 } 15460 } 15461 15462 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15463 CopyExpr); 15464 Captures.push_back(NewCap); 15465 } 15466 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15467 15468 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15469 15470 // If the block isn't obviously global, i.e. it captures anything at 15471 // all, then we need to do a few things in the surrounding context: 15472 if (Result->getBlockDecl()->hasCaptures()) { 15473 // First, this expression has a new cleanup object. 15474 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15475 Cleanup.setExprNeedsCleanups(true); 15476 15477 // It also gets a branch-protected scope if any of the captured 15478 // variables needs destruction. 15479 for (const auto &CI : Result->getBlockDecl()->captures()) { 15480 const VarDecl *var = CI.getVariable(); 15481 if (var->getType().isDestructedType() != QualType::DK_none) { 15482 setFunctionHasBranchProtectedScope(); 15483 break; 15484 } 15485 } 15486 } 15487 15488 if (getCurFunction()) 15489 getCurFunction()->addBlock(BD); 15490 15491 return Result; 15492 } 15493 15494 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15495 SourceLocation RPLoc) { 15496 TypeSourceInfo *TInfo; 15497 GetTypeFromParser(Ty, &TInfo); 15498 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15499 } 15500 15501 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15502 Expr *E, TypeSourceInfo *TInfo, 15503 SourceLocation RPLoc) { 15504 Expr *OrigExpr = E; 15505 bool IsMS = false; 15506 15507 // CUDA device code does not support varargs. 15508 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15509 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15510 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15511 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15512 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15513 } 15514 } 15515 15516 // NVPTX does not support va_arg expression. 15517 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15518 Context.getTargetInfo().getTriple().isNVPTX()) 15519 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15520 15521 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15522 // as Microsoft ABI on an actual Microsoft platform, where 15523 // __builtin_ms_va_list and __builtin_va_list are the same.) 15524 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15525 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15526 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15527 if (Context.hasSameType(MSVaListType, E->getType())) { 15528 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15529 return ExprError(); 15530 IsMS = true; 15531 } 15532 } 15533 15534 // Get the va_list type 15535 QualType VaListType = Context.getBuiltinVaListType(); 15536 if (!IsMS) { 15537 if (VaListType->isArrayType()) { 15538 // Deal with implicit array decay; for example, on x86-64, 15539 // va_list is an array, but it's supposed to decay to 15540 // a pointer for va_arg. 15541 VaListType = Context.getArrayDecayedType(VaListType); 15542 // Make sure the input expression also decays appropriately. 15543 ExprResult Result = UsualUnaryConversions(E); 15544 if (Result.isInvalid()) 15545 return ExprError(); 15546 E = Result.get(); 15547 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15548 // If va_list is a record type and we are compiling in C++ mode, 15549 // check the argument using reference binding. 15550 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15551 Context, Context.getLValueReferenceType(VaListType), false); 15552 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15553 if (Init.isInvalid()) 15554 return ExprError(); 15555 E = Init.getAs<Expr>(); 15556 } else { 15557 // Otherwise, the va_list argument must be an l-value because 15558 // it is modified by va_arg. 15559 if (!E->isTypeDependent() && 15560 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15561 return ExprError(); 15562 } 15563 } 15564 15565 if (!IsMS && !E->isTypeDependent() && 15566 !Context.hasSameType(VaListType, E->getType())) 15567 return ExprError( 15568 Diag(E->getBeginLoc(), 15569 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15570 << OrigExpr->getType() << E->getSourceRange()); 15571 15572 if (!TInfo->getType()->isDependentType()) { 15573 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15574 diag::err_second_parameter_to_va_arg_incomplete, 15575 TInfo->getTypeLoc())) 15576 return ExprError(); 15577 15578 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15579 TInfo->getType(), 15580 diag::err_second_parameter_to_va_arg_abstract, 15581 TInfo->getTypeLoc())) 15582 return ExprError(); 15583 15584 if (!TInfo->getType().isPODType(Context)) { 15585 Diag(TInfo->getTypeLoc().getBeginLoc(), 15586 TInfo->getType()->isObjCLifetimeType() 15587 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15588 : diag::warn_second_parameter_to_va_arg_not_pod) 15589 << TInfo->getType() 15590 << TInfo->getTypeLoc().getSourceRange(); 15591 } 15592 15593 // Check for va_arg where arguments of the given type will be promoted 15594 // (i.e. this va_arg is guaranteed to have undefined behavior). 15595 QualType PromoteType; 15596 if (TInfo->getType()->isPromotableIntegerType()) { 15597 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15598 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15599 PromoteType = QualType(); 15600 } 15601 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15602 PromoteType = Context.DoubleTy; 15603 if (!PromoteType.isNull()) 15604 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15605 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15606 << TInfo->getType() 15607 << PromoteType 15608 << TInfo->getTypeLoc().getSourceRange()); 15609 } 15610 15611 QualType T = TInfo->getType().getNonLValueExprType(Context); 15612 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15613 } 15614 15615 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15616 // The type of __null will be int or long, depending on the size of 15617 // pointers on the target. 15618 QualType Ty; 15619 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15620 if (pw == Context.getTargetInfo().getIntWidth()) 15621 Ty = Context.IntTy; 15622 else if (pw == Context.getTargetInfo().getLongWidth()) 15623 Ty = Context.LongTy; 15624 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15625 Ty = Context.LongLongTy; 15626 else { 15627 llvm_unreachable("I don't know size of pointer!"); 15628 } 15629 15630 return new (Context) GNUNullExpr(Ty, TokenLoc); 15631 } 15632 15633 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15634 SourceLocation BuiltinLoc, 15635 SourceLocation RPLoc) { 15636 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15637 } 15638 15639 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15640 SourceLocation BuiltinLoc, 15641 SourceLocation RPLoc, 15642 DeclContext *ParentContext) { 15643 return new (Context) 15644 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15645 } 15646 15647 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15648 bool Diagnose) { 15649 if (!getLangOpts().ObjC) 15650 return false; 15651 15652 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15653 if (!PT) 15654 return false; 15655 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15656 15657 // Ignore any parens, implicit casts (should only be 15658 // array-to-pointer decays), and not-so-opaque values. The last is 15659 // important for making this trigger for property assignments. 15660 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15661 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15662 if (OV->getSourceExpr()) 15663 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15664 15665 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15666 if (!PT->isObjCIdType() && 15667 !(ID && ID->getIdentifier()->isStr("NSString"))) 15668 return false; 15669 if (!SL->isAscii()) 15670 return false; 15671 15672 if (Diagnose) { 15673 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15674 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15675 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15676 } 15677 return true; 15678 } 15679 15680 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15681 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15682 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15683 !SrcExpr->isNullPointerConstant( 15684 getASTContext(), Expr::NPC_NeverValueDependent)) { 15685 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15686 return false; 15687 if (Diagnose) { 15688 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15689 << /*number*/1 15690 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15691 Expr *NumLit = 15692 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15693 if (NumLit) 15694 Exp = NumLit; 15695 } 15696 return true; 15697 } 15698 15699 return false; 15700 } 15701 15702 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15703 const Expr *SrcExpr) { 15704 if (!DstType->isFunctionPointerType() || 15705 !SrcExpr->getType()->isFunctionType()) 15706 return false; 15707 15708 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15709 if (!DRE) 15710 return false; 15711 15712 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15713 if (!FD) 15714 return false; 15715 15716 return !S.checkAddressOfFunctionIsAvailable(FD, 15717 /*Complain=*/true, 15718 SrcExpr->getBeginLoc()); 15719 } 15720 15721 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15722 SourceLocation Loc, 15723 QualType DstType, QualType SrcType, 15724 Expr *SrcExpr, AssignmentAction Action, 15725 bool *Complained) { 15726 if (Complained) 15727 *Complained = false; 15728 15729 // Decode the result (notice that AST's are still created for extensions). 15730 bool CheckInferredResultType = false; 15731 bool isInvalid = false; 15732 unsigned DiagKind = 0; 15733 ConversionFixItGenerator ConvHints; 15734 bool MayHaveConvFixit = false; 15735 bool MayHaveFunctionDiff = false; 15736 const ObjCInterfaceDecl *IFace = nullptr; 15737 const ObjCProtocolDecl *PDecl = nullptr; 15738 15739 switch (ConvTy) { 15740 case Compatible: 15741 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15742 return false; 15743 15744 case PointerToInt: 15745 if (getLangOpts().CPlusPlus) { 15746 DiagKind = diag::err_typecheck_convert_pointer_int; 15747 isInvalid = true; 15748 } else { 15749 DiagKind = diag::ext_typecheck_convert_pointer_int; 15750 } 15751 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15752 MayHaveConvFixit = true; 15753 break; 15754 case IntToPointer: 15755 if (getLangOpts().CPlusPlus) { 15756 DiagKind = diag::err_typecheck_convert_int_pointer; 15757 isInvalid = true; 15758 } else { 15759 DiagKind = diag::ext_typecheck_convert_int_pointer; 15760 } 15761 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15762 MayHaveConvFixit = true; 15763 break; 15764 case IncompatibleFunctionPointer: 15765 if (getLangOpts().CPlusPlus) { 15766 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15767 isInvalid = true; 15768 } else { 15769 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15770 } 15771 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15772 MayHaveConvFixit = true; 15773 break; 15774 case IncompatiblePointer: 15775 if (Action == AA_Passing_CFAudited) { 15776 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15777 } else if (getLangOpts().CPlusPlus) { 15778 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15779 isInvalid = true; 15780 } else { 15781 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15782 } 15783 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15784 SrcType->isObjCObjectPointerType(); 15785 if (!CheckInferredResultType) { 15786 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15787 } else if (CheckInferredResultType) { 15788 SrcType = SrcType.getUnqualifiedType(); 15789 DstType = DstType.getUnqualifiedType(); 15790 } 15791 MayHaveConvFixit = true; 15792 break; 15793 case IncompatiblePointerSign: 15794 if (getLangOpts().CPlusPlus) { 15795 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15796 isInvalid = true; 15797 } else { 15798 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15799 } 15800 break; 15801 case FunctionVoidPointer: 15802 if (getLangOpts().CPlusPlus) { 15803 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15804 isInvalid = true; 15805 } else { 15806 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15807 } 15808 break; 15809 case IncompatiblePointerDiscardsQualifiers: { 15810 // Perform array-to-pointer decay if necessary. 15811 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15812 15813 isInvalid = true; 15814 15815 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15816 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15817 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15818 DiagKind = diag::err_typecheck_incompatible_address_space; 15819 break; 15820 15821 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15822 DiagKind = diag::err_typecheck_incompatible_ownership; 15823 break; 15824 } 15825 15826 llvm_unreachable("unknown error case for discarding qualifiers!"); 15827 // fallthrough 15828 } 15829 case CompatiblePointerDiscardsQualifiers: 15830 // If the qualifiers lost were because we were applying the 15831 // (deprecated) C++ conversion from a string literal to a char* 15832 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15833 // Ideally, this check would be performed in 15834 // checkPointerTypesForAssignment. However, that would require a 15835 // bit of refactoring (so that the second argument is an 15836 // expression, rather than a type), which should be done as part 15837 // of a larger effort to fix checkPointerTypesForAssignment for 15838 // C++ semantics. 15839 if (getLangOpts().CPlusPlus && 15840 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15841 return false; 15842 if (getLangOpts().CPlusPlus) { 15843 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15844 isInvalid = true; 15845 } else { 15846 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15847 } 15848 15849 break; 15850 case IncompatibleNestedPointerQualifiers: 15851 if (getLangOpts().CPlusPlus) { 15852 isInvalid = true; 15853 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15854 } else { 15855 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15856 } 15857 break; 15858 case IncompatibleNestedPointerAddressSpaceMismatch: 15859 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15860 isInvalid = true; 15861 break; 15862 case IntToBlockPointer: 15863 DiagKind = diag::err_int_to_block_pointer; 15864 isInvalid = true; 15865 break; 15866 case IncompatibleBlockPointer: 15867 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15868 isInvalid = true; 15869 break; 15870 case IncompatibleObjCQualifiedId: { 15871 if (SrcType->isObjCQualifiedIdType()) { 15872 const ObjCObjectPointerType *srcOPT = 15873 SrcType->castAs<ObjCObjectPointerType>(); 15874 for (auto *srcProto : srcOPT->quals()) { 15875 PDecl = srcProto; 15876 break; 15877 } 15878 if (const ObjCInterfaceType *IFaceT = 15879 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15880 IFace = IFaceT->getDecl(); 15881 } 15882 else if (DstType->isObjCQualifiedIdType()) { 15883 const ObjCObjectPointerType *dstOPT = 15884 DstType->castAs<ObjCObjectPointerType>(); 15885 for (auto *dstProto : dstOPT->quals()) { 15886 PDecl = dstProto; 15887 break; 15888 } 15889 if (const ObjCInterfaceType *IFaceT = 15890 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15891 IFace = IFaceT->getDecl(); 15892 } 15893 if (getLangOpts().CPlusPlus) { 15894 DiagKind = diag::err_incompatible_qualified_id; 15895 isInvalid = true; 15896 } else { 15897 DiagKind = diag::warn_incompatible_qualified_id; 15898 } 15899 break; 15900 } 15901 case IncompatibleVectors: 15902 if (getLangOpts().CPlusPlus) { 15903 DiagKind = diag::err_incompatible_vectors; 15904 isInvalid = true; 15905 } else { 15906 DiagKind = diag::warn_incompatible_vectors; 15907 } 15908 break; 15909 case IncompatibleObjCWeakRef: 15910 DiagKind = diag::err_arc_weak_unavailable_assign; 15911 isInvalid = true; 15912 break; 15913 case Incompatible: 15914 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15915 if (Complained) 15916 *Complained = true; 15917 return true; 15918 } 15919 15920 DiagKind = diag::err_typecheck_convert_incompatible; 15921 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15922 MayHaveConvFixit = true; 15923 isInvalid = true; 15924 MayHaveFunctionDiff = true; 15925 break; 15926 } 15927 15928 QualType FirstType, SecondType; 15929 switch (Action) { 15930 case AA_Assigning: 15931 case AA_Initializing: 15932 // The destination type comes first. 15933 FirstType = DstType; 15934 SecondType = SrcType; 15935 break; 15936 15937 case AA_Returning: 15938 case AA_Passing: 15939 case AA_Passing_CFAudited: 15940 case AA_Converting: 15941 case AA_Sending: 15942 case AA_Casting: 15943 // The source type comes first. 15944 FirstType = SrcType; 15945 SecondType = DstType; 15946 break; 15947 } 15948 15949 PartialDiagnostic FDiag = PDiag(DiagKind); 15950 if (Action == AA_Passing_CFAudited) 15951 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15952 else 15953 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15954 15955 // If we can fix the conversion, suggest the FixIts. 15956 if (!ConvHints.isNull()) { 15957 for (FixItHint &H : ConvHints.Hints) 15958 FDiag << H; 15959 } 15960 15961 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15962 15963 if (MayHaveFunctionDiff) 15964 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15965 15966 Diag(Loc, FDiag); 15967 if ((DiagKind == diag::warn_incompatible_qualified_id || 15968 DiagKind == diag::err_incompatible_qualified_id) && 15969 PDecl && IFace && !IFace->hasDefinition()) 15970 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15971 << IFace << PDecl; 15972 15973 if (SecondType == Context.OverloadTy) 15974 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15975 FirstType, /*TakingAddress=*/true); 15976 15977 if (CheckInferredResultType) 15978 EmitRelatedResultTypeNote(SrcExpr); 15979 15980 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15981 EmitRelatedResultTypeNoteForReturn(DstType); 15982 15983 if (Complained) 15984 *Complained = true; 15985 return isInvalid; 15986 } 15987 15988 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15989 llvm::APSInt *Result, 15990 AllowFoldKind CanFold) { 15991 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15992 public: 15993 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 15994 QualType T) override { 15995 return S.Diag(Loc, diag::err_ice_not_integral) 15996 << T << S.LangOpts.CPlusPlus; 15997 } 15998 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 15999 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16000 } 16001 } Diagnoser; 16002 16003 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16004 } 16005 16006 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16007 llvm::APSInt *Result, 16008 unsigned DiagID, 16009 AllowFoldKind CanFold) { 16010 class IDDiagnoser : public VerifyICEDiagnoser { 16011 unsigned DiagID; 16012 16013 public: 16014 IDDiagnoser(unsigned DiagID) 16015 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16016 16017 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16018 return S.Diag(Loc, DiagID); 16019 } 16020 } Diagnoser(DiagID); 16021 16022 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16023 } 16024 16025 Sema::SemaDiagnosticBuilder 16026 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16027 QualType T) { 16028 return diagnoseNotICE(S, Loc); 16029 } 16030 16031 Sema::SemaDiagnosticBuilder 16032 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16033 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16034 } 16035 16036 ExprResult 16037 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16038 VerifyICEDiagnoser &Diagnoser, 16039 AllowFoldKind CanFold) { 16040 SourceLocation DiagLoc = E->getBeginLoc(); 16041 16042 if (getLangOpts().CPlusPlus11) { 16043 // C++11 [expr.const]p5: 16044 // If an expression of literal class type is used in a context where an 16045 // integral constant expression is required, then that class type shall 16046 // have a single non-explicit conversion function to an integral or 16047 // unscoped enumeration type 16048 ExprResult Converted; 16049 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16050 VerifyICEDiagnoser &BaseDiagnoser; 16051 public: 16052 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16053 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16054 BaseDiagnoser.Suppress, true), 16055 BaseDiagnoser(BaseDiagnoser) {} 16056 16057 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16058 QualType T) override { 16059 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16060 } 16061 16062 SemaDiagnosticBuilder diagnoseIncomplete( 16063 Sema &S, SourceLocation Loc, QualType T) override { 16064 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16065 } 16066 16067 SemaDiagnosticBuilder diagnoseExplicitConv( 16068 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16069 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16070 } 16071 16072 SemaDiagnosticBuilder noteExplicitConv( 16073 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16074 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16075 << ConvTy->isEnumeralType() << ConvTy; 16076 } 16077 16078 SemaDiagnosticBuilder diagnoseAmbiguous( 16079 Sema &S, SourceLocation Loc, QualType T) override { 16080 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16081 } 16082 16083 SemaDiagnosticBuilder noteAmbiguous( 16084 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16085 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16086 << ConvTy->isEnumeralType() << ConvTy; 16087 } 16088 16089 SemaDiagnosticBuilder diagnoseConversion( 16090 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16091 llvm_unreachable("conversion functions are permitted"); 16092 } 16093 } ConvertDiagnoser(Diagnoser); 16094 16095 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16096 ConvertDiagnoser); 16097 if (Converted.isInvalid()) 16098 return Converted; 16099 E = Converted.get(); 16100 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16101 return ExprError(); 16102 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16103 // An ICE must be of integral or unscoped enumeration type. 16104 if (!Diagnoser.Suppress) 16105 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16106 << E->getSourceRange(); 16107 return ExprError(); 16108 } 16109 16110 ExprResult RValueExpr = DefaultLvalueConversion(E); 16111 if (RValueExpr.isInvalid()) 16112 return ExprError(); 16113 16114 E = RValueExpr.get(); 16115 16116 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16117 // in the non-ICE case. 16118 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16119 if (Result) 16120 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16121 if (!isa<ConstantExpr>(E)) 16122 E = ConstantExpr::Create(Context, E); 16123 return E; 16124 } 16125 16126 Expr::EvalResult EvalResult; 16127 SmallVector<PartialDiagnosticAt, 8> Notes; 16128 EvalResult.Diag = &Notes; 16129 16130 // Try to evaluate the expression, and produce diagnostics explaining why it's 16131 // not a constant expression as a side-effect. 16132 bool Folded = 16133 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16134 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16135 16136 if (!isa<ConstantExpr>(E)) 16137 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16138 16139 // In C++11, we can rely on diagnostics being produced for any expression 16140 // which is not a constant expression. If no diagnostics were produced, then 16141 // this is a constant expression. 16142 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16143 if (Result) 16144 *Result = EvalResult.Val.getInt(); 16145 return E; 16146 } 16147 16148 // If our only note is the usual "invalid subexpression" note, just point 16149 // the caret at its location rather than producing an essentially 16150 // redundant note. 16151 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16152 diag::note_invalid_subexpr_in_const_expr) { 16153 DiagLoc = Notes[0].first; 16154 Notes.clear(); 16155 } 16156 16157 if (!Folded || !CanFold) { 16158 if (!Diagnoser.Suppress) { 16159 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16160 for (const PartialDiagnosticAt &Note : Notes) 16161 Diag(Note.first, Note.second); 16162 } 16163 16164 return ExprError(); 16165 } 16166 16167 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16168 for (const PartialDiagnosticAt &Note : Notes) 16169 Diag(Note.first, Note.second); 16170 16171 if (Result) 16172 *Result = EvalResult.Val.getInt(); 16173 return E; 16174 } 16175 16176 namespace { 16177 // Handle the case where we conclude a expression which we speculatively 16178 // considered to be unevaluated is actually evaluated. 16179 class TransformToPE : public TreeTransform<TransformToPE> { 16180 typedef TreeTransform<TransformToPE> BaseTransform; 16181 16182 public: 16183 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16184 16185 // Make sure we redo semantic analysis 16186 bool AlwaysRebuild() { return true; } 16187 bool ReplacingOriginal() { return true; } 16188 16189 // We need to special-case DeclRefExprs referring to FieldDecls which 16190 // are not part of a member pointer formation; normal TreeTransforming 16191 // doesn't catch this case because of the way we represent them in the AST. 16192 // FIXME: This is a bit ugly; is it really the best way to handle this 16193 // case? 16194 // 16195 // Error on DeclRefExprs referring to FieldDecls. 16196 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16197 if (isa<FieldDecl>(E->getDecl()) && 16198 !SemaRef.isUnevaluatedContext()) 16199 return SemaRef.Diag(E->getLocation(), 16200 diag::err_invalid_non_static_member_use) 16201 << E->getDecl() << E->getSourceRange(); 16202 16203 return BaseTransform::TransformDeclRefExpr(E); 16204 } 16205 16206 // Exception: filter out member pointer formation 16207 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16208 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16209 return E; 16210 16211 return BaseTransform::TransformUnaryOperator(E); 16212 } 16213 16214 // The body of a lambda-expression is in a separate expression evaluation 16215 // context so never needs to be transformed. 16216 // FIXME: Ideally we wouldn't transform the closure type either, and would 16217 // just recreate the capture expressions and lambda expression. 16218 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16219 return SkipLambdaBody(E, Body); 16220 } 16221 }; 16222 } 16223 16224 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16225 assert(isUnevaluatedContext() && 16226 "Should only transform unevaluated expressions"); 16227 ExprEvalContexts.back().Context = 16228 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16229 if (isUnevaluatedContext()) 16230 return E; 16231 return TransformToPE(*this).TransformExpr(E); 16232 } 16233 16234 void 16235 Sema::PushExpressionEvaluationContext( 16236 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16237 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16238 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16239 LambdaContextDecl, ExprContext); 16240 Cleanup.reset(); 16241 if (!MaybeODRUseExprs.empty()) 16242 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16243 } 16244 16245 void 16246 Sema::PushExpressionEvaluationContext( 16247 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16248 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16249 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16250 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16251 } 16252 16253 namespace { 16254 16255 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16256 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16257 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16258 if (E->getOpcode() == UO_Deref) 16259 return CheckPossibleDeref(S, E->getSubExpr()); 16260 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16261 return CheckPossibleDeref(S, E->getBase()); 16262 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16263 return CheckPossibleDeref(S, E->getBase()); 16264 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16265 QualType Inner; 16266 QualType Ty = E->getType(); 16267 if (const auto *Ptr = Ty->getAs<PointerType>()) 16268 Inner = Ptr->getPointeeType(); 16269 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16270 Inner = Arr->getElementType(); 16271 else 16272 return nullptr; 16273 16274 if (Inner->hasAttr(attr::NoDeref)) 16275 return E; 16276 } 16277 return nullptr; 16278 } 16279 16280 } // namespace 16281 16282 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16283 for (const Expr *E : Rec.PossibleDerefs) { 16284 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16285 if (DeclRef) { 16286 const ValueDecl *Decl = DeclRef->getDecl(); 16287 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16288 << Decl->getName() << E->getSourceRange(); 16289 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16290 } else { 16291 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16292 << E->getSourceRange(); 16293 } 16294 } 16295 Rec.PossibleDerefs.clear(); 16296 } 16297 16298 /// Check whether E, which is either a discarded-value expression or an 16299 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16300 /// and if so, remove it from the list of volatile-qualified assignments that 16301 /// we are going to warn are deprecated. 16302 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16303 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16304 return; 16305 16306 // Note: ignoring parens here is not justified by the standard rules, but 16307 // ignoring parentheses seems like a more reasonable approach, and this only 16308 // drives a deprecation warning so doesn't affect conformance. 16309 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16310 if (BO->getOpcode() == BO_Assign) { 16311 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16312 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16313 LHSs.end()); 16314 } 16315 } 16316 } 16317 16318 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16319 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16320 RebuildingImmediateInvocation) 16321 return E; 16322 16323 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16324 /// It's OK if this fails; we'll also remove this in 16325 /// HandleImmediateInvocations, but catching it here allows us to avoid 16326 /// walking the AST looking for it in simple cases. 16327 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16328 if (auto *DeclRef = 16329 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16330 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16331 16332 E = MaybeCreateExprWithCleanups(E); 16333 16334 ConstantExpr *Res = ConstantExpr::Create( 16335 getASTContext(), E.get(), 16336 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16337 getASTContext()), 16338 /*IsImmediateInvocation*/ true); 16339 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16340 return Res; 16341 } 16342 16343 static void EvaluateAndDiagnoseImmediateInvocation( 16344 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16345 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16346 Expr::EvalResult Eval; 16347 Eval.Diag = &Notes; 16348 ConstantExpr *CE = Candidate.getPointer(); 16349 bool Result = CE->EvaluateAsConstantExpr( 16350 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16351 if (!Result || !Notes.empty()) { 16352 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16353 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16354 InnerExpr = FunctionalCast->getSubExpr(); 16355 FunctionDecl *FD = nullptr; 16356 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16357 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16358 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16359 FD = Call->getConstructor(); 16360 else 16361 llvm_unreachable("unhandled decl kind"); 16362 assert(FD->isConsteval()); 16363 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16364 for (auto &Note : Notes) 16365 SemaRef.Diag(Note.first, Note.second); 16366 return; 16367 } 16368 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16369 } 16370 16371 static void RemoveNestedImmediateInvocation( 16372 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16373 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16374 struct ComplexRemove : TreeTransform<ComplexRemove> { 16375 using Base = TreeTransform<ComplexRemove>; 16376 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16377 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16378 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16379 CurrentII; 16380 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16381 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16382 SmallVector<Sema::ImmediateInvocationCandidate, 16383 4>::reverse_iterator Current) 16384 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16385 void RemoveImmediateInvocation(ConstantExpr* E) { 16386 auto It = std::find_if(CurrentII, IISet.rend(), 16387 [E](Sema::ImmediateInvocationCandidate Elem) { 16388 return Elem.getPointer() == E; 16389 }); 16390 assert(It != IISet.rend() && 16391 "ConstantExpr marked IsImmediateInvocation should " 16392 "be present"); 16393 It->setInt(1); // Mark as deleted 16394 } 16395 ExprResult TransformConstantExpr(ConstantExpr *E) { 16396 if (!E->isImmediateInvocation()) 16397 return Base::TransformConstantExpr(E); 16398 RemoveImmediateInvocation(E); 16399 return Base::TransformExpr(E->getSubExpr()); 16400 } 16401 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16402 /// we need to remove its DeclRefExpr from the DRSet. 16403 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16404 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16405 return Base::TransformCXXOperatorCallExpr(E); 16406 } 16407 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16408 /// here. 16409 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16410 if (!Init) 16411 return Init; 16412 /// ConstantExpr are the first layer of implicit node to be removed so if 16413 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16414 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16415 if (CE->isImmediateInvocation()) 16416 RemoveImmediateInvocation(CE); 16417 return Base::TransformInitializer(Init, NotCopyInit); 16418 } 16419 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16420 DRSet.erase(E); 16421 return E; 16422 } 16423 bool AlwaysRebuild() { return false; } 16424 bool ReplacingOriginal() { return true; } 16425 bool AllowSkippingCXXConstructExpr() { 16426 bool Res = AllowSkippingFirstCXXConstructExpr; 16427 AllowSkippingFirstCXXConstructExpr = true; 16428 return Res; 16429 } 16430 bool AllowSkippingFirstCXXConstructExpr = true; 16431 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16432 Rec.ImmediateInvocationCandidates, It); 16433 16434 /// CXXConstructExpr with a single argument are getting skipped by 16435 /// TreeTransform in some situtation because they could be implicit. This 16436 /// can only occur for the top-level CXXConstructExpr because it is used 16437 /// nowhere in the expression being transformed therefore will not be rebuilt. 16438 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16439 /// skipping the first CXXConstructExpr. 16440 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16441 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16442 16443 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16444 assert(Res.isUsable()); 16445 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16446 It->getPointer()->setSubExpr(Res.get()); 16447 } 16448 16449 static void 16450 HandleImmediateInvocations(Sema &SemaRef, 16451 Sema::ExpressionEvaluationContextRecord &Rec) { 16452 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16453 Rec.ReferenceToConsteval.size() == 0) || 16454 SemaRef.RebuildingImmediateInvocation) 16455 return; 16456 16457 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16458 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16459 /// need to remove ReferenceToConsteval in the immediate invocation. 16460 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16461 16462 /// Prevent sema calls during the tree transform from adding pointers that 16463 /// are already in the sets. 16464 llvm::SaveAndRestore<bool> DisableIITracking( 16465 SemaRef.RebuildingImmediateInvocation, true); 16466 16467 /// Prevent diagnostic during tree transfrom as they are duplicates 16468 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16469 16470 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16471 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16472 if (!It->getInt()) 16473 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16474 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16475 Rec.ReferenceToConsteval.size()) { 16476 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16477 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16478 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16479 bool VisitDeclRefExpr(DeclRefExpr *E) { 16480 DRSet.erase(E); 16481 return DRSet.size(); 16482 } 16483 } Visitor(Rec.ReferenceToConsteval); 16484 Visitor.TraverseStmt( 16485 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16486 } 16487 for (auto CE : Rec.ImmediateInvocationCandidates) 16488 if (!CE.getInt()) 16489 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16490 for (auto DR : Rec.ReferenceToConsteval) { 16491 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16492 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16493 << FD; 16494 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16495 } 16496 } 16497 16498 void Sema::PopExpressionEvaluationContext() { 16499 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16500 unsigned NumTypos = Rec.NumTypos; 16501 16502 if (!Rec.Lambdas.empty()) { 16503 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16504 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16505 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16506 unsigned D; 16507 if (Rec.isUnevaluated()) { 16508 // C++11 [expr.prim.lambda]p2: 16509 // A lambda-expression shall not appear in an unevaluated operand 16510 // (Clause 5). 16511 D = diag::err_lambda_unevaluated_operand; 16512 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16513 // C++1y [expr.const]p2: 16514 // A conditional-expression e is a core constant expression unless the 16515 // evaluation of e, following the rules of the abstract machine, would 16516 // evaluate [...] a lambda-expression. 16517 D = diag::err_lambda_in_constant_expression; 16518 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16519 // C++17 [expr.prim.lamda]p2: 16520 // A lambda-expression shall not appear [...] in a template-argument. 16521 D = diag::err_lambda_in_invalid_context; 16522 } else 16523 llvm_unreachable("Couldn't infer lambda error message."); 16524 16525 for (const auto *L : Rec.Lambdas) 16526 Diag(L->getBeginLoc(), D); 16527 } 16528 } 16529 16530 WarnOnPendingNoDerefs(Rec); 16531 HandleImmediateInvocations(*this, Rec); 16532 16533 // Warn on any volatile-qualified simple-assignments that are not discarded- 16534 // value expressions nor unevaluated operands (those cases get removed from 16535 // this list by CheckUnusedVolatileAssignment). 16536 for (auto *BO : Rec.VolatileAssignmentLHSs) 16537 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16538 << BO->getType(); 16539 16540 // When are coming out of an unevaluated context, clear out any 16541 // temporaries that we may have created as part of the evaluation of 16542 // the expression in that context: they aren't relevant because they 16543 // will never be constructed. 16544 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16545 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16546 ExprCleanupObjects.end()); 16547 Cleanup = Rec.ParentCleanup; 16548 CleanupVarDeclMarking(); 16549 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16550 // Otherwise, merge the contexts together. 16551 } else { 16552 Cleanup.mergeFrom(Rec.ParentCleanup); 16553 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16554 Rec.SavedMaybeODRUseExprs.end()); 16555 } 16556 16557 // Pop the current expression evaluation context off the stack. 16558 ExprEvalContexts.pop_back(); 16559 16560 // The global expression evaluation context record is never popped. 16561 ExprEvalContexts.back().NumTypos += NumTypos; 16562 } 16563 16564 void Sema::DiscardCleanupsInEvaluationContext() { 16565 ExprCleanupObjects.erase( 16566 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16567 ExprCleanupObjects.end()); 16568 Cleanup.reset(); 16569 MaybeODRUseExprs.clear(); 16570 } 16571 16572 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16573 ExprResult Result = CheckPlaceholderExpr(E); 16574 if (Result.isInvalid()) 16575 return ExprError(); 16576 E = Result.get(); 16577 if (!E->getType()->isVariablyModifiedType()) 16578 return E; 16579 return TransformToPotentiallyEvaluated(E); 16580 } 16581 16582 /// Are we in a context that is potentially constant evaluated per C++20 16583 /// [expr.const]p12? 16584 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16585 /// C++2a [expr.const]p12: 16586 // An expression or conversion is potentially constant evaluated if it is 16587 switch (SemaRef.ExprEvalContexts.back().Context) { 16588 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16589 // -- a manifestly constant-evaluated expression, 16590 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16591 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16592 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16593 // -- a potentially-evaluated expression, 16594 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16595 // -- an immediate subexpression of a braced-init-list, 16596 16597 // -- [FIXME] an expression of the form & cast-expression that occurs 16598 // within a templated entity 16599 // -- a subexpression of one of the above that is not a subexpression of 16600 // a nested unevaluated operand. 16601 return true; 16602 16603 case Sema::ExpressionEvaluationContext::Unevaluated: 16604 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16605 // Expressions in this context are never evaluated. 16606 return false; 16607 } 16608 llvm_unreachable("Invalid context"); 16609 } 16610 16611 /// Return true if this function has a calling convention that requires mangling 16612 /// in the size of the parameter pack. 16613 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16614 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16615 // we don't need parameter type sizes. 16616 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16617 if (!TT.isOSWindows() || !TT.isX86()) 16618 return false; 16619 16620 // If this is C++ and this isn't an extern "C" function, parameters do not 16621 // need to be complete. In this case, C++ mangling will apply, which doesn't 16622 // use the size of the parameters. 16623 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16624 return false; 16625 16626 // Stdcall, fastcall, and vectorcall need this special treatment. 16627 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16628 switch (CC) { 16629 case CC_X86StdCall: 16630 case CC_X86FastCall: 16631 case CC_X86VectorCall: 16632 return true; 16633 default: 16634 break; 16635 } 16636 return false; 16637 } 16638 16639 /// Require that all of the parameter types of function be complete. Normally, 16640 /// parameter types are only required to be complete when a function is called 16641 /// or defined, but to mangle functions with certain calling conventions, the 16642 /// mangler needs to know the size of the parameter list. In this situation, 16643 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16644 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16645 /// result in a linker error. Clang doesn't implement this behavior, and instead 16646 /// attempts to error at compile time. 16647 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16648 SourceLocation Loc) { 16649 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16650 FunctionDecl *FD; 16651 ParmVarDecl *Param; 16652 16653 public: 16654 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16655 : FD(FD), Param(Param) {} 16656 16657 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16658 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16659 StringRef CCName; 16660 switch (CC) { 16661 case CC_X86StdCall: 16662 CCName = "stdcall"; 16663 break; 16664 case CC_X86FastCall: 16665 CCName = "fastcall"; 16666 break; 16667 case CC_X86VectorCall: 16668 CCName = "vectorcall"; 16669 break; 16670 default: 16671 llvm_unreachable("CC does not need mangling"); 16672 } 16673 16674 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16675 << Param->getDeclName() << FD->getDeclName() << CCName; 16676 } 16677 }; 16678 16679 for (ParmVarDecl *Param : FD->parameters()) { 16680 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16681 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16682 } 16683 } 16684 16685 namespace { 16686 enum class OdrUseContext { 16687 /// Declarations in this context are not odr-used. 16688 None, 16689 /// Declarations in this context are formally odr-used, but this is a 16690 /// dependent context. 16691 Dependent, 16692 /// Declarations in this context are odr-used but not actually used (yet). 16693 FormallyOdrUsed, 16694 /// Declarations in this context are used. 16695 Used 16696 }; 16697 } 16698 16699 /// Are we within a context in which references to resolved functions or to 16700 /// variables result in odr-use? 16701 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16702 OdrUseContext Result; 16703 16704 switch (SemaRef.ExprEvalContexts.back().Context) { 16705 case Sema::ExpressionEvaluationContext::Unevaluated: 16706 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16707 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16708 return OdrUseContext::None; 16709 16710 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16711 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16712 Result = OdrUseContext::Used; 16713 break; 16714 16715 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16716 Result = OdrUseContext::FormallyOdrUsed; 16717 break; 16718 16719 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16720 // A default argument formally results in odr-use, but doesn't actually 16721 // result in a use in any real sense until it itself is used. 16722 Result = OdrUseContext::FormallyOdrUsed; 16723 break; 16724 } 16725 16726 if (SemaRef.CurContext->isDependentContext()) 16727 return OdrUseContext::Dependent; 16728 16729 return Result; 16730 } 16731 16732 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16733 if (!Func->isConstexpr()) 16734 return false; 16735 16736 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16737 return true; 16738 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16739 return CCD && CCD->getInheritedConstructor(); 16740 } 16741 16742 /// Mark a function referenced, and check whether it is odr-used 16743 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16744 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16745 bool MightBeOdrUse) { 16746 assert(Func && "No function?"); 16747 16748 Func->setReferenced(); 16749 16750 // Recursive functions aren't really used until they're used from some other 16751 // context. 16752 bool IsRecursiveCall = CurContext == Func; 16753 16754 // C++11 [basic.def.odr]p3: 16755 // A function whose name appears as a potentially-evaluated expression is 16756 // odr-used if it is the unique lookup result or the selected member of a 16757 // set of overloaded functions [...]. 16758 // 16759 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16760 // can just check that here. 16761 OdrUseContext OdrUse = 16762 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16763 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16764 OdrUse = OdrUseContext::FormallyOdrUsed; 16765 16766 // Trivial default constructors and destructors are never actually used. 16767 // FIXME: What about other special members? 16768 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16769 OdrUse == OdrUseContext::Used) { 16770 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16771 if (Constructor->isDefaultConstructor()) 16772 OdrUse = OdrUseContext::FormallyOdrUsed; 16773 if (isa<CXXDestructorDecl>(Func)) 16774 OdrUse = OdrUseContext::FormallyOdrUsed; 16775 } 16776 16777 // C++20 [expr.const]p12: 16778 // A function [...] is needed for constant evaluation if it is [...] a 16779 // constexpr function that is named by an expression that is potentially 16780 // constant evaluated 16781 bool NeededForConstantEvaluation = 16782 isPotentiallyConstantEvaluatedContext(*this) && 16783 isImplicitlyDefinableConstexprFunction(Func); 16784 16785 // Determine whether we require a function definition to exist, per 16786 // C++11 [temp.inst]p3: 16787 // Unless a function template specialization has been explicitly 16788 // instantiated or explicitly specialized, the function template 16789 // specialization is implicitly instantiated when the specialization is 16790 // referenced in a context that requires a function definition to exist. 16791 // C++20 [temp.inst]p7: 16792 // The existence of a definition of a [...] function is considered to 16793 // affect the semantics of the program if the [...] function is needed for 16794 // constant evaluation by an expression 16795 // C++20 [basic.def.odr]p10: 16796 // Every program shall contain exactly one definition of every non-inline 16797 // function or variable that is odr-used in that program outside of a 16798 // discarded statement 16799 // C++20 [special]p1: 16800 // The implementation will implicitly define [defaulted special members] 16801 // if they are odr-used or needed for constant evaluation. 16802 // 16803 // Note that we skip the implicit instantiation of templates that are only 16804 // used in unused default arguments or by recursive calls to themselves. 16805 // This is formally non-conforming, but seems reasonable in practice. 16806 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16807 NeededForConstantEvaluation); 16808 16809 // C++14 [temp.expl.spec]p6: 16810 // If a template [...] is explicitly specialized then that specialization 16811 // shall be declared before the first use of that specialization that would 16812 // cause an implicit instantiation to take place, in every translation unit 16813 // in which such a use occurs 16814 if (NeedDefinition && 16815 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16816 Func->getMemberSpecializationInfo())) 16817 checkSpecializationVisibility(Loc, Func); 16818 16819 if (getLangOpts().CUDA) 16820 CheckCUDACall(Loc, Func); 16821 16822 if (getLangOpts().SYCLIsDevice) 16823 checkSYCLDeviceFunction(Loc, Func); 16824 16825 // If we need a definition, try to create one. 16826 if (NeedDefinition && !Func->getBody()) { 16827 runWithSufficientStackSpace(Loc, [&] { 16828 if (CXXConstructorDecl *Constructor = 16829 dyn_cast<CXXConstructorDecl>(Func)) { 16830 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16831 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16832 if (Constructor->isDefaultConstructor()) { 16833 if (Constructor->isTrivial() && 16834 !Constructor->hasAttr<DLLExportAttr>()) 16835 return; 16836 DefineImplicitDefaultConstructor(Loc, Constructor); 16837 } else if (Constructor->isCopyConstructor()) { 16838 DefineImplicitCopyConstructor(Loc, Constructor); 16839 } else if (Constructor->isMoveConstructor()) { 16840 DefineImplicitMoveConstructor(Loc, Constructor); 16841 } 16842 } else if (Constructor->getInheritedConstructor()) { 16843 DefineInheritingConstructor(Loc, Constructor); 16844 } 16845 } else if (CXXDestructorDecl *Destructor = 16846 dyn_cast<CXXDestructorDecl>(Func)) { 16847 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16848 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16849 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16850 return; 16851 DefineImplicitDestructor(Loc, Destructor); 16852 } 16853 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16854 MarkVTableUsed(Loc, Destructor->getParent()); 16855 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16856 if (MethodDecl->isOverloadedOperator() && 16857 MethodDecl->getOverloadedOperator() == OO_Equal) { 16858 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16859 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16860 if (MethodDecl->isCopyAssignmentOperator()) 16861 DefineImplicitCopyAssignment(Loc, MethodDecl); 16862 else if (MethodDecl->isMoveAssignmentOperator()) 16863 DefineImplicitMoveAssignment(Loc, MethodDecl); 16864 } 16865 } else if (isa<CXXConversionDecl>(MethodDecl) && 16866 MethodDecl->getParent()->isLambda()) { 16867 CXXConversionDecl *Conversion = 16868 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16869 if (Conversion->isLambdaToBlockPointerConversion()) 16870 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16871 else 16872 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16873 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16874 MarkVTableUsed(Loc, MethodDecl->getParent()); 16875 } 16876 16877 if (Func->isDefaulted() && !Func->isDeleted()) { 16878 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16879 if (DCK != DefaultedComparisonKind::None) 16880 DefineDefaultedComparison(Loc, Func, DCK); 16881 } 16882 16883 // Implicit instantiation of function templates and member functions of 16884 // class templates. 16885 if (Func->isImplicitlyInstantiable()) { 16886 TemplateSpecializationKind TSK = 16887 Func->getTemplateSpecializationKindForInstantiation(); 16888 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16889 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16890 if (FirstInstantiation) { 16891 PointOfInstantiation = Loc; 16892 if (auto *MSI = Func->getMemberSpecializationInfo()) 16893 MSI->setPointOfInstantiation(Loc); 16894 // FIXME: Notify listener. 16895 else 16896 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16897 } else if (TSK != TSK_ImplicitInstantiation) { 16898 // Use the point of use as the point of instantiation, instead of the 16899 // point of explicit instantiation (which we track as the actual point 16900 // of instantiation). This gives better backtraces in diagnostics. 16901 PointOfInstantiation = Loc; 16902 } 16903 16904 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16905 Func->isConstexpr()) { 16906 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16907 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16908 CodeSynthesisContexts.size()) 16909 PendingLocalImplicitInstantiations.push_back( 16910 std::make_pair(Func, PointOfInstantiation)); 16911 else if (Func->isConstexpr()) 16912 // Do not defer instantiations of constexpr functions, to avoid the 16913 // expression evaluator needing to call back into Sema if it sees a 16914 // call to such a function. 16915 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16916 else { 16917 Func->setInstantiationIsPending(true); 16918 PendingInstantiations.push_back( 16919 std::make_pair(Func, PointOfInstantiation)); 16920 // Notify the consumer that a function was implicitly instantiated. 16921 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16922 } 16923 } 16924 } else { 16925 // Walk redefinitions, as some of them may be instantiable. 16926 for (auto i : Func->redecls()) { 16927 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16928 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16929 } 16930 } 16931 }); 16932 } 16933 16934 // C++14 [except.spec]p17: 16935 // An exception-specification is considered to be needed when: 16936 // - the function is odr-used or, if it appears in an unevaluated operand, 16937 // would be odr-used if the expression were potentially-evaluated; 16938 // 16939 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16940 // function is a pure virtual function we're calling, and in that case the 16941 // function was selected by overload resolution and we need to resolve its 16942 // exception specification for a different reason. 16943 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16944 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16945 ResolveExceptionSpec(Loc, FPT); 16946 16947 // If this is the first "real" use, act on that. 16948 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16949 // Keep track of used but undefined functions. 16950 if (!Func->isDefined()) { 16951 if (mightHaveNonExternalLinkage(Func)) 16952 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16953 else if (Func->getMostRecentDecl()->isInlined() && 16954 !LangOpts.GNUInline && 16955 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16956 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16957 else if (isExternalWithNoLinkageType(Func)) 16958 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16959 } 16960 16961 // Some x86 Windows calling conventions mangle the size of the parameter 16962 // pack into the name. Computing the size of the parameters requires the 16963 // parameter types to be complete. Check that now. 16964 if (funcHasParameterSizeMangling(*this, Func)) 16965 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16966 16967 // In the MS C++ ABI, the compiler emits destructor variants where they are 16968 // used. If the destructor is used here but defined elsewhere, mark the 16969 // virtual base destructors referenced. If those virtual base destructors 16970 // are inline, this will ensure they are defined when emitting the complete 16971 // destructor variant. This checking may be redundant if the destructor is 16972 // provided later in this TU. 16973 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16974 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 16975 CXXRecordDecl *Parent = Dtor->getParent(); 16976 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 16977 CheckCompleteDestructorVariant(Loc, Dtor); 16978 } 16979 } 16980 16981 Func->markUsed(Context); 16982 } 16983 } 16984 16985 /// Directly mark a variable odr-used. Given a choice, prefer to use 16986 /// MarkVariableReferenced since it does additional checks and then 16987 /// calls MarkVarDeclODRUsed. 16988 /// If the variable must be captured: 16989 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16990 /// - else capture it in the DeclContext that maps to the 16991 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16992 static void 16993 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16994 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16995 // Keep track of used but undefined variables. 16996 // FIXME: We shouldn't suppress this warning for static data members. 16997 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16998 (!Var->isExternallyVisible() || Var->isInline() || 16999 SemaRef.isExternalWithNoLinkageType(Var)) && 17000 !(Var->isStaticDataMember() && Var->hasInit())) { 17001 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17002 if (old.isInvalid()) 17003 old = Loc; 17004 } 17005 QualType CaptureType, DeclRefType; 17006 if (SemaRef.LangOpts.OpenMP) 17007 SemaRef.tryCaptureOpenMPLambdas(Var); 17008 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17009 /*EllipsisLoc*/ SourceLocation(), 17010 /*BuildAndDiagnose*/ true, 17011 CaptureType, DeclRefType, 17012 FunctionScopeIndexToStopAt); 17013 17014 Var->markUsed(SemaRef.Context); 17015 } 17016 17017 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17018 SourceLocation Loc, 17019 unsigned CapturingScopeIndex) { 17020 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17021 } 17022 17023 static void 17024 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17025 ValueDecl *var, DeclContext *DC) { 17026 DeclContext *VarDC = var->getDeclContext(); 17027 17028 // If the parameter still belongs to the translation unit, then 17029 // we're actually just using one parameter in the declaration of 17030 // the next. 17031 if (isa<ParmVarDecl>(var) && 17032 isa<TranslationUnitDecl>(VarDC)) 17033 return; 17034 17035 // For C code, don't diagnose about capture if we're not actually in code 17036 // right now; it's impossible to write a non-constant expression outside of 17037 // function context, so we'll get other (more useful) diagnostics later. 17038 // 17039 // For C++, things get a bit more nasty... it would be nice to suppress this 17040 // diagnostic for certain cases like using a local variable in an array bound 17041 // for a member of a local class, but the correct predicate is not obvious. 17042 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17043 return; 17044 17045 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17046 unsigned ContextKind = 3; // unknown 17047 if (isa<CXXMethodDecl>(VarDC) && 17048 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17049 ContextKind = 2; 17050 } else if (isa<FunctionDecl>(VarDC)) { 17051 ContextKind = 0; 17052 } else if (isa<BlockDecl>(VarDC)) { 17053 ContextKind = 1; 17054 } 17055 17056 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17057 << var << ValueKind << ContextKind << VarDC; 17058 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17059 << var; 17060 17061 // FIXME: Add additional diagnostic info about class etc. which prevents 17062 // capture. 17063 } 17064 17065 17066 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17067 bool &SubCapturesAreNested, 17068 QualType &CaptureType, 17069 QualType &DeclRefType) { 17070 // Check whether we've already captured it. 17071 if (CSI->CaptureMap.count(Var)) { 17072 // If we found a capture, any subcaptures are nested. 17073 SubCapturesAreNested = true; 17074 17075 // Retrieve the capture type for this variable. 17076 CaptureType = CSI->getCapture(Var).getCaptureType(); 17077 17078 // Compute the type of an expression that refers to this variable. 17079 DeclRefType = CaptureType.getNonReferenceType(); 17080 17081 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17082 // are mutable in the sense that user can change their value - they are 17083 // private instances of the captured declarations. 17084 const Capture &Cap = CSI->getCapture(Var); 17085 if (Cap.isCopyCapture() && 17086 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17087 !(isa<CapturedRegionScopeInfo>(CSI) && 17088 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17089 DeclRefType.addConst(); 17090 return true; 17091 } 17092 return false; 17093 } 17094 17095 // Only block literals, captured statements, and lambda expressions can 17096 // capture; other scopes don't work. 17097 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17098 SourceLocation Loc, 17099 const bool Diagnose, Sema &S) { 17100 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17101 return getLambdaAwareParentOfDeclContext(DC); 17102 else if (Var->hasLocalStorage()) { 17103 if (Diagnose) 17104 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17105 } 17106 return nullptr; 17107 } 17108 17109 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17110 // certain types of variables (unnamed, variably modified types etc.) 17111 // so check for eligibility. 17112 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17113 SourceLocation Loc, 17114 const bool Diagnose, Sema &S) { 17115 17116 bool IsBlock = isa<BlockScopeInfo>(CSI); 17117 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17118 17119 // Lambdas are not allowed to capture unnamed variables 17120 // (e.g. anonymous unions). 17121 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17122 // assuming that's the intent. 17123 if (IsLambda && !Var->getDeclName()) { 17124 if (Diagnose) { 17125 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17126 S.Diag(Var->getLocation(), diag::note_declared_at); 17127 } 17128 return false; 17129 } 17130 17131 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17132 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17133 if (Diagnose) { 17134 S.Diag(Loc, diag::err_ref_vm_type); 17135 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17136 } 17137 return false; 17138 } 17139 // Prohibit structs with flexible array members too. 17140 // We cannot capture what is in the tail end of the struct. 17141 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17142 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17143 if (Diagnose) { 17144 if (IsBlock) 17145 S.Diag(Loc, diag::err_ref_flexarray_type); 17146 else 17147 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17148 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17149 } 17150 return false; 17151 } 17152 } 17153 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17154 // Lambdas and captured statements are not allowed to capture __block 17155 // variables; they don't support the expected semantics. 17156 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17157 if (Diagnose) { 17158 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17159 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17160 } 17161 return false; 17162 } 17163 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17164 if (S.getLangOpts().OpenCL && IsBlock && 17165 Var->getType()->isBlockPointerType()) { 17166 if (Diagnose) 17167 S.Diag(Loc, diag::err_opencl_block_ref_block); 17168 return false; 17169 } 17170 17171 return true; 17172 } 17173 17174 // Returns true if the capture by block was successful. 17175 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17176 SourceLocation Loc, 17177 const bool BuildAndDiagnose, 17178 QualType &CaptureType, 17179 QualType &DeclRefType, 17180 const bool Nested, 17181 Sema &S, bool Invalid) { 17182 bool ByRef = false; 17183 17184 // Blocks are not allowed to capture arrays, excepting OpenCL. 17185 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17186 // (decayed to pointers). 17187 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17188 if (BuildAndDiagnose) { 17189 S.Diag(Loc, diag::err_ref_array_type); 17190 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17191 Invalid = true; 17192 } else { 17193 return false; 17194 } 17195 } 17196 17197 // Forbid the block-capture of autoreleasing variables. 17198 if (!Invalid && 17199 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17200 if (BuildAndDiagnose) { 17201 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17202 << /*block*/ 0; 17203 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17204 Invalid = true; 17205 } else { 17206 return false; 17207 } 17208 } 17209 17210 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17211 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17212 QualType PointeeTy = PT->getPointeeType(); 17213 17214 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17215 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17216 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17217 if (BuildAndDiagnose) { 17218 SourceLocation VarLoc = Var->getLocation(); 17219 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17220 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17221 } 17222 } 17223 } 17224 17225 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17226 if (HasBlocksAttr || CaptureType->isReferenceType() || 17227 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17228 // Block capture by reference does not change the capture or 17229 // declaration reference types. 17230 ByRef = true; 17231 } else { 17232 // Block capture by copy introduces 'const'. 17233 CaptureType = CaptureType.getNonReferenceType().withConst(); 17234 DeclRefType = CaptureType; 17235 } 17236 17237 // Actually capture the variable. 17238 if (BuildAndDiagnose) 17239 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17240 CaptureType, Invalid); 17241 17242 return !Invalid; 17243 } 17244 17245 17246 /// Capture the given variable in the captured region. 17247 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17248 VarDecl *Var, 17249 SourceLocation Loc, 17250 const bool BuildAndDiagnose, 17251 QualType &CaptureType, 17252 QualType &DeclRefType, 17253 const bool RefersToCapturedVariable, 17254 Sema &S, bool Invalid) { 17255 // By default, capture variables by reference. 17256 bool ByRef = true; 17257 // Using an LValue reference type is consistent with Lambdas (see below). 17258 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17259 if (S.isOpenMPCapturedDecl(Var)) { 17260 bool HasConst = DeclRefType.isConstQualified(); 17261 DeclRefType = DeclRefType.getUnqualifiedType(); 17262 // Don't lose diagnostics about assignments to const. 17263 if (HasConst) 17264 DeclRefType.addConst(); 17265 } 17266 // Do not capture firstprivates in tasks. 17267 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17268 OMPC_unknown) 17269 return true; 17270 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17271 RSI->OpenMPCaptureLevel); 17272 } 17273 17274 if (ByRef) 17275 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17276 else 17277 CaptureType = DeclRefType; 17278 17279 // Actually capture the variable. 17280 if (BuildAndDiagnose) 17281 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17282 Loc, SourceLocation(), CaptureType, Invalid); 17283 17284 return !Invalid; 17285 } 17286 17287 /// Capture the given variable in the lambda. 17288 static bool captureInLambda(LambdaScopeInfo *LSI, 17289 VarDecl *Var, 17290 SourceLocation Loc, 17291 const bool BuildAndDiagnose, 17292 QualType &CaptureType, 17293 QualType &DeclRefType, 17294 const bool RefersToCapturedVariable, 17295 const Sema::TryCaptureKind Kind, 17296 SourceLocation EllipsisLoc, 17297 const bool IsTopScope, 17298 Sema &S, bool Invalid) { 17299 // Determine whether we are capturing by reference or by value. 17300 bool ByRef = false; 17301 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17302 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17303 } else { 17304 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17305 } 17306 17307 // Compute the type of the field that will capture this variable. 17308 if (ByRef) { 17309 // C++11 [expr.prim.lambda]p15: 17310 // An entity is captured by reference if it is implicitly or 17311 // explicitly captured but not captured by copy. It is 17312 // unspecified whether additional unnamed non-static data 17313 // members are declared in the closure type for entities 17314 // captured by reference. 17315 // 17316 // FIXME: It is not clear whether we want to build an lvalue reference 17317 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17318 // to do the former, while EDG does the latter. Core issue 1249 will 17319 // clarify, but for now we follow GCC because it's a more permissive and 17320 // easily defensible position. 17321 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17322 } else { 17323 // C++11 [expr.prim.lambda]p14: 17324 // For each entity captured by copy, an unnamed non-static 17325 // data member is declared in the closure type. The 17326 // declaration order of these members is unspecified. The type 17327 // of such a data member is the type of the corresponding 17328 // captured entity if the entity is not a reference to an 17329 // object, or the referenced type otherwise. [Note: If the 17330 // captured entity is a reference to a function, the 17331 // corresponding data member is also a reference to a 17332 // function. - end note ] 17333 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17334 if (!RefType->getPointeeType()->isFunctionType()) 17335 CaptureType = RefType->getPointeeType(); 17336 } 17337 17338 // Forbid the lambda copy-capture of autoreleasing variables. 17339 if (!Invalid && 17340 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17341 if (BuildAndDiagnose) { 17342 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17343 S.Diag(Var->getLocation(), diag::note_previous_decl) 17344 << Var->getDeclName(); 17345 Invalid = true; 17346 } else { 17347 return false; 17348 } 17349 } 17350 17351 // Make sure that by-copy captures are of a complete and non-abstract type. 17352 if (!Invalid && BuildAndDiagnose) { 17353 if (!CaptureType->isDependentType() && 17354 S.RequireCompleteSizedType( 17355 Loc, CaptureType, 17356 diag::err_capture_of_incomplete_or_sizeless_type, 17357 Var->getDeclName())) 17358 Invalid = true; 17359 else if (S.RequireNonAbstractType(Loc, CaptureType, 17360 diag::err_capture_of_abstract_type)) 17361 Invalid = true; 17362 } 17363 } 17364 17365 // Compute the type of a reference to this captured variable. 17366 if (ByRef) 17367 DeclRefType = CaptureType.getNonReferenceType(); 17368 else { 17369 // C++ [expr.prim.lambda]p5: 17370 // The closure type for a lambda-expression has a public inline 17371 // function call operator [...]. This function call operator is 17372 // declared const (9.3.1) if and only if the lambda-expression's 17373 // parameter-declaration-clause is not followed by mutable. 17374 DeclRefType = CaptureType.getNonReferenceType(); 17375 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17376 DeclRefType.addConst(); 17377 } 17378 17379 // Add the capture. 17380 if (BuildAndDiagnose) 17381 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17382 Loc, EllipsisLoc, CaptureType, Invalid); 17383 17384 return !Invalid; 17385 } 17386 17387 bool Sema::tryCaptureVariable( 17388 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17389 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17390 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17391 // An init-capture is notionally from the context surrounding its 17392 // declaration, but its parent DC is the lambda class. 17393 DeclContext *VarDC = Var->getDeclContext(); 17394 if (Var->isInitCapture()) 17395 VarDC = VarDC->getParent(); 17396 17397 DeclContext *DC = CurContext; 17398 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17399 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17400 // We need to sync up the Declaration Context with the 17401 // FunctionScopeIndexToStopAt 17402 if (FunctionScopeIndexToStopAt) { 17403 unsigned FSIndex = FunctionScopes.size() - 1; 17404 while (FSIndex != MaxFunctionScopesIndex) { 17405 DC = getLambdaAwareParentOfDeclContext(DC); 17406 --FSIndex; 17407 } 17408 } 17409 17410 17411 // If the variable is declared in the current context, there is no need to 17412 // capture it. 17413 if (VarDC == DC) return true; 17414 17415 // Capture global variables if it is required to use private copy of this 17416 // variable. 17417 bool IsGlobal = !Var->hasLocalStorage(); 17418 if (IsGlobal && 17419 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17420 MaxFunctionScopesIndex))) 17421 return true; 17422 Var = Var->getCanonicalDecl(); 17423 17424 // Walk up the stack to determine whether we can capture the variable, 17425 // performing the "simple" checks that don't depend on type. We stop when 17426 // we've either hit the declared scope of the variable or find an existing 17427 // capture of that variable. We start from the innermost capturing-entity 17428 // (the DC) and ensure that all intervening capturing-entities 17429 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17430 // declcontext can either capture the variable or have already captured 17431 // the variable. 17432 CaptureType = Var->getType(); 17433 DeclRefType = CaptureType.getNonReferenceType(); 17434 bool Nested = false; 17435 bool Explicit = (Kind != TryCapture_Implicit); 17436 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17437 do { 17438 // Only block literals, captured statements, and lambda expressions can 17439 // capture; other scopes don't work. 17440 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17441 ExprLoc, 17442 BuildAndDiagnose, 17443 *this); 17444 // We need to check for the parent *first* because, if we *have* 17445 // private-captured a global variable, we need to recursively capture it in 17446 // intermediate blocks, lambdas, etc. 17447 if (!ParentDC) { 17448 if (IsGlobal) { 17449 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17450 break; 17451 } 17452 return true; 17453 } 17454 17455 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17456 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17457 17458 17459 // Check whether we've already captured it. 17460 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17461 DeclRefType)) { 17462 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17463 break; 17464 } 17465 // If we are instantiating a generic lambda call operator body, 17466 // we do not want to capture new variables. What was captured 17467 // during either a lambdas transformation or initial parsing 17468 // should be used. 17469 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17470 if (BuildAndDiagnose) { 17471 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17472 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17473 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17474 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17475 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17476 } else 17477 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17478 } 17479 return true; 17480 } 17481 17482 // Try to capture variable-length arrays types. 17483 if (Var->getType()->isVariablyModifiedType()) { 17484 // We're going to walk down into the type and look for VLA 17485 // expressions. 17486 QualType QTy = Var->getType(); 17487 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17488 QTy = PVD->getOriginalType(); 17489 captureVariablyModifiedType(Context, QTy, CSI); 17490 } 17491 17492 if (getLangOpts().OpenMP) { 17493 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17494 // OpenMP private variables should not be captured in outer scope, so 17495 // just break here. Similarly, global variables that are captured in a 17496 // target region should not be captured outside the scope of the region. 17497 if (RSI->CapRegionKind == CR_OpenMP) { 17498 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17499 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17500 // If the variable is private (i.e. not captured) and has variably 17501 // modified type, we still need to capture the type for correct 17502 // codegen in all regions, associated with the construct. Currently, 17503 // it is captured in the innermost captured region only. 17504 if (IsOpenMPPrivateDecl != OMPC_unknown && 17505 Var->getType()->isVariablyModifiedType()) { 17506 QualType QTy = Var->getType(); 17507 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17508 QTy = PVD->getOriginalType(); 17509 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17510 I < E; ++I) { 17511 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17512 FunctionScopes[FunctionScopesIndex - I]); 17513 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17514 "Wrong number of captured regions associated with the " 17515 "OpenMP construct."); 17516 captureVariablyModifiedType(Context, QTy, OuterRSI); 17517 } 17518 } 17519 bool IsTargetCap = 17520 IsOpenMPPrivateDecl != OMPC_private && 17521 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17522 RSI->OpenMPCaptureLevel); 17523 // Do not capture global if it is not privatized in outer regions. 17524 bool IsGlobalCap = 17525 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17526 RSI->OpenMPCaptureLevel); 17527 17528 // When we detect target captures we are looking from inside the 17529 // target region, therefore we need to propagate the capture from the 17530 // enclosing region. Therefore, the capture is not initially nested. 17531 if (IsTargetCap) 17532 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17533 17534 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17535 (IsGlobal && !IsGlobalCap)) { 17536 Nested = !IsTargetCap; 17537 bool HasConst = DeclRefType.isConstQualified(); 17538 DeclRefType = DeclRefType.getUnqualifiedType(); 17539 // Don't lose diagnostics about assignments to const. 17540 if (HasConst) 17541 DeclRefType.addConst(); 17542 CaptureType = Context.getLValueReferenceType(DeclRefType); 17543 break; 17544 } 17545 } 17546 } 17547 } 17548 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17549 // No capture-default, and this is not an explicit capture 17550 // so cannot capture this variable. 17551 if (BuildAndDiagnose) { 17552 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17553 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17554 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17555 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17556 diag::note_lambda_decl); 17557 // FIXME: If we error out because an outer lambda can not implicitly 17558 // capture a variable that an inner lambda explicitly captures, we 17559 // should have the inner lambda do the explicit capture - because 17560 // it makes for cleaner diagnostics later. This would purely be done 17561 // so that the diagnostic does not misleadingly claim that a variable 17562 // can not be captured by a lambda implicitly even though it is captured 17563 // explicitly. Suggestion: 17564 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17565 // at the function head 17566 // - cache the StartingDeclContext - this must be a lambda 17567 // - captureInLambda in the innermost lambda the variable. 17568 } 17569 return true; 17570 } 17571 17572 FunctionScopesIndex--; 17573 DC = ParentDC; 17574 Explicit = false; 17575 } while (!VarDC->Equals(DC)); 17576 17577 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17578 // computing the type of the capture at each step, checking type-specific 17579 // requirements, and adding captures if requested. 17580 // If the variable had already been captured previously, we start capturing 17581 // at the lambda nested within that one. 17582 bool Invalid = false; 17583 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17584 ++I) { 17585 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17586 17587 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17588 // certain types of variables (unnamed, variably modified types etc.) 17589 // so check for eligibility. 17590 if (!Invalid) 17591 Invalid = 17592 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17593 17594 // After encountering an error, if we're actually supposed to capture, keep 17595 // capturing in nested contexts to suppress any follow-on diagnostics. 17596 if (Invalid && !BuildAndDiagnose) 17597 return true; 17598 17599 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17600 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17601 DeclRefType, Nested, *this, Invalid); 17602 Nested = true; 17603 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17604 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17605 CaptureType, DeclRefType, Nested, 17606 *this, Invalid); 17607 Nested = true; 17608 } else { 17609 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17610 Invalid = 17611 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17612 DeclRefType, Nested, Kind, EllipsisLoc, 17613 /*IsTopScope*/ I == N - 1, *this, Invalid); 17614 Nested = true; 17615 } 17616 17617 if (Invalid && !BuildAndDiagnose) 17618 return true; 17619 } 17620 return Invalid; 17621 } 17622 17623 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17624 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17625 QualType CaptureType; 17626 QualType DeclRefType; 17627 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17628 /*BuildAndDiagnose=*/true, CaptureType, 17629 DeclRefType, nullptr); 17630 } 17631 17632 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17633 QualType CaptureType; 17634 QualType DeclRefType; 17635 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17636 /*BuildAndDiagnose=*/false, CaptureType, 17637 DeclRefType, nullptr); 17638 } 17639 17640 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17641 QualType CaptureType; 17642 QualType DeclRefType; 17643 17644 // Determine whether we can capture this variable. 17645 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17646 /*BuildAndDiagnose=*/false, CaptureType, 17647 DeclRefType, nullptr)) 17648 return QualType(); 17649 17650 return DeclRefType; 17651 } 17652 17653 namespace { 17654 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17655 // The produced TemplateArgumentListInfo* points to data stored within this 17656 // object, so should only be used in contexts where the pointer will not be 17657 // used after the CopiedTemplateArgs object is destroyed. 17658 class CopiedTemplateArgs { 17659 bool HasArgs; 17660 TemplateArgumentListInfo TemplateArgStorage; 17661 public: 17662 template<typename RefExpr> 17663 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17664 if (HasArgs) 17665 E->copyTemplateArgumentsInto(TemplateArgStorage); 17666 } 17667 operator TemplateArgumentListInfo*() 17668 #ifdef __has_cpp_attribute 17669 #if __has_cpp_attribute(clang::lifetimebound) 17670 [[clang::lifetimebound]] 17671 #endif 17672 #endif 17673 { 17674 return HasArgs ? &TemplateArgStorage : nullptr; 17675 } 17676 }; 17677 } 17678 17679 /// Walk the set of potential results of an expression and mark them all as 17680 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17681 /// 17682 /// \return A new expression if we found any potential results, ExprEmpty() if 17683 /// not, and ExprError() if we diagnosed an error. 17684 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17685 NonOdrUseReason NOUR) { 17686 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17687 // an object that satisfies the requirements for appearing in a 17688 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17689 // is immediately applied." This function handles the lvalue-to-rvalue 17690 // conversion part. 17691 // 17692 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17693 // transform it into the relevant kind of non-odr-use node and rebuild the 17694 // tree of nodes leading to it. 17695 // 17696 // This is a mini-TreeTransform that only transforms a restricted subset of 17697 // nodes (and only certain operands of them). 17698 17699 // Rebuild a subexpression. 17700 auto Rebuild = [&](Expr *Sub) { 17701 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17702 }; 17703 17704 // Check whether a potential result satisfies the requirements of NOUR. 17705 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17706 // Any entity other than a VarDecl is always odr-used whenever it's named 17707 // in a potentially-evaluated expression. 17708 auto *VD = dyn_cast<VarDecl>(D); 17709 if (!VD) 17710 return true; 17711 17712 // C++2a [basic.def.odr]p4: 17713 // A variable x whose name appears as a potentially-evalauted expression 17714 // e is odr-used by e unless 17715 // -- x is a reference that is usable in constant expressions, or 17716 // -- x is a variable of non-reference type that is usable in constant 17717 // expressions and has no mutable subobjects, and e is an element of 17718 // the set of potential results of an expression of 17719 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17720 // conversion is applied, or 17721 // -- x is a variable of non-reference type, and e is an element of the 17722 // set of potential results of a discarded-value expression to which 17723 // the lvalue-to-rvalue conversion is not applied 17724 // 17725 // We check the first bullet and the "potentially-evaluated" condition in 17726 // BuildDeclRefExpr. We check the type requirements in the second bullet 17727 // in CheckLValueToRValueConversionOperand below. 17728 switch (NOUR) { 17729 case NOUR_None: 17730 case NOUR_Unevaluated: 17731 llvm_unreachable("unexpected non-odr-use-reason"); 17732 17733 case NOUR_Constant: 17734 // Constant references were handled when they were built. 17735 if (VD->getType()->isReferenceType()) 17736 return true; 17737 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17738 if (RD->hasMutableFields()) 17739 return true; 17740 if (!VD->isUsableInConstantExpressions(S.Context)) 17741 return true; 17742 break; 17743 17744 case NOUR_Discarded: 17745 if (VD->getType()->isReferenceType()) 17746 return true; 17747 break; 17748 } 17749 return false; 17750 }; 17751 17752 // Mark that this expression does not constitute an odr-use. 17753 auto MarkNotOdrUsed = [&] { 17754 S.MaybeODRUseExprs.remove(E); 17755 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17756 LSI->markVariableExprAsNonODRUsed(E); 17757 }; 17758 17759 // C++2a [basic.def.odr]p2: 17760 // The set of potential results of an expression e is defined as follows: 17761 switch (E->getStmtClass()) { 17762 // -- If e is an id-expression, ... 17763 case Expr::DeclRefExprClass: { 17764 auto *DRE = cast<DeclRefExpr>(E); 17765 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17766 break; 17767 17768 // Rebuild as a non-odr-use DeclRefExpr. 17769 MarkNotOdrUsed(); 17770 return DeclRefExpr::Create( 17771 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17772 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17773 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17774 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17775 } 17776 17777 case Expr::FunctionParmPackExprClass: { 17778 auto *FPPE = cast<FunctionParmPackExpr>(E); 17779 // If any of the declarations in the pack is odr-used, then the expression 17780 // as a whole constitutes an odr-use. 17781 for (VarDecl *D : *FPPE) 17782 if (IsPotentialResultOdrUsed(D)) 17783 return ExprEmpty(); 17784 17785 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17786 // nothing cares about whether we marked this as an odr-use, but it might 17787 // be useful for non-compiler tools. 17788 MarkNotOdrUsed(); 17789 break; 17790 } 17791 17792 // -- If e is a subscripting operation with an array operand... 17793 case Expr::ArraySubscriptExprClass: { 17794 auto *ASE = cast<ArraySubscriptExpr>(E); 17795 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17796 if (!OldBase->getType()->isArrayType()) 17797 break; 17798 ExprResult Base = Rebuild(OldBase); 17799 if (!Base.isUsable()) 17800 return Base; 17801 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17802 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17803 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17804 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17805 ASE->getRBracketLoc()); 17806 } 17807 17808 case Expr::MemberExprClass: { 17809 auto *ME = cast<MemberExpr>(E); 17810 // -- If e is a class member access expression [...] naming a non-static 17811 // data member... 17812 if (isa<FieldDecl>(ME->getMemberDecl())) { 17813 ExprResult Base = Rebuild(ME->getBase()); 17814 if (!Base.isUsable()) 17815 return Base; 17816 return MemberExpr::Create( 17817 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17818 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17819 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17820 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17821 ME->getObjectKind(), ME->isNonOdrUse()); 17822 } 17823 17824 if (ME->getMemberDecl()->isCXXInstanceMember()) 17825 break; 17826 17827 // -- If e is a class member access expression naming a static data member, 17828 // ... 17829 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17830 break; 17831 17832 // Rebuild as a non-odr-use MemberExpr. 17833 MarkNotOdrUsed(); 17834 return MemberExpr::Create( 17835 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17836 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17837 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17838 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17839 return ExprEmpty(); 17840 } 17841 17842 case Expr::BinaryOperatorClass: { 17843 auto *BO = cast<BinaryOperator>(E); 17844 Expr *LHS = BO->getLHS(); 17845 Expr *RHS = BO->getRHS(); 17846 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17847 if (BO->getOpcode() == BO_PtrMemD) { 17848 ExprResult Sub = Rebuild(LHS); 17849 if (!Sub.isUsable()) 17850 return Sub; 17851 LHS = Sub.get(); 17852 // -- If e is a comma expression, ... 17853 } else if (BO->getOpcode() == BO_Comma) { 17854 ExprResult Sub = Rebuild(RHS); 17855 if (!Sub.isUsable()) 17856 return Sub; 17857 RHS = Sub.get(); 17858 } else { 17859 break; 17860 } 17861 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17862 LHS, RHS); 17863 } 17864 17865 // -- If e has the form (e1)... 17866 case Expr::ParenExprClass: { 17867 auto *PE = cast<ParenExpr>(E); 17868 ExprResult Sub = Rebuild(PE->getSubExpr()); 17869 if (!Sub.isUsable()) 17870 return Sub; 17871 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17872 } 17873 17874 // -- If e is a glvalue conditional expression, ... 17875 // We don't apply this to a binary conditional operator. FIXME: Should we? 17876 case Expr::ConditionalOperatorClass: { 17877 auto *CO = cast<ConditionalOperator>(E); 17878 ExprResult LHS = Rebuild(CO->getLHS()); 17879 if (LHS.isInvalid()) 17880 return ExprError(); 17881 ExprResult RHS = Rebuild(CO->getRHS()); 17882 if (RHS.isInvalid()) 17883 return ExprError(); 17884 if (!LHS.isUsable() && !RHS.isUsable()) 17885 return ExprEmpty(); 17886 if (!LHS.isUsable()) 17887 LHS = CO->getLHS(); 17888 if (!RHS.isUsable()) 17889 RHS = CO->getRHS(); 17890 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17891 CO->getCond(), LHS.get(), RHS.get()); 17892 } 17893 17894 // [Clang extension] 17895 // -- If e has the form __extension__ e1... 17896 case Expr::UnaryOperatorClass: { 17897 auto *UO = cast<UnaryOperator>(E); 17898 if (UO->getOpcode() != UO_Extension) 17899 break; 17900 ExprResult Sub = Rebuild(UO->getSubExpr()); 17901 if (!Sub.isUsable()) 17902 return Sub; 17903 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17904 Sub.get()); 17905 } 17906 17907 // [Clang extension] 17908 // -- If e has the form _Generic(...), the set of potential results is the 17909 // union of the sets of potential results of the associated expressions. 17910 case Expr::GenericSelectionExprClass: { 17911 auto *GSE = cast<GenericSelectionExpr>(E); 17912 17913 SmallVector<Expr *, 4> AssocExprs; 17914 bool AnyChanged = false; 17915 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17916 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17917 if (AssocExpr.isInvalid()) 17918 return ExprError(); 17919 if (AssocExpr.isUsable()) { 17920 AssocExprs.push_back(AssocExpr.get()); 17921 AnyChanged = true; 17922 } else { 17923 AssocExprs.push_back(OrigAssocExpr); 17924 } 17925 } 17926 17927 return AnyChanged ? S.CreateGenericSelectionExpr( 17928 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17929 GSE->getRParenLoc(), GSE->getControllingExpr(), 17930 GSE->getAssocTypeSourceInfos(), AssocExprs) 17931 : ExprEmpty(); 17932 } 17933 17934 // [Clang extension] 17935 // -- If e has the form __builtin_choose_expr(...), the set of potential 17936 // results is the union of the sets of potential results of the 17937 // second and third subexpressions. 17938 case Expr::ChooseExprClass: { 17939 auto *CE = cast<ChooseExpr>(E); 17940 17941 ExprResult LHS = Rebuild(CE->getLHS()); 17942 if (LHS.isInvalid()) 17943 return ExprError(); 17944 17945 ExprResult RHS = Rebuild(CE->getLHS()); 17946 if (RHS.isInvalid()) 17947 return ExprError(); 17948 17949 if (!LHS.get() && !RHS.get()) 17950 return ExprEmpty(); 17951 if (!LHS.isUsable()) 17952 LHS = CE->getLHS(); 17953 if (!RHS.isUsable()) 17954 RHS = CE->getRHS(); 17955 17956 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17957 RHS.get(), CE->getRParenLoc()); 17958 } 17959 17960 // Step through non-syntactic nodes. 17961 case Expr::ConstantExprClass: { 17962 auto *CE = cast<ConstantExpr>(E); 17963 ExprResult Sub = Rebuild(CE->getSubExpr()); 17964 if (!Sub.isUsable()) 17965 return Sub; 17966 return ConstantExpr::Create(S.Context, Sub.get()); 17967 } 17968 17969 // We could mostly rely on the recursive rebuilding to rebuild implicit 17970 // casts, but not at the top level, so rebuild them here. 17971 case Expr::ImplicitCastExprClass: { 17972 auto *ICE = cast<ImplicitCastExpr>(E); 17973 // Only step through the narrow set of cast kinds we expect to encounter. 17974 // Anything else suggests we've left the region in which potential results 17975 // can be found. 17976 switch (ICE->getCastKind()) { 17977 case CK_NoOp: 17978 case CK_DerivedToBase: 17979 case CK_UncheckedDerivedToBase: { 17980 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17981 if (!Sub.isUsable()) 17982 return Sub; 17983 CXXCastPath Path(ICE->path()); 17984 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17985 ICE->getValueKind(), &Path); 17986 } 17987 17988 default: 17989 break; 17990 } 17991 break; 17992 } 17993 17994 default: 17995 break; 17996 } 17997 17998 // Can't traverse through this node. Nothing to do. 17999 return ExprEmpty(); 18000 } 18001 18002 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18003 // Check whether the operand is or contains an object of non-trivial C union 18004 // type. 18005 if (E->getType().isVolatileQualified() && 18006 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18007 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18008 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18009 Sema::NTCUC_LValueToRValueVolatile, 18010 NTCUK_Destruct|NTCUK_Copy); 18011 18012 // C++2a [basic.def.odr]p4: 18013 // [...] an expression of non-volatile-qualified non-class type to which 18014 // the lvalue-to-rvalue conversion is applied [...] 18015 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18016 return E; 18017 18018 ExprResult Result = 18019 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18020 if (Result.isInvalid()) 18021 return ExprError(); 18022 return Result.get() ? Result : E; 18023 } 18024 18025 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18026 Res = CorrectDelayedTyposInExpr(Res); 18027 18028 if (!Res.isUsable()) 18029 return Res; 18030 18031 // If a constant-expression is a reference to a variable where we delay 18032 // deciding whether it is an odr-use, just assume we will apply the 18033 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18034 // (a non-type template argument), we have special handling anyway. 18035 return CheckLValueToRValueConversionOperand(Res.get()); 18036 } 18037 18038 void Sema::CleanupVarDeclMarking() { 18039 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18040 // call. 18041 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18042 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18043 18044 for (Expr *E : LocalMaybeODRUseExprs) { 18045 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18046 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18047 DRE->getLocation(), *this); 18048 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18049 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18050 *this); 18051 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18052 for (VarDecl *VD : *FP) 18053 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18054 } else { 18055 llvm_unreachable("Unexpected expression"); 18056 } 18057 } 18058 18059 assert(MaybeODRUseExprs.empty() && 18060 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18061 } 18062 18063 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18064 VarDecl *Var, Expr *E) { 18065 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18066 isa<FunctionParmPackExpr>(E)) && 18067 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18068 Var->setReferenced(); 18069 18070 if (Var->isInvalidDecl()) 18071 return; 18072 18073 // Record a CUDA/HIP static device/constant variable if it is referenced 18074 // by host code. This is done conservatively, when the variable is referenced 18075 // in any of the following contexts: 18076 // - a non-function context 18077 // - a host function 18078 // - a host device function 18079 // This also requires the reference of the static device/constant variable by 18080 // host code to be visible in the device compilation for the compiler to be 18081 // able to externalize the static device/constant variable. 18082 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18083 auto *CurContext = SemaRef.CurContext; 18084 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18085 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18086 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18087 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18088 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18089 } 18090 18091 auto *MSI = Var->getMemberSpecializationInfo(); 18092 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18093 : Var->getTemplateSpecializationKind(); 18094 18095 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18096 bool UsableInConstantExpr = 18097 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18098 18099 // C++20 [expr.const]p12: 18100 // A variable [...] is needed for constant evaluation if it is [...] a 18101 // variable whose name appears as a potentially constant evaluated 18102 // expression that is either a contexpr variable or is of non-volatile 18103 // const-qualified integral type or of reference type 18104 bool NeededForConstantEvaluation = 18105 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18106 18107 bool NeedDefinition = 18108 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18109 18110 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18111 "Can't instantiate a partial template specialization."); 18112 18113 // If this might be a member specialization of a static data member, check 18114 // the specialization is visible. We already did the checks for variable 18115 // template specializations when we created them. 18116 if (NeedDefinition && TSK != TSK_Undeclared && 18117 !isa<VarTemplateSpecializationDecl>(Var)) 18118 SemaRef.checkSpecializationVisibility(Loc, Var); 18119 18120 // Perform implicit instantiation of static data members, static data member 18121 // templates of class templates, and variable template specializations. Delay 18122 // instantiations of variable templates, except for those that could be used 18123 // in a constant expression. 18124 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18125 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18126 // instantiation declaration if a variable is usable in a constant 18127 // expression (among other cases). 18128 bool TryInstantiating = 18129 TSK == TSK_ImplicitInstantiation || 18130 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18131 18132 if (TryInstantiating) { 18133 SourceLocation PointOfInstantiation = 18134 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18135 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18136 if (FirstInstantiation) { 18137 PointOfInstantiation = Loc; 18138 if (MSI) 18139 MSI->setPointOfInstantiation(PointOfInstantiation); 18140 // FIXME: Notify listener. 18141 else 18142 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18143 } 18144 18145 if (UsableInConstantExpr) { 18146 // Do not defer instantiations of variables that could be used in a 18147 // constant expression. 18148 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18149 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18150 }); 18151 } else if (FirstInstantiation || 18152 isa<VarTemplateSpecializationDecl>(Var)) { 18153 // FIXME: For a specialization of a variable template, we don't 18154 // distinguish between "declaration and type implicitly instantiated" 18155 // and "implicit instantiation of definition requested", so we have 18156 // no direct way to avoid enqueueing the pending instantiation 18157 // multiple times. 18158 SemaRef.PendingInstantiations 18159 .push_back(std::make_pair(Var, PointOfInstantiation)); 18160 } 18161 } 18162 } 18163 18164 // C++2a [basic.def.odr]p4: 18165 // A variable x whose name appears as a potentially-evaluated expression e 18166 // is odr-used by e unless 18167 // -- x is a reference that is usable in constant expressions 18168 // -- x is a variable of non-reference type that is usable in constant 18169 // expressions and has no mutable subobjects [FIXME], and e is an 18170 // element of the set of potential results of an expression of 18171 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18172 // conversion is applied 18173 // -- x is a variable of non-reference type, and e is an element of the set 18174 // of potential results of a discarded-value expression to which the 18175 // lvalue-to-rvalue conversion is not applied [FIXME] 18176 // 18177 // We check the first part of the second bullet here, and 18178 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18179 // FIXME: To get the third bullet right, we need to delay this even for 18180 // variables that are not usable in constant expressions. 18181 18182 // If we already know this isn't an odr-use, there's nothing more to do. 18183 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18184 if (DRE->isNonOdrUse()) 18185 return; 18186 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18187 if (ME->isNonOdrUse()) 18188 return; 18189 18190 switch (OdrUse) { 18191 case OdrUseContext::None: 18192 assert((!E || isa<FunctionParmPackExpr>(E)) && 18193 "missing non-odr-use marking for unevaluated decl ref"); 18194 break; 18195 18196 case OdrUseContext::FormallyOdrUsed: 18197 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18198 // behavior. 18199 break; 18200 18201 case OdrUseContext::Used: 18202 // If we might later find that this expression isn't actually an odr-use, 18203 // delay the marking. 18204 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18205 SemaRef.MaybeODRUseExprs.insert(E); 18206 else 18207 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18208 break; 18209 18210 case OdrUseContext::Dependent: 18211 // If this is a dependent context, we don't need to mark variables as 18212 // odr-used, but we may still need to track them for lambda capture. 18213 // FIXME: Do we also need to do this inside dependent typeid expressions 18214 // (which are modeled as unevaluated at this point)? 18215 const bool RefersToEnclosingScope = 18216 (SemaRef.CurContext != Var->getDeclContext() && 18217 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18218 if (RefersToEnclosingScope) { 18219 LambdaScopeInfo *const LSI = 18220 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18221 if (LSI && (!LSI->CallOperator || 18222 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18223 // If a variable could potentially be odr-used, defer marking it so 18224 // until we finish analyzing the full expression for any 18225 // lvalue-to-rvalue 18226 // or discarded value conversions that would obviate odr-use. 18227 // Add it to the list of potential captures that will be analyzed 18228 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18229 // unless the variable is a reference that was initialized by a constant 18230 // expression (this will never need to be captured or odr-used). 18231 // 18232 // FIXME: We can simplify this a lot after implementing P0588R1. 18233 assert(E && "Capture variable should be used in an expression."); 18234 if (!Var->getType()->isReferenceType() || 18235 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18236 LSI->addPotentialCapture(E->IgnoreParens()); 18237 } 18238 } 18239 break; 18240 } 18241 } 18242 18243 /// Mark a variable referenced, and check whether it is odr-used 18244 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18245 /// used directly for normal expressions referring to VarDecl. 18246 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18247 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18248 } 18249 18250 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18251 Decl *D, Expr *E, bool MightBeOdrUse) { 18252 if (SemaRef.isInOpenMPDeclareTargetContext()) 18253 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18254 18255 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18256 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18257 return; 18258 } 18259 18260 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18261 18262 // If this is a call to a method via a cast, also mark the method in the 18263 // derived class used in case codegen can devirtualize the call. 18264 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18265 if (!ME) 18266 return; 18267 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18268 if (!MD) 18269 return; 18270 // Only attempt to devirtualize if this is truly a virtual call. 18271 bool IsVirtualCall = MD->isVirtual() && 18272 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18273 if (!IsVirtualCall) 18274 return; 18275 18276 // If it's possible to devirtualize the call, mark the called function 18277 // referenced. 18278 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18279 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18280 if (DM) 18281 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18282 } 18283 18284 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18285 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18286 // TODO: update this with DR# once a defect report is filed. 18287 // C++11 defect. The address of a pure member should not be an ODR use, even 18288 // if it's a qualified reference. 18289 bool OdrUse = true; 18290 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18291 if (Method->isVirtual() && 18292 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18293 OdrUse = false; 18294 18295 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18296 if (!isConstantEvaluated() && FD->isConsteval() && 18297 !RebuildingImmediateInvocation) 18298 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18299 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18300 } 18301 18302 /// Perform reference-marking and odr-use handling for a MemberExpr. 18303 void Sema::MarkMemberReferenced(MemberExpr *E) { 18304 // C++11 [basic.def.odr]p2: 18305 // A non-overloaded function whose name appears as a potentially-evaluated 18306 // expression or a member of a set of candidate functions, if selected by 18307 // overload resolution when referred to from a potentially-evaluated 18308 // expression, is odr-used, unless it is a pure virtual function and its 18309 // name is not explicitly qualified. 18310 bool MightBeOdrUse = true; 18311 if (E->performsVirtualDispatch(getLangOpts())) { 18312 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18313 if (Method->isPure()) 18314 MightBeOdrUse = false; 18315 } 18316 SourceLocation Loc = 18317 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18318 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18319 } 18320 18321 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18322 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18323 for (VarDecl *VD : *E) 18324 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18325 } 18326 18327 /// Perform marking for a reference to an arbitrary declaration. It 18328 /// marks the declaration referenced, and performs odr-use checking for 18329 /// functions and variables. This method should not be used when building a 18330 /// normal expression which refers to a variable. 18331 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18332 bool MightBeOdrUse) { 18333 if (MightBeOdrUse) { 18334 if (auto *VD = dyn_cast<VarDecl>(D)) { 18335 MarkVariableReferenced(Loc, VD); 18336 return; 18337 } 18338 } 18339 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18340 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18341 return; 18342 } 18343 D->setReferenced(); 18344 } 18345 18346 namespace { 18347 // Mark all of the declarations used by a type as referenced. 18348 // FIXME: Not fully implemented yet! We need to have a better understanding 18349 // of when we're entering a context we should not recurse into. 18350 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18351 // TreeTransforms rebuilding the type in a new context. Rather than 18352 // duplicating the TreeTransform logic, we should consider reusing it here. 18353 // Currently that causes problems when rebuilding LambdaExprs. 18354 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18355 Sema &S; 18356 SourceLocation Loc; 18357 18358 public: 18359 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18360 18361 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18362 18363 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18364 }; 18365 } 18366 18367 bool MarkReferencedDecls::TraverseTemplateArgument( 18368 const TemplateArgument &Arg) { 18369 { 18370 // A non-type template argument is a constant-evaluated context. 18371 EnterExpressionEvaluationContext Evaluated( 18372 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18373 if (Arg.getKind() == TemplateArgument::Declaration) { 18374 if (Decl *D = Arg.getAsDecl()) 18375 S.MarkAnyDeclReferenced(Loc, D, true); 18376 } else if (Arg.getKind() == TemplateArgument::Expression) { 18377 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18378 } 18379 } 18380 18381 return Inherited::TraverseTemplateArgument(Arg); 18382 } 18383 18384 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18385 MarkReferencedDecls Marker(*this, Loc); 18386 Marker.TraverseType(T); 18387 } 18388 18389 namespace { 18390 /// Helper class that marks all of the declarations referenced by 18391 /// potentially-evaluated subexpressions as "referenced". 18392 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18393 public: 18394 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18395 bool SkipLocalVariables; 18396 18397 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18398 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18399 18400 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18401 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18402 } 18403 18404 void VisitDeclRefExpr(DeclRefExpr *E) { 18405 // If we were asked not to visit local variables, don't. 18406 if (SkipLocalVariables) { 18407 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18408 if (VD->hasLocalStorage()) 18409 return; 18410 } 18411 S.MarkDeclRefReferenced(E); 18412 } 18413 18414 void VisitMemberExpr(MemberExpr *E) { 18415 S.MarkMemberReferenced(E); 18416 Visit(E->getBase()); 18417 } 18418 }; 18419 } // namespace 18420 18421 /// Mark any declarations that appear within this expression or any 18422 /// potentially-evaluated subexpressions as "referenced". 18423 /// 18424 /// \param SkipLocalVariables If true, don't mark local variables as 18425 /// 'referenced'. 18426 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18427 bool SkipLocalVariables) { 18428 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18429 } 18430 18431 /// Emit a diagnostic that describes an effect on the run-time behavior 18432 /// of the program being compiled. 18433 /// 18434 /// This routine emits the given diagnostic when the code currently being 18435 /// type-checked is "potentially evaluated", meaning that there is a 18436 /// possibility that the code will actually be executable. Code in sizeof() 18437 /// expressions, code used only during overload resolution, etc., are not 18438 /// potentially evaluated. This routine will suppress such diagnostics or, 18439 /// in the absolutely nutty case of potentially potentially evaluated 18440 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18441 /// later. 18442 /// 18443 /// This routine should be used for all diagnostics that describe the run-time 18444 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18445 /// Failure to do so will likely result in spurious diagnostics or failures 18446 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18447 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18448 const PartialDiagnostic &PD) { 18449 switch (ExprEvalContexts.back().Context) { 18450 case ExpressionEvaluationContext::Unevaluated: 18451 case ExpressionEvaluationContext::UnevaluatedList: 18452 case ExpressionEvaluationContext::UnevaluatedAbstract: 18453 case ExpressionEvaluationContext::DiscardedStatement: 18454 // The argument will never be evaluated, so don't complain. 18455 break; 18456 18457 case ExpressionEvaluationContext::ConstantEvaluated: 18458 // Relevant diagnostics should be produced by constant evaluation. 18459 break; 18460 18461 case ExpressionEvaluationContext::PotentiallyEvaluated: 18462 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18463 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18464 FunctionScopes.back()->PossiblyUnreachableDiags. 18465 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18466 return true; 18467 } 18468 18469 // The initializer of a constexpr variable or of the first declaration of a 18470 // static data member is not syntactically a constant evaluated constant, 18471 // but nonetheless is always required to be a constant expression, so we 18472 // can skip diagnosing. 18473 // FIXME: Using the mangling context here is a hack. 18474 if (auto *VD = dyn_cast_or_null<VarDecl>( 18475 ExprEvalContexts.back().ManglingContextDecl)) { 18476 if (VD->isConstexpr() || 18477 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18478 break; 18479 // FIXME: For any other kind of variable, we should build a CFG for its 18480 // initializer and check whether the context in question is reachable. 18481 } 18482 18483 Diag(Loc, PD); 18484 return true; 18485 } 18486 18487 return false; 18488 } 18489 18490 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18491 const PartialDiagnostic &PD) { 18492 return DiagRuntimeBehavior( 18493 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18494 } 18495 18496 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18497 CallExpr *CE, FunctionDecl *FD) { 18498 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18499 return false; 18500 18501 // If we're inside a decltype's expression, don't check for a valid return 18502 // type or construct temporaries until we know whether this is the last call. 18503 if (ExprEvalContexts.back().ExprContext == 18504 ExpressionEvaluationContextRecord::EK_Decltype) { 18505 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18506 return false; 18507 } 18508 18509 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18510 FunctionDecl *FD; 18511 CallExpr *CE; 18512 18513 public: 18514 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18515 : FD(FD), CE(CE) { } 18516 18517 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18518 if (!FD) { 18519 S.Diag(Loc, diag::err_call_incomplete_return) 18520 << T << CE->getSourceRange(); 18521 return; 18522 } 18523 18524 S.Diag(Loc, diag::err_call_function_incomplete_return) 18525 << CE->getSourceRange() << FD << T; 18526 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18527 << FD->getDeclName(); 18528 } 18529 } Diagnoser(FD, CE); 18530 18531 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18532 return true; 18533 18534 return false; 18535 } 18536 18537 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18538 // will prevent this condition from triggering, which is what we want. 18539 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18540 SourceLocation Loc; 18541 18542 unsigned diagnostic = diag::warn_condition_is_assignment; 18543 bool IsOrAssign = false; 18544 18545 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18546 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18547 return; 18548 18549 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18550 18551 // Greylist some idioms by putting them into a warning subcategory. 18552 if (ObjCMessageExpr *ME 18553 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18554 Selector Sel = ME->getSelector(); 18555 18556 // self = [<foo> init...] 18557 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18558 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18559 18560 // <foo> = [<bar> nextObject] 18561 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18562 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18563 } 18564 18565 Loc = Op->getOperatorLoc(); 18566 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18567 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18568 return; 18569 18570 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18571 Loc = Op->getOperatorLoc(); 18572 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18573 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18574 else { 18575 // Not an assignment. 18576 return; 18577 } 18578 18579 Diag(Loc, diagnostic) << E->getSourceRange(); 18580 18581 SourceLocation Open = E->getBeginLoc(); 18582 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18583 Diag(Loc, diag::note_condition_assign_silence) 18584 << FixItHint::CreateInsertion(Open, "(") 18585 << FixItHint::CreateInsertion(Close, ")"); 18586 18587 if (IsOrAssign) 18588 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18589 << FixItHint::CreateReplacement(Loc, "!="); 18590 else 18591 Diag(Loc, diag::note_condition_assign_to_comparison) 18592 << FixItHint::CreateReplacement(Loc, "=="); 18593 } 18594 18595 /// Redundant parentheses over an equality comparison can indicate 18596 /// that the user intended an assignment used as condition. 18597 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18598 // Don't warn if the parens came from a macro. 18599 SourceLocation parenLoc = ParenE->getBeginLoc(); 18600 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18601 return; 18602 // Don't warn for dependent expressions. 18603 if (ParenE->isTypeDependent()) 18604 return; 18605 18606 Expr *E = ParenE->IgnoreParens(); 18607 18608 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18609 if (opE->getOpcode() == BO_EQ && 18610 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18611 == Expr::MLV_Valid) { 18612 SourceLocation Loc = opE->getOperatorLoc(); 18613 18614 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18615 SourceRange ParenERange = ParenE->getSourceRange(); 18616 Diag(Loc, diag::note_equality_comparison_silence) 18617 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18618 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18619 Diag(Loc, diag::note_equality_comparison_to_assign) 18620 << FixItHint::CreateReplacement(Loc, "="); 18621 } 18622 } 18623 18624 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18625 bool IsConstexpr) { 18626 DiagnoseAssignmentAsCondition(E); 18627 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18628 DiagnoseEqualityWithExtraParens(parenE); 18629 18630 ExprResult result = CheckPlaceholderExpr(E); 18631 if (result.isInvalid()) return ExprError(); 18632 E = result.get(); 18633 18634 if (!E->isTypeDependent()) { 18635 if (getLangOpts().CPlusPlus) 18636 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18637 18638 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18639 if (ERes.isInvalid()) 18640 return ExprError(); 18641 E = ERes.get(); 18642 18643 QualType T = E->getType(); 18644 if (!T->isScalarType()) { // C99 6.8.4.1p1 18645 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18646 << T << E->getSourceRange(); 18647 return ExprError(); 18648 } 18649 CheckBoolLikeConversion(E, Loc); 18650 } 18651 18652 return E; 18653 } 18654 18655 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18656 Expr *SubExpr, ConditionKind CK) { 18657 // Empty conditions are valid in for-statements. 18658 if (!SubExpr) 18659 return ConditionResult(); 18660 18661 ExprResult Cond; 18662 switch (CK) { 18663 case ConditionKind::Boolean: 18664 Cond = CheckBooleanCondition(Loc, SubExpr); 18665 break; 18666 18667 case ConditionKind::ConstexprIf: 18668 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18669 break; 18670 18671 case ConditionKind::Switch: 18672 Cond = CheckSwitchCondition(Loc, SubExpr); 18673 break; 18674 } 18675 if (Cond.isInvalid()) { 18676 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18677 {SubExpr}); 18678 if (!Cond.get()) 18679 return ConditionError(); 18680 } 18681 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18682 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18683 if (!FullExpr.get()) 18684 return ConditionError(); 18685 18686 return ConditionResult(*this, nullptr, FullExpr, 18687 CK == ConditionKind::ConstexprIf); 18688 } 18689 18690 namespace { 18691 /// A visitor for rebuilding a call to an __unknown_any expression 18692 /// to have an appropriate type. 18693 struct RebuildUnknownAnyFunction 18694 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18695 18696 Sema &S; 18697 18698 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18699 18700 ExprResult VisitStmt(Stmt *S) { 18701 llvm_unreachable("unexpected statement!"); 18702 } 18703 18704 ExprResult VisitExpr(Expr *E) { 18705 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18706 << E->getSourceRange(); 18707 return ExprError(); 18708 } 18709 18710 /// Rebuild an expression which simply semantically wraps another 18711 /// expression which it shares the type and value kind of. 18712 template <class T> ExprResult rebuildSugarExpr(T *E) { 18713 ExprResult SubResult = Visit(E->getSubExpr()); 18714 if (SubResult.isInvalid()) return ExprError(); 18715 18716 Expr *SubExpr = SubResult.get(); 18717 E->setSubExpr(SubExpr); 18718 E->setType(SubExpr->getType()); 18719 E->setValueKind(SubExpr->getValueKind()); 18720 assert(E->getObjectKind() == OK_Ordinary); 18721 return E; 18722 } 18723 18724 ExprResult VisitParenExpr(ParenExpr *E) { 18725 return rebuildSugarExpr(E); 18726 } 18727 18728 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18729 return rebuildSugarExpr(E); 18730 } 18731 18732 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18733 ExprResult SubResult = Visit(E->getSubExpr()); 18734 if (SubResult.isInvalid()) return ExprError(); 18735 18736 Expr *SubExpr = SubResult.get(); 18737 E->setSubExpr(SubExpr); 18738 E->setType(S.Context.getPointerType(SubExpr->getType())); 18739 assert(E->getValueKind() == VK_RValue); 18740 assert(E->getObjectKind() == OK_Ordinary); 18741 return E; 18742 } 18743 18744 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18745 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18746 18747 E->setType(VD->getType()); 18748 18749 assert(E->getValueKind() == VK_RValue); 18750 if (S.getLangOpts().CPlusPlus && 18751 !(isa<CXXMethodDecl>(VD) && 18752 cast<CXXMethodDecl>(VD)->isInstance())) 18753 E->setValueKind(VK_LValue); 18754 18755 return E; 18756 } 18757 18758 ExprResult VisitMemberExpr(MemberExpr *E) { 18759 return resolveDecl(E, E->getMemberDecl()); 18760 } 18761 18762 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18763 return resolveDecl(E, E->getDecl()); 18764 } 18765 }; 18766 } 18767 18768 /// Given a function expression of unknown-any type, try to rebuild it 18769 /// to have a function type. 18770 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18771 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18772 if (Result.isInvalid()) return ExprError(); 18773 return S.DefaultFunctionArrayConversion(Result.get()); 18774 } 18775 18776 namespace { 18777 /// A visitor for rebuilding an expression of type __unknown_anytype 18778 /// into one which resolves the type directly on the referring 18779 /// expression. Strict preservation of the original source 18780 /// structure is not a goal. 18781 struct RebuildUnknownAnyExpr 18782 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18783 18784 Sema &S; 18785 18786 /// The current destination type. 18787 QualType DestType; 18788 18789 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18790 : S(S), DestType(CastType) {} 18791 18792 ExprResult VisitStmt(Stmt *S) { 18793 llvm_unreachable("unexpected statement!"); 18794 } 18795 18796 ExprResult VisitExpr(Expr *E) { 18797 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18798 << E->getSourceRange(); 18799 return ExprError(); 18800 } 18801 18802 ExprResult VisitCallExpr(CallExpr *E); 18803 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18804 18805 /// Rebuild an expression which simply semantically wraps another 18806 /// expression which it shares the type and value kind of. 18807 template <class T> ExprResult rebuildSugarExpr(T *E) { 18808 ExprResult SubResult = Visit(E->getSubExpr()); 18809 if (SubResult.isInvalid()) return ExprError(); 18810 Expr *SubExpr = SubResult.get(); 18811 E->setSubExpr(SubExpr); 18812 E->setType(SubExpr->getType()); 18813 E->setValueKind(SubExpr->getValueKind()); 18814 assert(E->getObjectKind() == OK_Ordinary); 18815 return E; 18816 } 18817 18818 ExprResult VisitParenExpr(ParenExpr *E) { 18819 return rebuildSugarExpr(E); 18820 } 18821 18822 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18823 return rebuildSugarExpr(E); 18824 } 18825 18826 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18827 const PointerType *Ptr = DestType->getAs<PointerType>(); 18828 if (!Ptr) { 18829 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18830 << E->getSourceRange(); 18831 return ExprError(); 18832 } 18833 18834 if (isa<CallExpr>(E->getSubExpr())) { 18835 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18836 << E->getSourceRange(); 18837 return ExprError(); 18838 } 18839 18840 assert(E->getValueKind() == VK_RValue); 18841 assert(E->getObjectKind() == OK_Ordinary); 18842 E->setType(DestType); 18843 18844 // Build the sub-expression as if it were an object of the pointee type. 18845 DestType = Ptr->getPointeeType(); 18846 ExprResult SubResult = Visit(E->getSubExpr()); 18847 if (SubResult.isInvalid()) return ExprError(); 18848 E->setSubExpr(SubResult.get()); 18849 return E; 18850 } 18851 18852 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18853 18854 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18855 18856 ExprResult VisitMemberExpr(MemberExpr *E) { 18857 return resolveDecl(E, E->getMemberDecl()); 18858 } 18859 18860 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18861 return resolveDecl(E, E->getDecl()); 18862 } 18863 }; 18864 } 18865 18866 /// Rebuilds a call expression which yielded __unknown_anytype. 18867 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18868 Expr *CalleeExpr = E->getCallee(); 18869 18870 enum FnKind { 18871 FK_MemberFunction, 18872 FK_FunctionPointer, 18873 FK_BlockPointer 18874 }; 18875 18876 FnKind Kind; 18877 QualType CalleeType = CalleeExpr->getType(); 18878 if (CalleeType == S.Context.BoundMemberTy) { 18879 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18880 Kind = FK_MemberFunction; 18881 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18882 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18883 CalleeType = Ptr->getPointeeType(); 18884 Kind = FK_FunctionPointer; 18885 } else { 18886 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18887 Kind = FK_BlockPointer; 18888 } 18889 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18890 18891 // Verify that this is a legal result type of a function. 18892 if (DestType->isArrayType() || DestType->isFunctionType()) { 18893 unsigned diagID = diag::err_func_returning_array_function; 18894 if (Kind == FK_BlockPointer) 18895 diagID = diag::err_block_returning_array_function; 18896 18897 S.Diag(E->getExprLoc(), diagID) 18898 << DestType->isFunctionType() << DestType; 18899 return ExprError(); 18900 } 18901 18902 // Otherwise, go ahead and set DestType as the call's result. 18903 E->setType(DestType.getNonLValueExprType(S.Context)); 18904 E->setValueKind(Expr::getValueKindForType(DestType)); 18905 assert(E->getObjectKind() == OK_Ordinary); 18906 18907 // Rebuild the function type, replacing the result type with DestType. 18908 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18909 if (Proto) { 18910 // __unknown_anytype(...) is a special case used by the debugger when 18911 // it has no idea what a function's signature is. 18912 // 18913 // We want to build this call essentially under the K&R 18914 // unprototyped rules, but making a FunctionNoProtoType in C++ 18915 // would foul up all sorts of assumptions. However, we cannot 18916 // simply pass all arguments as variadic arguments, nor can we 18917 // portably just call the function under a non-variadic type; see 18918 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18919 // However, it turns out that in practice it is generally safe to 18920 // call a function declared as "A foo(B,C,D);" under the prototype 18921 // "A foo(B,C,D,...);". The only known exception is with the 18922 // Windows ABI, where any variadic function is implicitly cdecl 18923 // regardless of its normal CC. Therefore we change the parameter 18924 // types to match the types of the arguments. 18925 // 18926 // This is a hack, but it is far superior to moving the 18927 // corresponding target-specific code from IR-gen to Sema/AST. 18928 18929 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18930 SmallVector<QualType, 8> ArgTypes; 18931 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18932 ArgTypes.reserve(E->getNumArgs()); 18933 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18934 Expr *Arg = E->getArg(i); 18935 QualType ArgType = Arg->getType(); 18936 if (E->isLValue()) { 18937 ArgType = S.Context.getLValueReferenceType(ArgType); 18938 } else if (E->isXValue()) { 18939 ArgType = S.Context.getRValueReferenceType(ArgType); 18940 } 18941 ArgTypes.push_back(ArgType); 18942 } 18943 ParamTypes = ArgTypes; 18944 } 18945 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18946 Proto->getExtProtoInfo()); 18947 } else { 18948 DestType = S.Context.getFunctionNoProtoType(DestType, 18949 FnType->getExtInfo()); 18950 } 18951 18952 // Rebuild the appropriate pointer-to-function type. 18953 switch (Kind) { 18954 case FK_MemberFunction: 18955 // Nothing to do. 18956 break; 18957 18958 case FK_FunctionPointer: 18959 DestType = S.Context.getPointerType(DestType); 18960 break; 18961 18962 case FK_BlockPointer: 18963 DestType = S.Context.getBlockPointerType(DestType); 18964 break; 18965 } 18966 18967 // Finally, we can recurse. 18968 ExprResult CalleeResult = Visit(CalleeExpr); 18969 if (!CalleeResult.isUsable()) return ExprError(); 18970 E->setCallee(CalleeResult.get()); 18971 18972 // Bind a temporary if necessary. 18973 return S.MaybeBindToTemporary(E); 18974 } 18975 18976 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18977 // Verify that this is a legal result type of a call. 18978 if (DestType->isArrayType() || DestType->isFunctionType()) { 18979 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18980 << DestType->isFunctionType() << DestType; 18981 return ExprError(); 18982 } 18983 18984 // Rewrite the method result type if available. 18985 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18986 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18987 Method->setReturnType(DestType); 18988 } 18989 18990 // Change the type of the message. 18991 E->setType(DestType.getNonReferenceType()); 18992 E->setValueKind(Expr::getValueKindForType(DestType)); 18993 18994 return S.MaybeBindToTemporary(E); 18995 } 18996 18997 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18998 // The only case we should ever see here is a function-to-pointer decay. 18999 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19000 assert(E->getValueKind() == VK_RValue); 19001 assert(E->getObjectKind() == OK_Ordinary); 19002 19003 E->setType(DestType); 19004 19005 // Rebuild the sub-expression as the pointee (function) type. 19006 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19007 19008 ExprResult Result = Visit(E->getSubExpr()); 19009 if (!Result.isUsable()) return ExprError(); 19010 19011 E->setSubExpr(Result.get()); 19012 return E; 19013 } else if (E->getCastKind() == CK_LValueToRValue) { 19014 assert(E->getValueKind() == VK_RValue); 19015 assert(E->getObjectKind() == OK_Ordinary); 19016 19017 assert(isa<BlockPointerType>(E->getType())); 19018 19019 E->setType(DestType); 19020 19021 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19022 DestType = S.Context.getLValueReferenceType(DestType); 19023 19024 ExprResult Result = Visit(E->getSubExpr()); 19025 if (!Result.isUsable()) return ExprError(); 19026 19027 E->setSubExpr(Result.get()); 19028 return E; 19029 } else { 19030 llvm_unreachable("Unhandled cast type!"); 19031 } 19032 } 19033 19034 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19035 ExprValueKind ValueKind = VK_LValue; 19036 QualType Type = DestType; 19037 19038 // We know how to make this work for certain kinds of decls: 19039 19040 // - functions 19041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19042 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19043 DestType = Ptr->getPointeeType(); 19044 ExprResult Result = resolveDecl(E, VD); 19045 if (Result.isInvalid()) return ExprError(); 19046 return S.ImpCastExprToType(Result.get(), Type, 19047 CK_FunctionToPointerDecay, VK_RValue); 19048 } 19049 19050 if (!Type->isFunctionType()) { 19051 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19052 << VD << E->getSourceRange(); 19053 return ExprError(); 19054 } 19055 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19056 // We must match the FunctionDecl's type to the hack introduced in 19057 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19058 // type. See the lengthy commentary in that routine. 19059 QualType FDT = FD->getType(); 19060 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19061 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19062 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19063 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19064 SourceLocation Loc = FD->getLocation(); 19065 FunctionDecl *NewFD = FunctionDecl::Create( 19066 S.Context, FD->getDeclContext(), Loc, Loc, 19067 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19068 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19069 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19070 19071 if (FD->getQualifier()) 19072 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19073 19074 SmallVector<ParmVarDecl*, 16> Params; 19075 for (const auto &AI : FT->param_types()) { 19076 ParmVarDecl *Param = 19077 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19078 Param->setScopeInfo(0, Params.size()); 19079 Params.push_back(Param); 19080 } 19081 NewFD->setParams(Params); 19082 DRE->setDecl(NewFD); 19083 VD = DRE->getDecl(); 19084 } 19085 } 19086 19087 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19088 if (MD->isInstance()) { 19089 ValueKind = VK_RValue; 19090 Type = S.Context.BoundMemberTy; 19091 } 19092 19093 // Function references aren't l-values in C. 19094 if (!S.getLangOpts().CPlusPlus) 19095 ValueKind = VK_RValue; 19096 19097 // - variables 19098 } else if (isa<VarDecl>(VD)) { 19099 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19100 Type = RefTy->getPointeeType(); 19101 } else if (Type->isFunctionType()) { 19102 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19103 << VD << E->getSourceRange(); 19104 return ExprError(); 19105 } 19106 19107 // - nothing else 19108 } else { 19109 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19110 << VD << E->getSourceRange(); 19111 return ExprError(); 19112 } 19113 19114 // Modifying the declaration like this is friendly to IR-gen but 19115 // also really dangerous. 19116 VD->setType(DestType); 19117 E->setType(Type); 19118 E->setValueKind(ValueKind); 19119 return E; 19120 } 19121 19122 /// Check a cast of an unknown-any type. We intentionally only 19123 /// trigger this for C-style casts. 19124 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19125 Expr *CastExpr, CastKind &CastKind, 19126 ExprValueKind &VK, CXXCastPath &Path) { 19127 // The type we're casting to must be either void or complete. 19128 if (!CastType->isVoidType() && 19129 RequireCompleteType(TypeRange.getBegin(), CastType, 19130 diag::err_typecheck_cast_to_incomplete)) 19131 return ExprError(); 19132 19133 // Rewrite the casted expression from scratch. 19134 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19135 if (!result.isUsable()) return ExprError(); 19136 19137 CastExpr = result.get(); 19138 VK = CastExpr->getValueKind(); 19139 CastKind = CK_NoOp; 19140 19141 return CastExpr; 19142 } 19143 19144 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19145 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19146 } 19147 19148 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19149 Expr *arg, QualType ¶mType) { 19150 // If the syntactic form of the argument is not an explicit cast of 19151 // any sort, just do default argument promotion. 19152 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19153 if (!castArg) { 19154 ExprResult result = DefaultArgumentPromotion(arg); 19155 if (result.isInvalid()) return ExprError(); 19156 paramType = result.get()->getType(); 19157 return result; 19158 } 19159 19160 // Otherwise, use the type that was written in the explicit cast. 19161 assert(!arg->hasPlaceholderType()); 19162 paramType = castArg->getTypeAsWritten(); 19163 19164 // Copy-initialize a parameter of that type. 19165 InitializedEntity entity = 19166 InitializedEntity::InitializeParameter(Context, paramType, 19167 /*consumed*/ false); 19168 return PerformCopyInitialization(entity, callLoc, arg); 19169 } 19170 19171 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19172 Expr *orig = E; 19173 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19174 while (true) { 19175 E = E->IgnoreParenImpCasts(); 19176 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19177 E = call->getCallee(); 19178 diagID = diag::err_uncasted_call_of_unknown_any; 19179 } else { 19180 break; 19181 } 19182 } 19183 19184 SourceLocation loc; 19185 NamedDecl *d; 19186 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19187 loc = ref->getLocation(); 19188 d = ref->getDecl(); 19189 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19190 loc = mem->getMemberLoc(); 19191 d = mem->getMemberDecl(); 19192 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19193 diagID = diag::err_uncasted_call_of_unknown_any; 19194 loc = msg->getSelectorStartLoc(); 19195 d = msg->getMethodDecl(); 19196 if (!d) { 19197 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19198 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19199 << orig->getSourceRange(); 19200 return ExprError(); 19201 } 19202 } else { 19203 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19204 << E->getSourceRange(); 19205 return ExprError(); 19206 } 19207 19208 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19209 19210 // Never recoverable. 19211 return ExprError(); 19212 } 19213 19214 /// Check for operands with placeholder types and complain if found. 19215 /// Returns ExprError() if there was an error and no recovery was possible. 19216 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19217 if (!Context.isDependenceAllowed()) { 19218 // C cannot handle TypoExpr nodes on either side of a binop because it 19219 // doesn't handle dependent types properly, so make sure any TypoExprs have 19220 // been dealt with before checking the operands. 19221 ExprResult Result = CorrectDelayedTyposInExpr(E); 19222 if (!Result.isUsable()) return ExprError(); 19223 E = Result.get(); 19224 } 19225 19226 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19227 if (!placeholderType) return E; 19228 19229 switch (placeholderType->getKind()) { 19230 19231 // Overloaded expressions. 19232 case BuiltinType::Overload: { 19233 // Try to resolve a single function template specialization. 19234 // This is obligatory. 19235 ExprResult Result = E; 19236 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19237 return Result; 19238 19239 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19240 // leaves Result unchanged on failure. 19241 Result = E; 19242 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19243 return Result; 19244 19245 // If that failed, try to recover with a call. 19246 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19247 /*complain*/ true); 19248 return Result; 19249 } 19250 19251 // Bound member functions. 19252 case BuiltinType::BoundMember: { 19253 ExprResult result = E; 19254 const Expr *BME = E->IgnoreParens(); 19255 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19256 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19257 if (isa<CXXPseudoDestructorExpr>(BME)) { 19258 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19259 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19260 if (ME->getMemberNameInfo().getName().getNameKind() == 19261 DeclarationName::CXXDestructorName) 19262 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19263 } 19264 tryToRecoverWithCall(result, PD, 19265 /*complain*/ true); 19266 return result; 19267 } 19268 19269 // ARC unbridged casts. 19270 case BuiltinType::ARCUnbridgedCast: { 19271 Expr *realCast = stripARCUnbridgedCast(E); 19272 diagnoseARCUnbridgedCast(realCast); 19273 return realCast; 19274 } 19275 19276 // Expressions of unknown type. 19277 case BuiltinType::UnknownAny: 19278 return diagnoseUnknownAnyExpr(*this, E); 19279 19280 // Pseudo-objects. 19281 case BuiltinType::PseudoObject: 19282 return checkPseudoObjectRValue(E); 19283 19284 case BuiltinType::BuiltinFn: { 19285 // Accept __noop without parens by implicitly converting it to a call expr. 19286 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19287 if (DRE) { 19288 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19289 if (FD->getBuiltinID() == Builtin::BI__noop) { 19290 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19291 CK_BuiltinFnToFnPtr) 19292 .get(); 19293 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19294 VK_RValue, SourceLocation(), 19295 FPOptionsOverride()); 19296 } 19297 } 19298 19299 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19300 return ExprError(); 19301 } 19302 19303 case BuiltinType::IncompleteMatrixIdx: 19304 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19305 ->getRowIdx() 19306 ->getBeginLoc(), 19307 diag::err_matrix_incomplete_index); 19308 return ExprError(); 19309 19310 // Expressions of unknown type. 19311 case BuiltinType::OMPArraySection: 19312 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19313 return ExprError(); 19314 19315 // Expressions of unknown type. 19316 case BuiltinType::OMPArrayShaping: 19317 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19318 19319 case BuiltinType::OMPIterator: 19320 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19321 19322 // Everything else should be impossible. 19323 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19324 case BuiltinType::Id: 19325 #include "clang/Basic/OpenCLImageTypes.def" 19326 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19327 case BuiltinType::Id: 19328 #include "clang/Basic/OpenCLExtensionTypes.def" 19329 #define SVE_TYPE(Name, Id, SingletonId) \ 19330 case BuiltinType::Id: 19331 #include "clang/Basic/AArch64SVEACLETypes.def" 19332 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \ 19333 case BuiltinType::Id: 19334 #include "clang/Basic/PPCTypes.def" 19335 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19336 #define PLACEHOLDER_TYPE(Id, SingletonId) 19337 #include "clang/AST/BuiltinTypes.def" 19338 break; 19339 } 19340 19341 llvm_unreachable("invalid placeholder type!"); 19342 } 19343 19344 bool Sema::CheckCaseExpression(Expr *E) { 19345 if (E->isTypeDependent()) 19346 return true; 19347 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19348 return E->getType()->isIntegralOrEnumerationType(); 19349 return false; 19350 } 19351 19352 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19353 ExprResult 19354 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19355 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19356 "Unknown Objective-C Boolean value!"); 19357 QualType BoolT = Context.ObjCBuiltinBoolTy; 19358 if (!Context.getBOOLDecl()) { 19359 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19360 Sema::LookupOrdinaryName); 19361 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19362 NamedDecl *ND = Result.getFoundDecl(); 19363 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19364 Context.setBOOLDecl(TD); 19365 } 19366 } 19367 if (Context.getBOOLDecl()) 19368 BoolT = Context.getBOOLType(); 19369 return new (Context) 19370 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19371 } 19372 19373 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19374 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19375 SourceLocation RParen) { 19376 19377 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19378 19379 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19380 return Spec.getPlatform() == Platform; 19381 }); 19382 19383 VersionTuple Version; 19384 if (Spec != AvailSpecs.end()) 19385 Version = Spec->getVersion(); 19386 19387 // The use of `@available` in the enclosing function should be analyzed to 19388 // warn when it's used inappropriately (i.e. not if(@available)). 19389 if (getCurFunctionOrMethodDecl()) 19390 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19391 else if (getCurBlock() || getCurLambda()) 19392 getCurFunction()->HasPotentialAvailabilityViolations = true; 19393 19394 return new (Context) 19395 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19396 } 19397 19398 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19399 ArrayRef<Expr *> SubExprs, QualType T) { 19400 if (!Context.getLangOpts().RecoveryAST) 19401 return ExprError(); 19402 19403 if (isSFINAEContext()) 19404 return ExprError(); 19405 19406 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19407 // We don't know the concrete type, fallback to dependent type. 19408 T = Context.DependentTy; 19409 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19410 } 19411