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 (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.setImplicitSelfParam(&II); 2855 CXXScopeSpec SelfScopeSpec; 2856 SourceLocation TemplateKWLoc; 2857 ExprResult SelfExpr = 2858 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2859 /*HasTrailingLParen=*/false, 2860 /*IsAddressOfOperand=*/false); 2861 if (SelfExpr.isInvalid()) 2862 return ExprError(); 2863 2864 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2865 if (SelfExpr.isInvalid()) 2866 return ExprError(); 2867 2868 MarkAnyDeclReferenced(Loc, IV, true); 2869 2870 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2871 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2872 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2873 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2874 2875 ObjCIvarRefExpr *Result = new (Context) 2876 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2877 IV->getLocation(), SelfExpr.get(), true, true); 2878 2879 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2880 if (!isUnevaluatedContext() && 2881 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2882 getCurFunction()->recordUseOfWeak(Result); 2883 } 2884 if (getLangOpts().ObjCAutoRefCount) 2885 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2886 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2887 2888 return Result; 2889 } 2890 2891 /// The parser has read a name in, and Sema has detected that we're currently 2892 /// inside an ObjC method. Perform some additional checks and determine if we 2893 /// should form a reference to an ivar. If so, build an expression referencing 2894 /// that ivar. 2895 ExprResult 2896 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2897 IdentifierInfo *II, bool AllowBuiltinCreation) { 2898 // FIXME: Integrate this lookup step into LookupParsedName. 2899 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2900 if (Ivar.isInvalid()) 2901 return ExprError(); 2902 if (Ivar.isUsable()) 2903 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2904 cast<ObjCIvarDecl>(Ivar.get())); 2905 2906 if (Lookup.empty() && II && AllowBuiltinCreation) 2907 LookupBuiltin(Lookup); 2908 2909 // Sentinel value saying that we didn't do anything special. 2910 return ExprResult(false); 2911 } 2912 2913 /// Cast a base object to a member's actual type. 2914 /// 2915 /// There are two relevant checks: 2916 /// 2917 /// C++ [class.access.base]p7: 2918 /// 2919 /// If a class member access operator [...] is used to access a non-static 2920 /// data member or non-static member function, the reference is ill-formed if 2921 /// the left operand [...] cannot be implicitly converted to a pointer to the 2922 /// naming class of the right operand. 2923 /// 2924 /// C++ [expr.ref]p7: 2925 /// 2926 /// If E2 is a non-static data member or a non-static member function, the 2927 /// program is ill-formed if the class of which E2 is directly a member is an 2928 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2929 /// 2930 /// Note that the latter check does not consider access; the access of the 2931 /// "real" base class is checked as appropriate when checking the access of the 2932 /// member name. 2933 ExprResult 2934 Sema::PerformObjectMemberConversion(Expr *From, 2935 NestedNameSpecifier *Qualifier, 2936 NamedDecl *FoundDecl, 2937 NamedDecl *Member) { 2938 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2939 if (!RD) 2940 return From; 2941 2942 QualType DestRecordType; 2943 QualType DestType; 2944 QualType FromRecordType; 2945 QualType FromType = From->getType(); 2946 bool PointerConversions = false; 2947 if (isa<FieldDecl>(Member)) { 2948 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2949 auto FromPtrType = FromType->getAs<PointerType>(); 2950 DestRecordType = Context.getAddrSpaceQualType( 2951 DestRecordType, FromPtrType 2952 ? FromType->getPointeeType().getAddressSpace() 2953 : FromType.getAddressSpace()); 2954 2955 if (FromPtrType) { 2956 DestType = Context.getPointerType(DestRecordType); 2957 FromRecordType = FromPtrType->getPointeeType(); 2958 PointerConversions = true; 2959 } else { 2960 DestType = DestRecordType; 2961 FromRecordType = FromType; 2962 } 2963 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2964 if (Method->isStatic()) 2965 return From; 2966 2967 DestType = Method->getThisType(); 2968 DestRecordType = DestType->getPointeeType(); 2969 2970 if (FromType->getAs<PointerType>()) { 2971 FromRecordType = FromType->getPointeeType(); 2972 PointerConversions = true; 2973 } else { 2974 FromRecordType = FromType; 2975 DestType = DestRecordType; 2976 } 2977 2978 LangAS FromAS = FromRecordType.getAddressSpace(); 2979 LangAS DestAS = DestRecordType.getAddressSpace(); 2980 if (FromAS != DestAS) { 2981 QualType FromRecordTypeWithoutAS = 2982 Context.removeAddrSpaceQualType(FromRecordType); 2983 QualType FromTypeWithDestAS = 2984 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2985 if (PointerConversions) 2986 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2987 From = ImpCastExprToType(From, FromTypeWithDestAS, 2988 CK_AddressSpaceConversion, From->getValueKind()) 2989 .get(); 2990 } 2991 } else { 2992 // No conversion necessary. 2993 return From; 2994 } 2995 2996 if (DestType->isDependentType() || FromType->isDependentType()) 2997 return From; 2998 2999 // If the unqualified types are the same, no conversion is necessary. 3000 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3001 return From; 3002 3003 SourceRange FromRange = From->getSourceRange(); 3004 SourceLocation FromLoc = FromRange.getBegin(); 3005 3006 ExprValueKind VK = From->getValueKind(); 3007 3008 // C++ [class.member.lookup]p8: 3009 // [...] Ambiguities can often be resolved by qualifying a name with its 3010 // class name. 3011 // 3012 // If the member was a qualified name and the qualified referred to a 3013 // specific base subobject type, we'll cast to that intermediate type 3014 // first and then to the object in which the member is declared. That allows 3015 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3016 // 3017 // class Base { public: int x; }; 3018 // class Derived1 : public Base { }; 3019 // class Derived2 : public Base { }; 3020 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3021 // 3022 // void VeryDerived::f() { 3023 // x = 17; // error: ambiguous base subobjects 3024 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3025 // } 3026 if (Qualifier && Qualifier->getAsType()) { 3027 QualType QType = QualType(Qualifier->getAsType(), 0); 3028 assert(QType->isRecordType() && "lookup done with non-record type"); 3029 3030 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3031 3032 // In C++98, the qualifier type doesn't actually have to be a base 3033 // type of the object type, in which case we just ignore it. 3034 // Otherwise build the appropriate casts. 3035 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3036 CXXCastPath BasePath; 3037 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3038 FromLoc, FromRange, &BasePath)) 3039 return ExprError(); 3040 3041 if (PointerConversions) 3042 QType = Context.getPointerType(QType); 3043 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3044 VK, &BasePath).get(); 3045 3046 FromType = QType; 3047 FromRecordType = QRecordType; 3048 3049 // If the qualifier type was the same as the destination type, 3050 // we're done. 3051 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3052 return From; 3053 } 3054 } 3055 3056 CXXCastPath BasePath; 3057 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3058 FromLoc, FromRange, &BasePath, 3059 /*IgnoreAccess=*/true)) 3060 return ExprError(); 3061 3062 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3063 VK, &BasePath); 3064 } 3065 3066 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3067 const LookupResult &R, 3068 bool HasTrailingLParen) { 3069 // Only when used directly as the postfix-expression of a call. 3070 if (!HasTrailingLParen) 3071 return false; 3072 3073 // Never if a scope specifier was provided. 3074 if (SS.isSet()) 3075 return false; 3076 3077 // Only in C++ or ObjC++. 3078 if (!getLangOpts().CPlusPlus) 3079 return false; 3080 3081 // Turn off ADL when we find certain kinds of declarations during 3082 // normal lookup: 3083 for (NamedDecl *D : R) { 3084 // C++0x [basic.lookup.argdep]p3: 3085 // -- a declaration of a class member 3086 // Since using decls preserve this property, we check this on the 3087 // original decl. 3088 if (D->isCXXClassMember()) 3089 return false; 3090 3091 // C++0x [basic.lookup.argdep]p3: 3092 // -- a block-scope function declaration that is not a 3093 // using-declaration 3094 // NOTE: we also trigger this for function templates (in fact, we 3095 // don't check the decl type at all, since all other decl types 3096 // turn off ADL anyway). 3097 if (isa<UsingShadowDecl>(D)) 3098 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3099 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3100 return false; 3101 3102 // C++0x [basic.lookup.argdep]p3: 3103 // -- a declaration that is neither a function or a function 3104 // template 3105 // And also for builtin functions. 3106 if (isa<FunctionDecl>(D)) { 3107 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3108 3109 // But also builtin functions. 3110 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3111 return false; 3112 } else if (!isa<FunctionTemplateDecl>(D)) 3113 return false; 3114 } 3115 3116 return true; 3117 } 3118 3119 3120 /// Diagnoses obvious problems with the use of the given declaration 3121 /// as an expression. This is only actually called for lookups that 3122 /// were not overloaded, and it doesn't promise that the declaration 3123 /// will in fact be used. 3124 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3125 if (D->isInvalidDecl()) 3126 return true; 3127 3128 if (isa<TypedefNameDecl>(D)) { 3129 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3130 return true; 3131 } 3132 3133 if (isa<ObjCInterfaceDecl>(D)) { 3134 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3135 return true; 3136 } 3137 3138 if (isa<NamespaceDecl>(D)) { 3139 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3140 return true; 3141 } 3142 3143 return false; 3144 } 3145 3146 // Certain multiversion types should be treated as overloaded even when there is 3147 // only one result. 3148 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3149 assert(R.isSingleResult() && "Expected only a single result"); 3150 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3151 return FD && 3152 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3153 } 3154 3155 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3156 LookupResult &R, bool NeedsADL, 3157 bool AcceptInvalidDecl) { 3158 // If this is a single, fully-resolved result and we don't need ADL, 3159 // just build an ordinary singleton decl ref. 3160 if (!NeedsADL && R.isSingleResult() && 3161 !R.getAsSingle<FunctionTemplateDecl>() && 3162 !ShouldLookupResultBeMultiVersionOverload(R)) 3163 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3164 R.getRepresentativeDecl(), nullptr, 3165 AcceptInvalidDecl); 3166 3167 // We only need to check the declaration if there's exactly one 3168 // result, because in the overloaded case the results can only be 3169 // functions and function templates. 3170 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3171 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3172 return ExprError(); 3173 3174 // Otherwise, just build an unresolved lookup expression. Suppress 3175 // any lookup-related diagnostics; we'll hash these out later, when 3176 // we've picked a target. 3177 R.suppressDiagnostics(); 3178 3179 UnresolvedLookupExpr *ULE 3180 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3181 SS.getWithLocInContext(Context), 3182 R.getLookupNameInfo(), 3183 NeedsADL, R.isOverloadedResult(), 3184 R.begin(), R.end()); 3185 3186 return ULE; 3187 } 3188 3189 static void 3190 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3191 ValueDecl *var, DeclContext *DC); 3192 3193 /// Complete semantic analysis for a reference to the given declaration. 3194 ExprResult Sema::BuildDeclarationNameExpr( 3195 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3196 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3197 bool AcceptInvalidDecl) { 3198 assert(D && "Cannot refer to a NULL declaration"); 3199 assert(!isa<FunctionTemplateDecl>(D) && 3200 "Cannot refer unambiguously to a function template"); 3201 3202 SourceLocation Loc = NameInfo.getLoc(); 3203 if (CheckDeclInExpr(*this, Loc, D)) 3204 return ExprError(); 3205 3206 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3207 // Specifically diagnose references to class templates that are missing 3208 // a template argument list. 3209 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3210 return ExprError(); 3211 } 3212 3213 // Make sure that we're referring to a value. 3214 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3215 if (!VD) { 3216 Diag(Loc, diag::err_ref_non_value) 3217 << D << SS.getRange(); 3218 Diag(D->getLocation(), diag::note_declared_at); 3219 return ExprError(); 3220 } 3221 3222 // Check whether this declaration can be used. Note that we suppress 3223 // this check when we're going to perform argument-dependent lookup 3224 // on this function name, because this might not be the function 3225 // that overload resolution actually selects. 3226 if (DiagnoseUseOfDecl(VD, Loc)) 3227 return ExprError(); 3228 3229 // Only create DeclRefExpr's for valid Decl's. 3230 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3231 return ExprError(); 3232 3233 // Handle members of anonymous structs and unions. If we got here, 3234 // and the reference is to a class member indirect field, then this 3235 // must be the subject of a pointer-to-member expression. 3236 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3237 if (!indirectField->isCXXClassMember()) 3238 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3239 indirectField); 3240 3241 { 3242 QualType type = VD->getType(); 3243 if (type.isNull()) 3244 return ExprError(); 3245 ExprValueKind valueKind = VK_RValue; 3246 3247 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3248 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3249 // is expanded by some outer '...' in the context of the use. 3250 type = type.getNonPackExpansionType(); 3251 3252 switch (D->getKind()) { 3253 // Ignore all the non-ValueDecl kinds. 3254 #define ABSTRACT_DECL(kind) 3255 #define VALUE(type, base) 3256 #define DECL(type, base) \ 3257 case Decl::type: 3258 #include "clang/AST/DeclNodes.inc" 3259 llvm_unreachable("invalid value decl kind"); 3260 3261 // These shouldn't make it here. 3262 case Decl::ObjCAtDefsField: 3263 llvm_unreachable("forming non-member reference to ivar?"); 3264 3265 // Enum constants are always r-values and never references. 3266 // Unresolved using declarations are dependent. 3267 case Decl::EnumConstant: 3268 case Decl::UnresolvedUsingValue: 3269 case Decl::OMPDeclareReduction: 3270 case Decl::OMPDeclareMapper: 3271 valueKind = VK_RValue; 3272 break; 3273 3274 // Fields and indirect fields that got here must be for 3275 // pointer-to-member expressions; we just call them l-values for 3276 // internal consistency, because this subexpression doesn't really 3277 // exist in the high-level semantics. 3278 case Decl::Field: 3279 case Decl::IndirectField: 3280 case Decl::ObjCIvar: 3281 assert(getLangOpts().CPlusPlus && 3282 "building reference to field in C?"); 3283 3284 // These can't have reference type in well-formed programs, but 3285 // for internal consistency we do this anyway. 3286 type = type.getNonReferenceType(); 3287 valueKind = VK_LValue; 3288 break; 3289 3290 // Non-type template parameters are either l-values or r-values 3291 // depending on the type. 3292 case Decl::NonTypeTemplateParm: { 3293 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3294 type = reftype->getPointeeType(); 3295 valueKind = VK_LValue; // even if the parameter is an r-value reference 3296 break; 3297 } 3298 3299 // [expr.prim.id.unqual]p2: 3300 // If the entity is a template parameter object for a template 3301 // parameter of type T, the type of the expression is const T. 3302 // [...] The expression is an lvalue if the entity is a [...] template 3303 // parameter object. 3304 if (type->isRecordType()) { 3305 type = type.getUnqualifiedType().withConst(); 3306 valueKind = VK_LValue; 3307 break; 3308 } 3309 3310 // For non-references, we need to strip qualifiers just in case 3311 // the template parameter was declared as 'const int' or whatever. 3312 valueKind = VK_RValue; 3313 type = type.getUnqualifiedType(); 3314 break; 3315 } 3316 3317 case Decl::Var: 3318 case Decl::VarTemplateSpecialization: 3319 case Decl::VarTemplatePartialSpecialization: 3320 case Decl::Decomposition: 3321 case Decl::OMPCapturedExpr: 3322 // In C, "extern void blah;" is valid and is an r-value. 3323 if (!getLangOpts().CPlusPlus && 3324 !type.hasQualifiers() && 3325 type->isVoidType()) { 3326 valueKind = VK_RValue; 3327 break; 3328 } 3329 LLVM_FALLTHROUGH; 3330 3331 case Decl::ImplicitParam: 3332 case Decl::ParmVar: { 3333 // These are always l-values. 3334 valueKind = VK_LValue; 3335 type = type.getNonReferenceType(); 3336 3337 // FIXME: Does the addition of const really only apply in 3338 // potentially-evaluated contexts? Since the variable isn't actually 3339 // captured in an unevaluated context, it seems that the answer is no. 3340 if (!isUnevaluatedContext()) { 3341 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3342 if (!CapturedType.isNull()) 3343 type = CapturedType; 3344 } 3345 3346 break; 3347 } 3348 3349 case Decl::Binding: { 3350 // These are always lvalues. 3351 valueKind = VK_LValue; 3352 type = type.getNonReferenceType(); 3353 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3354 // decides how that's supposed to work. 3355 auto *BD = cast<BindingDecl>(VD); 3356 if (BD->getDeclContext() != CurContext) { 3357 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3358 if (DD && DD->hasLocalStorage()) 3359 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3360 } 3361 break; 3362 } 3363 3364 case Decl::Function: { 3365 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3366 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3367 type = Context.BuiltinFnTy; 3368 valueKind = VK_RValue; 3369 break; 3370 } 3371 } 3372 3373 const FunctionType *fty = type->castAs<FunctionType>(); 3374 3375 // If we're referring to a function with an __unknown_anytype 3376 // result type, make the entire expression __unknown_anytype. 3377 if (fty->getReturnType() == Context.UnknownAnyTy) { 3378 type = Context.UnknownAnyTy; 3379 valueKind = VK_RValue; 3380 break; 3381 } 3382 3383 // Functions are l-values in C++. 3384 if (getLangOpts().CPlusPlus) { 3385 valueKind = VK_LValue; 3386 break; 3387 } 3388 3389 // C99 DR 316 says that, if a function type comes from a 3390 // function definition (without a prototype), that type is only 3391 // used for checking compatibility. Therefore, when referencing 3392 // the function, we pretend that we don't have the full function 3393 // type. 3394 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3395 isa<FunctionProtoType>(fty)) 3396 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3397 fty->getExtInfo()); 3398 3399 // Functions are r-values in C. 3400 valueKind = VK_RValue; 3401 break; 3402 } 3403 3404 case Decl::CXXDeductionGuide: 3405 llvm_unreachable("building reference to deduction guide"); 3406 3407 case Decl::MSProperty: 3408 case Decl::MSGuid: 3409 case Decl::TemplateParamObject: 3410 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3411 // capture in OpenMP, or duplicated between host and device? 3412 valueKind = VK_LValue; 3413 break; 3414 3415 case Decl::CXXMethod: 3416 // If we're referring to a method with an __unknown_anytype 3417 // result type, make the entire expression __unknown_anytype. 3418 // This should only be possible with a type written directly. 3419 if (const FunctionProtoType *proto 3420 = dyn_cast<FunctionProtoType>(VD->getType())) 3421 if (proto->getReturnType() == Context.UnknownAnyTy) { 3422 type = Context.UnknownAnyTy; 3423 valueKind = VK_RValue; 3424 break; 3425 } 3426 3427 // C++ methods are l-values if static, r-values if non-static. 3428 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3429 valueKind = VK_LValue; 3430 break; 3431 } 3432 LLVM_FALLTHROUGH; 3433 3434 case Decl::CXXConversion: 3435 case Decl::CXXDestructor: 3436 case Decl::CXXConstructor: 3437 valueKind = VK_RValue; 3438 break; 3439 } 3440 3441 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3442 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3443 TemplateArgs); 3444 } 3445 } 3446 3447 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3448 SmallString<32> &Target) { 3449 Target.resize(CharByteWidth * (Source.size() + 1)); 3450 char *ResultPtr = &Target[0]; 3451 const llvm::UTF8 *ErrorPtr; 3452 bool success = 3453 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3454 (void)success; 3455 assert(success); 3456 Target.resize(ResultPtr - &Target[0]); 3457 } 3458 3459 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3460 PredefinedExpr::IdentKind IK) { 3461 // Pick the current block, lambda, captured statement or function. 3462 Decl *currentDecl = nullptr; 3463 if (const BlockScopeInfo *BSI = getCurBlock()) 3464 currentDecl = BSI->TheDecl; 3465 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3466 currentDecl = LSI->CallOperator; 3467 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3468 currentDecl = CSI->TheCapturedDecl; 3469 else 3470 currentDecl = getCurFunctionOrMethodDecl(); 3471 3472 if (!currentDecl) { 3473 Diag(Loc, diag::ext_predef_outside_function); 3474 currentDecl = Context.getTranslationUnitDecl(); 3475 } 3476 3477 QualType ResTy; 3478 StringLiteral *SL = nullptr; 3479 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3480 ResTy = Context.DependentTy; 3481 else { 3482 // Pre-defined identifiers are of type char[x], where x is the length of 3483 // the string. 3484 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3485 unsigned Length = Str.length(); 3486 3487 llvm::APInt LengthI(32, Length + 1); 3488 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3489 ResTy = 3490 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3491 SmallString<32> RawChars; 3492 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3493 Str, RawChars); 3494 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3495 ArrayType::Normal, 3496 /*IndexTypeQuals*/ 0); 3497 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3498 /*Pascal*/ false, ResTy, Loc); 3499 } else { 3500 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3501 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3502 ArrayType::Normal, 3503 /*IndexTypeQuals*/ 0); 3504 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3505 /*Pascal*/ false, ResTy, Loc); 3506 } 3507 } 3508 3509 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3510 } 3511 3512 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3513 PredefinedExpr::IdentKind IK; 3514 3515 switch (Kind) { 3516 default: llvm_unreachable("Unknown simple primary expr!"); 3517 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3518 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3519 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3520 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3521 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3522 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3523 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3524 } 3525 3526 return BuildPredefinedExpr(Loc, IK); 3527 } 3528 3529 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3530 SmallString<16> CharBuffer; 3531 bool Invalid = false; 3532 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3533 if (Invalid) 3534 return ExprError(); 3535 3536 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3537 PP, Tok.getKind()); 3538 if (Literal.hadError()) 3539 return ExprError(); 3540 3541 QualType Ty; 3542 if (Literal.isWide()) 3543 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3544 else if (Literal.isUTF8() && getLangOpts().Char8) 3545 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3546 else if (Literal.isUTF16()) 3547 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3548 else if (Literal.isUTF32()) 3549 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3550 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3551 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3552 else 3553 Ty = Context.CharTy; // 'x' -> char in C++ 3554 3555 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3556 if (Literal.isWide()) 3557 Kind = CharacterLiteral::Wide; 3558 else if (Literal.isUTF16()) 3559 Kind = CharacterLiteral::UTF16; 3560 else if (Literal.isUTF32()) 3561 Kind = CharacterLiteral::UTF32; 3562 else if (Literal.isUTF8()) 3563 Kind = CharacterLiteral::UTF8; 3564 3565 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3566 Tok.getLocation()); 3567 3568 if (Literal.getUDSuffix().empty()) 3569 return Lit; 3570 3571 // We're building a user-defined literal. 3572 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3573 SourceLocation UDSuffixLoc = 3574 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3575 3576 // Make sure we're allowed user-defined literals here. 3577 if (!UDLScope) 3578 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3579 3580 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3581 // operator "" X (ch) 3582 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3583 Lit, Tok.getLocation()); 3584 } 3585 3586 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3587 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3588 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3589 Context.IntTy, Loc); 3590 } 3591 3592 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3593 QualType Ty, SourceLocation Loc) { 3594 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3595 3596 using llvm::APFloat; 3597 APFloat Val(Format); 3598 3599 APFloat::opStatus result = Literal.GetFloatValue(Val); 3600 3601 // Overflow is always an error, but underflow is only an error if 3602 // we underflowed to zero (APFloat reports denormals as underflow). 3603 if ((result & APFloat::opOverflow) || 3604 ((result & APFloat::opUnderflow) && Val.isZero())) { 3605 unsigned diagnostic; 3606 SmallString<20> buffer; 3607 if (result & APFloat::opOverflow) { 3608 diagnostic = diag::warn_float_overflow; 3609 APFloat::getLargest(Format).toString(buffer); 3610 } else { 3611 diagnostic = diag::warn_float_underflow; 3612 APFloat::getSmallest(Format).toString(buffer); 3613 } 3614 3615 S.Diag(Loc, diagnostic) 3616 << Ty 3617 << StringRef(buffer.data(), buffer.size()); 3618 } 3619 3620 bool isExact = (result == APFloat::opOK); 3621 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3622 } 3623 3624 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3625 assert(E && "Invalid expression"); 3626 3627 if (E->isValueDependent()) 3628 return false; 3629 3630 QualType QT = E->getType(); 3631 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3632 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3633 return true; 3634 } 3635 3636 llvm::APSInt ValueAPS; 3637 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3638 3639 if (R.isInvalid()) 3640 return true; 3641 3642 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3643 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3644 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3645 << ValueAPS.toString(10) << ValueIsPositive; 3646 return true; 3647 } 3648 3649 return false; 3650 } 3651 3652 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3653 // Fast path for a single digit (which is quite common). A single digit 3654 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3655 if (Tok.getLength() == 1) { 3656 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3657 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3658 } 3659 3660 SmallString<128> SpellingBuffer; 3661 // NumericLiteralParser wants to overread by one character. Add padding to 3662 // the buffer in case the token is copied to the buffer. If getSpelling() 3663 // returns a StringRef to the memory buffer, it should have a null char at 3664 // the EOF, so it is also safe. 3665 SpellingBuffer.resize(Tok.getLength() + 1); 3666 3667 // Get the spelling of the token, which eliminates trigraphs, etc. 3668 bool Invalid = false; 3669 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3670 if (Invalid) 3671 return ExprError(); 3672 3673 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3674 PP.getSourceManager(), PP.getLangOpts(), 3675 PP.getTargetInfo(), PP.getDiagnostics()); 3676 if (Literal.hadError) 3677 return ExprError(); 3678 3679 if (Literal.hasUDSuffix()) { 3680 // We're building a user-defined literal. 3681 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3682 SourceLocation UDSuffixLoc = 3683 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3684 3685 // Make sure we're allowed user-defined literals here. 3686 if (!UDLScope) 3687 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3688 3689 QualType CookedTy; 3690 if (Literal.isFloatingLiteral()) { 3691 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3692 // long double, the literal is treated as a call of the form 3693 // operator "" X (f L) 3694 CookedTy = Context.LongDoubleTy; 3695 } else { 3696 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3697 // unsigned long long, the literal is treated as a call of the form 3698 // operator "" X (n ULL) 3699 CookedTy = Context.UnsignedLongLongTy; 3700 } 3701 3702 DeclarationName OpName = 3703 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3704 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3705 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3706 3707 SourceLocation TokLoc = Tok.getLocation(); 3708 3709 // Perform literal operator lookup to determine if we're building a raw 3710 // literal or a cooked one. 3711 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3712 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3713 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3714 /*AllowStringTemplatePack*/ false, 3715 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3716 case LOLR_ErrorNoDiagnostic: 3717 // Lookup failure for imaginary constants isn't fatal, there's still the 3718 // GNU extension producing _Complex types. 3719 break; 3720 case LOLR_Error: 3721 return ExprError(); 3722 case LOLR_Cooked: { 3723 Expr *Lit; 3724 if (Literal.isFloatingLiteral()) { 3725 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3726 } else { 3727 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3728 if (Literal.GetIntegerValue(ResultVal)) 3729 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3730 << /* Unsigned */ 1; 3731 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3732 Tok.getLocation()); 3733 } 3734 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3735 } 3736 3737 case LOLR_Raw: { 3738 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3739 // literal is treated as a call of the form 3740 // operator "" X ("n") 3741 unsigned Length = Literal.getUDSuffixOffset(); 3742 QualType StrTy = Context.getConstantArrayType( 3743 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3744 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3745 Expr *Lit = StringLiteral::Create( 3746 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3747 /*Pascal*/false, StrTy, &TokLoc, 1); 3748 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3749 } 3750 3751 case LOLR_Template: { 3752 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3753 // template), L is treated as a call fo the form 3754 // operator "" X <'c1', 'c2', ... 'ck'>() 3755 // where n is the source character sequence c1 c2 ... ck. 3756 TemplateArgumentListInfo ExplicitArgs; 3757 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3758 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3759 llvm::APSInt Value(CharBits, CharIsUnsigned); 3760 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3761 Value = TokSpelling[I]; 3762 TemplateArgument Arg(Context, Value, Context.CharTy); 3763 TemplateArgumentLocInfo ArgInfo; 3764 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3765 } 3766 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3767 &ExplicitArgs); 3768 } 3769 case LOLR_StringTemplatePack: 3770 llvm_unreachable("unexpected literal operator lookup result"); 3771 } 3772 } 3773 3774 Expr *Res; 3775 3776 if (Literal.isFixedPointLiteral()) { 3777 QualType Ty; 3778 3779 if (Literal.isAccum) { 3780 if (Literal.isHalf) { 3781 Ty = Context.ShortAccumTy; 3782 } else if (Literal.isLong) { 3783 Ty = Context.LongAccumTy; 3784 } else { 3785 Ty = Context.AccumTy; 3786 } 3787 } else if (Literal.isFract) { 3788 if (Literal.isHalf) { 3789 Ty = Context.ShortFractTy; 3790 } else if (Literal.isLong) { 3791 Ty = Context.LongFractTy; 3792 } else { 3793 Ty = Context.FractTy; 3794 } 3795 } 3796 3797 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3798 3799 bool isSigned = !Literal.isUnsigned; 3800 unsigned scale = Context.getFixedPointScale(Ty); 3801 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3802 3803 llvm::APInt Val(bit_width, 0, isSigned); 3804 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3805 bool ValIsZero = Val.isNullValue() && !Overflowed; 3806 3807 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3808 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3809 // Clause 6.4.4 - The value of a constant shall be in the range of 3810 // representable values for its type, with exception for constants of a 3811 // fract type with a value of exactly 1; such a constant shall denote 3812 // the maximal value for the type. 3813 --Val; 3814 else if (Val.ugt(MaxVal) || Overflowed) 3815 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3816 3817 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3818 Tok.getLocation(), scale); 3819 } else if (Literal.isFloatingLiteral()) { 3820 QualType Ty; 3821 if (Literal.isHalf){ 3822 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3823 Ty = Context.HalfTy; 3824 else { 3825 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3826 return ExprError(); 3827 } 3828 } else if (Literal.isFloat) 3829 Ty = Context.FloatTy; 3830 else if (Literal.isLong) 3831 Ty = Context.LongDoubleTy; 3832 else if (Literal.isFloat16) 3833 Ty = Context.Float16Ty; 3834 else if (Literal.isFloat128) 3835 Ty = Context.Float128Ty; 3836 else 3837 Ty = Context.DoubleTy; 3838 3839 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3840 3841 if (Ty == Context.DoubleTy) { 3842 if (getLangOpts().SinglePrecisionConstants) { 3843 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3844 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3845 } 3846 } else if (getLangOpts().OpenCL && 3847 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3848 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3849 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3850 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3851 } 3852 } 3853 } else if (!Literal.isIntegerLiteral()) { 3854 return ExprError(); 3855 } else { 3856 QualType Ty; 3857 3858 // 'long long' is a C99 or C++11 feature. 3859 if (!getLangOpts().C99 && Literal.isLongLong) { 3860 if (getLangOpts().CPlusPlus) 3861 Diag(Tok.getLocation(), 3862 getLangOpts().CPlusPlus11 ? 3863 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3864 else 3865 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3866 } 3867 3868 // Get the value in the widest-possible width. 3869 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3870 llvm::APInt ResultVal(MaxWidth, 0); 3871 3872 if (Literal.GetIntegerValue(ResultVal)) { 3873 // If this value didn't fit into uintmax_t, error and force to ull. 3874 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3875 << /* Unsigned */ 1; 3876 Ty = Context.UnsignedLongLongTy; 3877 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3878 "long long is not intmax_t?"); 3879 } else { 3880 // If this value fits into a ULL, try to figure out what else it fits into 3881 // according to the rules of C99 6.4.4.1p5. 3882 3883 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3884 // be an unsigned int. 3885 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3886 3887 // Check from smallest to largest, picking the smallest type we can. 3888 unsigned Width = 0; 3889 3890 // Microsoft specific integer suffixes are explicitly sized. 3891 if (Literal.MicrosoftInteger) { 3892 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3893 Width = 8; 3894 Ty = Context.CharTy; 3895 } else { 3896 Width = Literal.MicrosoftInteger; 3897 Ty = Context.getIntTypeForBitwidth(Width, 3898 /*Signed=*/!Literal.isUnsigned); 3899 } 3900 } 3901 3902 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3903 // Are int/unsigned possibilities? 3904 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3905 3906 // Does it fit in a unsigned int? 3907 if (ResultVal.isIntN(IntSize)) { 3908 // Does it fit in a signed int? 3909 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3910 Ty = Context.IntTy; 3911 else if (AllowUnsigned) 3912 Ty = Context.UnsignedIntTy; 3913 Width = IntSize; 3914 } 3915 } 3916 3917 // Are long/unsigned long possibilities? 3918 if (Ty.isNull() && !Literal.isLongLong) { 3919 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3920 3921 // Does it fit in a unsigned long? 3922 if (ResultVal.isIntN(LongSize)) { 3923 // Does it fit in a signed long? 3924 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3925 Ty = Context.LongTy; 3926 else if (AllowUnsigned) 3927 Ty = Context.UnsignedLongTy; 3928 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3929 // is compatible. 3930 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3931 const unsigned LongLongSize = 3932 Context.getTargetInfo().getLongLongWidth(); 3933 Diag(Tok.getLocation(), 3934 getLangOpts().CPlusPlus 3935 ? Literal.isLong 3936 ? diag::warn_old_implicitly_unsigned_long_cxx 3937 : /*C++98 UB*/ diag:: 3938 ext_old_implicitly_unsigned_long_cxx 3939 : diag::warn_old_implicitly_unsigned_long) 3940 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3941 : /*will be ill-formed*/ 1); 3942 Ty = Context.UnsignedLongTy; 3943 } 3944 Width = LongSize; 3945 } 3946 } 3947 3948 // Check long long if needed. 3949 if (Ty.isNull()) { 3950 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3951 3952 // Does it fit in a unsigned long long? 3953 if (ResultVal.isIntN(LongLongSize)) { 3954 // Does it fit in a signed long long? 3955 // To be compatible with MSVC, hex integer literals ending with the 3956 // LL or i64 suffix are always signed in Microsoft mode. 3957 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3958 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3959 Ty = Context.LongLongTy; 3960 else if (AllowUnsigned) 3961 Ty = Context.UnsignedLongLongTy; 3962 Width = LongLongSize; 3963 } 3964 } 3965 3966 // If we still couldn't decide a type, we probably have something that 3967 // does not fit in a signed long long, but has no U suffix. 3968 if (Ty.isNull()) { 3969 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3970 Ty = Context.UnsignedLongLongTy; 3971 Width = Context.getTargetInfo().getLongLongWidth(); 3972 } 3973 3974 if (ResultVal.getBitWidth() != Width) 3975 ResultVal = ResultVal.trunc(Width); 3976 } 3977 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3978 } 3979 3980 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3981 if (Literal.isImaginary) { 3982 Res = new (Context) ImaginaryLiteral(Res, 3983 Context.getComplexType(Res->getType())); 3984 3985 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3986 } 3987 return Res; 3988 } 3989 3990 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3991 assert(E && "ActOnParenExpr() missing expr"); 3992 return new (Context) ParenExpr(L, R, E); 3993 } 3994 3995 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3996 SourceLocation Loc, 3997 SourceRange ArgRange) { 3998 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3999 // scalar or vector data type argument..." 4000 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4001 // type (C99 6.2.5p18) or void. 4002 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4003 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4004 << T << ArgRange; 4005 return true; 4006 } 4007 4008 assert((T->isVoidType() || !T->isIncompleteType()) && 4009 "Scalar types should always be complete"); 4010 return false; 4011 } 4012 4013 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4014 SourceLocation Loc, 4015 SourceRange ArgRange, 4016 UnaryExprOrTypeTrait TraitKind) { 4017 // Invalid types must be hard errors for SFINAE in C++. 4018 if (S.LangOpts.CPlusPlus) 4019 return true; 4020 4021 // C99 6.5.3.4p1: 4022 if (T->isFunctionType() && 4023 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4024 TraitKind == UETT_PreferredAlignOf)) { 4025 // sizeof(function)/alignof(function) is allowed as an extension. 4026 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4027 << getTraitSpelling(TraitKind) << ArgRange; 4028 return false; 4029 } 4030 4031 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4032 // this is an error (OpenCL v1.1 s6.3.k) 4033 if (T->isVoidType()) { 4034 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4035 : diag::ext_sizeof_alignof_void_type; 4036 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4037 return false; 4038 } 4039 4040 return true; 4041 } 4042 4043 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4044 SourceLocation Loc, 4045 SourceRange ArgRange, 4046 UnaryExprOrTypeTrait TraitKind) { 4047 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4048 // runtime doesn't allow it. 4049 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4050 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4051 << T << (TraitKind == UETT_SizeOf) 4052 << ArgRange; 4053 return true; 4054 } 4055 4056 return false; 4057 } 4058 4059 /// Check whether E is a pointer from a decayed array type (the decayed 4060 /// pointer type is equal to T) and emit a warning if it is. 4061 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4062 Expr *E) { 4063 // Don't warn if the operation changed the type. 4064 if (T != E->getType()) 4065 return; 4066 4067 // Now look for array decays. 4068 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4069 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4070 return; 4071 4072 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4073 << ICE->getType() 4074 << ICE->getSubExpr()->getType(); 4075 } 4076 4077 /// Check the constraints on expression operands to unary type expression 4078 /// and type traits. 4079 /// 4080 /// Completes any types necessary and validates the constraints on the operand 4081 /// expression. The logic mostly mirrors the type-based overload, but may modify 4082 /// the expression as it completes the type for that expression through template 4083 /// instantiation, etc. 4084 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4085 UnaryExprOrTypeTrait ExprKind) { 4086 QualType ExprTy = E->getType(); 4087 assert(!ExprTy->isReferenceType()); 4088 4089 bool IsUnevaluatedOperand = 4090 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4091 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4092 if (IsUnevaluatedOperand) { 4093 ExprResult Result = CheckUnevaluatedOperand(E); 4094 if (Result.isInvalid()) 4095 return true; 4096 E = Result.get(); 4097 } 4098 4099 // The operand for sizeof and alignof is in an unevaluated expression context, 4100 // so side effects could result in unintended consequences. 4101 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4102 // used to build SFINAE gadgets. 4103 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4104 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4105 !E->isInstantiationDependent() && 4106 E->HasSideEffects(Context, false)) 4107 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4108 4109 if (ExprKind == UETT_VecStep) 4110 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4111 E->getSourceRange()); 4112 4113 // Explicitly list some types as extensions. 4114 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4115 E->getSourceRange(), ExprKind)) 4116 return false; 4117 4118 // 'alignof' applied to an expression only requires the base element type of 4119 // the expression to be complete. 'sizeof' requires the expression's type to 4120 // be complete (and will attempt to complete it if it's an array of unknown 4121 // bound). 4122 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4123 if (RequireCompleteSizedType( 4124 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4125 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4126 getTraitSpelling(ExprKind), E->getSourceRange())) 4127 return true; 4128 } else { 4129 if (RequireCompleteSizedExprType( 4130 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4131 getTraitSpelling(ExprKind), E->getSourceRange())) 4132 return true; 4133 } 4134 4135 // Completing the expression's type may have changed it. 4136 ExprTy = E->getType(); 4137 assert(!ExprTy->isReferenceType()); 4138 4139 if (ExprTy->isFunctionType()) { 4140 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4141 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4142 return true; 4143 } 4144 4145 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4146 E->getSourceRange(), ExprKind)) 4147 return true; 4148 4149 if (ExprKind == UETT_SizeOf) { 4150 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4151 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4152 QualType OType = PVD->getOriginalType(); 4153 QualType Type = PVD->getType(); 4154 if (Type->isPointerType() && OType->isArrayType()) { 4155 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4156 << Type << OType; 4157 Diag(PVD->getLocation(), diag::note_declared_at); 4158 } 4159 } 4160 } 4161 4162 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4163 // decays into a pointer and returns an unintended result. This is most 4164 // likely a typo for "sizeof(array) op x". 4165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4166 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4167 BO->getLHS()); 4168 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4169 BO->getRHS()); 4170 } 4171 } 4172 4173 return false; 4174 } 4175 4176 /// Check the constraints on operands to unary expression and type 4177 /// traits. 4178 /// 4179 /// This will complete any types necessary, and validate the various constraints 4180 /// on those operands. 4181 /// 4182 /// The UsualUnaryConversions() function is *not* called by this routine. 4183 /// C99 6.3.2.1p[2-4] all state: 4184 /// Except when it is the operand of the sizeof operator ... 4185 /// 4186 /// C++ [expr.sizeof]p4 4187 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4188 /// standard conversions are not applied to the operand of sizeof. 4189 /// 4190 /// This policy is followed for all of the unary trait expressions. 4191 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4192 SourceLocation OpLoc, 4193 SourceRange ExprRange, 4194 UnaryExprOrTypeTrait ExprKind) { 4195 if (ExprType->isDependentType()) 4196 return false; 4197 4198 // C++ [expr.sizeof]p2: 4199 // When applied to a reference or a reference type, the result 4200 // is the size of the referenced type. 4201 // C++11 [expr.alignof]p3: 4202 // When alignof is applied to a reference type, the result 4203 // shall be the alignment of the referenced type. 4204 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4205 ExprType = Ref->getPointeeType(); 4206 4207 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4208 // When alignof or _Alignof is applied to an array type, the result 4209 // is the alignment of the element type. 4210 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4211 ExprKind == UETT_OpenMPRequiredSimdAlign) 4212 ExprType = Context.getBaseElementType(ExprType); 4213 4214 if (ExprKind == UETT_VecStep) 4215 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4216 4217 // Explicitly list some types as extensions. 4218 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4219 ExprKind)) 4220 return false; 4221 4222 if (RequireCompleteSizedType( 4223 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4224 getTraitSpelling(ExprKind), ExprRange)) 4225 return true; 4226 4227 if (ExprType->isFunctionType()) { 4228 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4229 << getTraitSpelling(ExprKind) << ExprRange; 4230 return true; 4231 } 4232 4233 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4234 ExprKind)) 4235 return true; 4236 4237 return false; 4238 } 4239 4240 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4241 // Cannot know anything else if the expression is dependent. 4242 if (E->isTypeDependent()) 4243 return false; 4244 4245 if (E->getObjectKind() == OK_BitField) { 4246 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4247 << 1 << E->getSourceRange(); 4248 return true; 4249 } 4250 4251 ValueDecl *D = nullptr; 4252 Expr *Inner = E->IgnoreParens(); 4253 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4254 D = DRE->getDecl(); 4255 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4256 D = ME->getMemberDecl(); 4257 } 4258 4259 // If it's a field, require the containing struct to have a 4260 // complete definition so that we can compute the layout. 4261 // 4262 // This can happen in C++11 onwards, either by naming the member 4263 // in a way that is not transformed into a member access expression 4264 // (in an unevaluated operand, for instance), or by naming the member 4265 // in a trailing-return-type. 4266 // 4267 // For the record, since __alignof__ on expressions is a GCC 4268 // extension, GCC seems to permit this but always gives the 4269 // nonsensical answer 0. 4270 // 4271 // We don't really need the layout here --- we could instead just 4272 // directly check for all the appropriate alignment-lowing 4273 // attributes --- but that would require duplicating a lot of 4274 // logic that just isn't worth duplicating for such a marginal 4275 // use-case. 4276 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4277 // Fast path this check, since we at least know the record has a 4278 // definition if we can find a member of it. 4279 if (!FD->getParent()->isCompleteDefinition()) { 4280 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4281 << E->getSourceRange(); 4282 return true; 4283 } 4284 4285 // Otherwise, if it's a field, and the field doesn't have 4286 // reference type, then it must have a complete type (or be a 4287 // flexible array member, which we explicitly want to 4288 // white-list anyway), which makes the following checks trivial. 4289 if (!FD->getType()->isReferenceType()) 4290 return false; 4291 } 4292 4293 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4294 } 4295 4296 bool Sema::CheckVecStepExpr(Expr *E) { 4297 E = E->IgnoreParens(); 4298 4299 // Cannot know anything else if the expression is dependent. 4300 if (E->isTypeDependent()) 4301 return false; 4302 4303 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4304 } 4305 4306 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4307 CapturingScopeInfo *CSI) { 4308 assert(T->isVariablyModifiedType()); 4309 assert(CSI != nullptr); 4310 4311 // We're going to walk down into the type and look for VLA expressions. 4312 do { 4313 const Type *Ty = T.getTypePtr(); 4314 switch (Ty->getTypeClass()) { 4315 #define TYPE(Class, Base) 4316 #define ABSTRACT_TYPE(Class, Base) 4317 #define NON_CANONICAL_TYPE(Class, Base) 4318 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4319 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4320 #include "clang/AST/TypeNodes.inc" 4321 T = QualType(); 4322 break; 4323 // These types are never variably-modified. 4324 case Type::Builtin: 4325 case Type::Complex: 4326 case Type::Vector: 4327 case Type::ExtVector: 4328 case Type::ConstantMatrix: 4329 case Type::Record: 4330 case Type::Enum: 4331 case Type::Elaborated: 4332 case Type::TemplateSpecialization: 4333 case Type::ObjCObject: 4334 case Type::ObjCInterface: 4335 case Type::ObjCObjectPointer: 4336 case Type::ObjCTypeParam: 4337 case Type::Pipe: 4338 case Type::ExtInt: 4339 llvm_unreachable("type class is never variably-modified!"); 4340 case Type::Adjusted: 4341 T = cast<AdjustedType>(Ty)->getOriginalType(); 4342 break; 4343 case Type::Decayed: 4344 T = cast<DecayedType>(Ty)->getPointeeType(); 4345 break; 4346 case Type::Pointer: 4347 T = cast<PointerType>(Ty)->getPointeeType(); 4348 break; 4349 case Type::BlockPointer: 4350 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4351 break; 4352 case Type::LValueReference: 4353 case Type::RValueReference: 4354 T = cast<ReferenceType>(Ty)->getPointeeType(); 4355 break; 4356 case Type::MemberPointer: 4357 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4358 break; 4359 case Type::ConstantArray: 4360 case Type::IncompleteArray: 4361 // Losing element qualification here is fine. 4362 T = cast<ArrayType>(Ty)->getElementType(); 4363 break; 4364 case Type::VariableArray: { 4365 // Losing element qualification here is fine. 4366 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4367 4368 // Unknown size indication requires no size computation. 4369 // Otherwise, evaluate and record it. 4370 auto Size = VAT->getSizeExpr(); 4371 if (Size && !CSI->isVLATypeCaptured(VAT) && 4372 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4373 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4374 4375 T = VAT->getElementType(); 4376 break; 4377 } 4378 case Type::FunctionProto: 4379 case Type::FunctionNoProto: 4380 T = cast<FunctionType>(Ty)->getReturnType(); 4381 break; 4382 case Type::Paren: 4383 case Type::TypeOf: 4384 case Type::UnaryTransform: 4385 case Type::Attributed: 4386 case Type::SubstTemplateTypeParm: 4387 case Type::MacroQualified: 4388 // Keep walking after single level desugaring. 4389 T = T.getSingleStepDesugaredType(Context); 4390 break; 4391 case Type::Typedef: 4392 T = cast<TypedefType>(Ty)->desugar(); 4393 break; 4394 case Type::Decltype: 4395 T = cast<DecltypeType>(Ty)->desugar(); 4396 break; 4397 case Type::Auto: 4398 case Type::DeducedTemplateSpecialization: 4399 T = cast<DeducedType>(Ty)->getDeducedType(); 4400 break; 4401 case Type::TypeOfExpr: 4402 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4403 break; 4404 case Type::Atomic: 4405 T = cast<AtomicType>(Ty)->getValueType(); 4406 break; 4407 } 4408 } while (!T.isNull() && T->isVariablyModifiedType()); 4409 } 4410 4411 /// Build a sizeof or alignof expression given a type operand. 4412 ExprResult 4413 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4414 SourceLocation OpLoc, 4415 UnaryExprOrTypeTrait ExprKind, 4416 SourceRange R) { 4417 if (!TInfo) 4418 return ExprError(); 4419 4420 QualType T = TInfo->getType(); 4421 4422 if (!T->isDependentType() && 4423 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4424 return ExprError(); 4425 4426 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4427 if (auto *TT = T->getAs<TypedefType>()) { 4428 for (auto I = FunctionScopes.rbegin(), 4429 E = std::prev(FunctionScopes.rend()); 4430 I != E; ++I) { 4431 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4432 if (CSI == nullptr) 4433 break; 4434 DeclContext *DC = nullptr; 4435 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4436 DC = LSI->CallOperator; 4437 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4438 DC = CRSI->TheCapturedDecl; 4439 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4440 DC = BSI->TheDecl; 4441 if (DC) { 4442 if (DC->containsDecl(TT->getDecl())) 4443 break; 4444 captureVariablyModifiedType(Context, T, CSI); 4445 } 4446 } 4447 } 4448 } 4449 4450 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4451 return new (Context) UnaryExprOrTypeTraitExpr( 4452 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4453 } 4454 4455 /// Build a sizeof or alignof expression given an expression 4456 /// operand. 4457 ExprResult 4458 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4459 UnaryExprOrTypeTrait ExprKind) { 4460 ExprResult PE = CheckPlaceholderExpr(E); 4461 if (PE.isInvalid()) 4462 return ExprError(); 4463 4464 E = PE.get(); 4465 4466 // Verify that the operand is valid. 4467 bool isInvalid = false; 4468 if (E->isTypeDependent()) { 4469 // Delay type-checking for type-dependent expressions. 4470 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4471 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4472 } else if (ExprKind == UETT_VecStep) { 4473 isInvalid = CheckVecStepExpr(E); 4474 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4475 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4476 isInvalid = true; 4477 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4478 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4479 isInvalid = true; 4480 } else { 4481 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4482 } 4483 4484 if (isInvalid) 4485 return ExprError(); 4486 4487 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4488 PE = TransformToPotentiallyEvaluated(E); 4489 if (PE.isInvalid()) return ExprError(); 4490 E = PE.get(); 4491 } 4492 4493 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4494 return new (Context) UnaryExprOrTypeTraitExpr( 4495 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4496 } 4497 4498 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4499 /// expr and the same for @c alignof and @c __alignof 4500 /// Note that the ArgRange is invalid if isType is false. 4501 ExprResult 4502 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4503 UnaryExprOrTypeTrait ExprKind, bool IsType, 4504 void *TyOrEx, SourceRange ArgRange) { 4505 // If error parsing type, ignore. 4506 if (!TyOrEx) return ExprError(); 4507 4508 if (IsType) { 4509 TypeSourceInfo *TInfo; 4510 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4511 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4512 } 4513 4514 Expr *ArgEx = (Expr *)TyOrEx; 4515 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4516 return Result; 4517 } 4518 4519 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4520 bool IsReal) { 4521 if (V.get()->isTypeDependent()) 4522 return S.Context.DependentTy; 4523 4524 // _Real and _Imag are only l-values for normal l-values. 4525 if (V.get()->getObjectKind() != OK_Ordinary) { 4526 V = S.DefaultLvalueConversion(V.get()); 4527 if (V.isInvalid()) 4528 return QualType(); 4529 } 4530 4531 // These operators return the element type of a complex type. 4532 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4533 return CT->getElementType(); 4534 4535 // Otherwise they pass through real integer and floating point types here. 4536 if (V.get()->getType()->isArithmeticType()) 4537 return V.get()->getType(); 4538 4539 // Test for placeholders. 4540 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4541 if (PR.isInvalid()) return QualType(); 4542 if (PR.get() != V.get()) { 4543 V = PR; 4544 return CheckRealImagOperand(S, V, Loc, IsReal); 4545 } 4546 4547 // Reject anything else. 4548 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4549 << (IsReal ? "__real" : "__imag"); 4550 return QualType(); 4551 } 4552 4553 4554 4555 ExprResult 4556 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4557 tok::TokenKind Kind, Expr *Input) { 4558 UnaryOperatorKind Opc; 4559 switch (Kind) { 4560 default: llvm_unreachable("Unknown unary op!"); 4561 case tok::plusplus: Opc = UO_PostInc; break; 4562 case tok::minusminus: Opc = UO_PostDec; break; 4563 } 4564 4565 // Since this might is a postfix expression, get rid of ParenListExprs. 4566 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4567 if (Result.isInvalid()) return ExprError(); 4568 Input = Result.get(); 4569 4570 return BuildUnaryOp(S, OpLoc, Opc, Input); 4571 } 4572 4573 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4574 /// 4575 /// \return true on error 4576 static bool checkArithmeticOnObjCPointer(Sema &S, 4577 SourceLocation opLoc, 4578 Expr *op) { 4579 assert(op->getType()->isObjCObjectPointerType()); 4580 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4581 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4582 return false; 4583 4584 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4585 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4586 << op->getSourceRange(); 4587 return true; 4588 } 4589 4590 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4591 auto *BaseNoParens = Base->IgnoreParens(); 4592 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4593 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4594 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4595 } 4596 4597 ExprResult 4598 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4599 Expr *idx, SourceLocation rbLoc) { 4600 if (base && !base->getType().isNull() && 4601 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4602 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4603 SourceLocation(), /*Length*/ nullptr, 4604 /*Stride=*/nullptr, rbLoc); 4605 4606 // Since this might be a postfix expression, get rid of ParenListExprs. 4607 if (isa<ParenListExpr>(base)) { 4608 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4609 if (result.isInvalid()) return ExprError(); 4610 base = result.get(); 4611 } 4612 4613 // Check if base and idx form a MatrixSubscriptExpr. 4614 // 4615 // Helper to check for comma expressions, which are not allowed as indices for 4616 // matrix subscript expressions. 4617 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4618 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4619 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4620 << SourceRange(base->getBeginLoc(), rbLoc); 4621 return true; 4622 } 4623 return false; 4624 }; 4625 // The matrix subscript operator ([][])is considered a single operator. 4626 // Separating the index expressions by parenthesis is not allowed. 4627 if (base->getType()->isSpecificPlaceholderType( 4628 BuiltinType::IncompleteMatrixIdx) && 4629 !isa<MatrixSubscriptExpr>(base)) { 4630 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4631 << SourceRange(base->getBeginLoc(), rbLoc); 4632 return ExprError(); 4633 } 4634 // If the base is a MatrixSubscriptExpr, try to create a new 4635 // MatrixSubscriptExpr. 4636 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4637 if (matSubscriptE) { 4638 if (CheckAndReportCommaError(idx)) 4639 return ExprError(); 4640 4641 assert(matSubscriptE->isIncomplete() && 4642 "base has to be an incomplete matrix subscript"); 4643 return CreateBuiltinMatrixSubscriptExpr( 4644 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4645 } 4646 4647 // Handle any non-overload placeholder types in the base and index 4648 // expressions. We can't handle overloads here because the other 4649 // operand might be an overloadable type, in which case the overload 4650 // resolution for the operator overload should get the first crack 4651 // at the overload. 4652 bool IsMSPropertySubscript = false; 4653 if (base->getType()->isNonOverloadPlaceholderType()) { 4654 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4655 if (!IsMSPropertySubscript) { 4656 ExprResult result = CheckPlaceholderExpr(base); 4657 if (result.isInvalid()) 4658 return ExprError(); 4659 base = result.get(); 4660 } 4661 } 4662 4663 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4664 if (base->getType()->isMatrixType()) { 4665 if (CheckAndReportCommaError(idx)) 4666 return ExprError(); 4667 4668 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4669 } 4670 4671 // A comma-expression as the index is deprecated in C++2a onwards. 4672 if (getLangOpts().CPlusPlus20 && 4673 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4674 (isa<CXXOperatorCallExpr>(idx) && 4675 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4676 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4677 << SourceRange(base->getBeginLoc(), rbLoc); 4678 } 4679 4680 if (idx->getType()->isNonOverloadPlaceholderType()) { 4681 ExprResult result = CheckPlaceholderExpr(idx); 4682 if (result.isInvalid()) return ExprError(); 4683 idx = result.get(); 4684 } 4685 4686 // Build an unanalyzed expression if either operand is type-dependent. 4687 if (getLangOpts().CPlusPlus && 4688 (base->isTypeDependent() || idx->isTypeDependent())) { 4689 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4690 VK_LValue, OK_Ordinary, rbLoc); 4691 } 4692 4693 // MSDN, property (C++) 4694 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4695 // This attribute can also be used in the declaration of an empty array in a 4696 // class or structure definition. For example: 4697 // __declspec(property(get=GetX, put=PutX)) int x[]; 4698 // The above statement indicates that x[] can be used with one or more array 4699 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4700 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4701 if (IsMSPropertySubscript) { 4702 // Build MS property subscript expression if base is MS property reference 4703 // or MS property subscript. 4704 return new (Context) MSPropertySubscriptExpr( 4705 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4706 } 4707 4708 // Use C++ overloaded-operator rules if either operand has record 4709 // type. The spec says to do this if either type is *overloadable*, 4710 // but enum types can't declare subscript operators or conversion 4711 // operators, so there's nothing interesting for overload resolution 4712 // to do if there aren't any record types involved. 4713 // 4714 // ObjC pointers have their own subscripting logic that is not tied 4715 // to overload resolution and so should not take this path. 4716 if (getLangOpts().CPlusPlus && 4717 (base->getType()->isRecordType() || 4718 (!base->getType()->isObjCObjectPointerType() && 4719 idx->getType()->isRecordType()))) { 4720 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4721 } 4722 4723 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4724 4725 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4726 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4727 4728 return Res; 4729 } 4730 4731 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4732 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4733 InitializationKind Kind = 4734 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4735 InitializationSequence InitSeq(*this, Entity, Kind, E); 4736 return InitSeq.Perform(*this, Entity, Kind, E); 4737 } 4738 4739 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4740 Expr *ColumnIdx, 4741 SourceLocation RBLoc) { 4742 ExprResult BaseR = CheckPlaceholderExpr(Base); 4743 if (BaseR.isInvalid()) 4744 return BaseR; 4745 Base = BaseR.get(); 4746 4747 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4748 if (RowR.isInvalid()) 4749 return RowR; 4750 RowIdx = RowR.get(); 4751 4752 if (!ColumnIdx) 4753 return new (Context) MatrixSubscriptExpr( 4754 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4755 4756 // Build an unanalyzed expression if any of the operands is type-dependent. 4757 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4758 ColumnIdx->isTypeDependent()) 4759 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4760 Context.DependentTy, RBLoc); 4761 4762 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4763 if (ColumnR.isInvalid()) 4764 return ColumnR; 4765 ColumnIdx = ColumnR.get(); 4766 4767 // Check that IndexExpr is an integer expression. If it is a constant 4768 // expression, check that it is less than Dim (= the number of elements in the 4769 // corresponding dimension). 4770 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4771 bool IsColumnIdx) -> Expr * { 4772 if (!IndexExpr->getType()->isIntegerType() && 4773 !IndexExpr->isTypeDependent()) { 4774 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4775 << IsColumnIdx; 4776 return nullptr; 4777 } 4778 4779 if (Optional<llvm::APSInt> Idx = 4780 IndexExpr->getIntegerConstantExpr(Context)) { 4781 if ((*Idx < 0 || *Idx >= Dim)) { 4782 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4783 << IsColumnIdx << Dim; 4784 return nullptr; 4785 } 4786 } 4787 4788 ExprResult ConvExpr = 4789 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4790 assert(!ConvExpr.isInvalid() && 4791 "should be able to convert any integer type to size type"); 4792 return ConvExpr.get(); 4793 }; 4794 4795 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4796 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4797 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4798 if (!RowIdx || !ColumnIdx) 4799 return ExprError(); 4800 4801 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4802 MTy->getElementType(), RBLoc); 4803 } 4804 4805 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4806 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4807 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4808 4809 // For expressions like `&(*s).b`, the base is recorded and what should be 4810 // checked. 4811 const MemberExpr *Member = nullptr; 4812 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4813 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4814 4815 LastRecord.PossibleDerefs.erase(StrippedExpr); 4816 } 4817 4818 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4819 if (isUnevaluatedContext()) 4820 return; 4821 4822 QualType ResultTy = E->getType(); 4823 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4824 4825 // Bail if the element is an array since it is not memory access. 4826 if (isa<ArrayType>(ResultTy)) 4827 return; 4828 4829 if (ResultTy->hasAttr(attr::NoDeref)) { 4830 LastRecord.PossibleDerefs.insert(E); 4831 return; 4832 } 4833 4834 // Check if the base type is a pointer to a member access of a struct 4835 // marked with noderef. 4836 const Expr *Base = E->getBase(); 4837 QualType BaseTy = Base->getType(); 4838 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4839 // Not a pointer access 4840 return; 4841 4842 const MemberExpr *Member = nullptr; 4843 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4844 Member->isArrow()) 4845 Base = Member->getBase(); 4846 4847 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4848 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4849 LastRecord.PossibleDerefs.insert(E); 4850 } 4851 } 4852 4853 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4854 Expr *LowerBound, 4855 SourceLocation ColonLocFirst, 4856 SourceLocation ColonLocSecond, 4857 Expr *Length, Expr *Stride, 4858 SourceLocation RBLoc) { 4859 if (Base->getType()->isPlaceholderType() && 4860 !Base->getType()->isSpecificPlaceholderType( 4861 BuiltinType::OMPArraySection)) { 4862 ExprResult Result = CheckPlaceholderExpr(Base); 4863 if (Result.isInvalid()) 4864 return ExprError(); 4865 Base = Result.get(); 4866 } 4867 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4868 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4869 if (Result.isInvalid()) 4870 return ExprError(); 4871 Result = DefaultLvalueConversion(Result.get()); 4872 if (Result.isInvalid()) 4873 return ExprError(); 4874 LowerBound = Result.get(); 4875 } 4876 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4877 ExprResult Result = CheckPlaceholderExpr(Length); 4878 if (Result.isInvalid()) 4879 return ExprError(); 4880 Result = DefaultLvalueConversion(Result.get()); 4881 if (Result.isInvalid()) 4882 return ExprError(); 4883 Length = Result.get(); 4884 } 4885 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4886 ExprResult Result = CheckPlaceholderExpr(Stride); 4887 if (Result.isInvalid()) 4888 return ExprError(); 4889 Result = DefaultLvalueConversion(Result.get()); 4890 if (Result.isInvalid()) 4891 return ExprError(); 4892 Stride = Result.get(); 4893 } 4894 4895 // Build an unanalyzed expression if either operand is type-dependent. 4896 if (Base->isTypeDependent() || 4897 (LowerBound && 4898 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4899 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4900 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4901 return new (Context) OMPArraySectionExpr( 4902 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4903 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4904 } 4905 4906 // Perform default conversions. 4907 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4908 QualType ResultTy; 4909 if (OriginalTy->isAnyPointerType()) { 4910 ResultTy = OriginalTy->getPointeeType(); 4911 } else if (OriginalTy->isArrayType()) { 4912 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4913 } else { 4914 return ExprError( 4915 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4916 << Base->getSourceRange()); 4917 } 4918 // C99 6.5.2.1p1 4919 if (LowerBound) { 4920 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4921 LowerBound); 4922 if (Res.isInvalid()) 4923 return ExprError(Diag(LowerBound->getExprLoc(), 4924 diag::err_omp_typecheck_section_not_integer) 4925 << 0 << LowerBound->getSourceRange()); 4926 LowerBound = Res.get(); 4927 4928 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4929 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4930 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4931 << 0 << LowerBound->getSourceRange(); 4932 } 4933 if (Length) { 4934 auto Res = 4935 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4936 if (Res.isInvalid()) 4937 return ExprError(Diag(Length->getExprLoc(), 4938 diag::err_omp_typecheck_section_not_integer) 4939 << 1 << Length->getSourceRange()); 4940 Length = Res.get(); 4941 4942 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4943 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4944 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4945 << 1 << Length->getSourceRange(); 4946 } 4947 if (Stride) { 4948 ExprResult Res = 4949 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4950 if (Res.isInvalid()) 4951 return ExprError(Diag(Stride->getExprLoc(), 4952 diag::err_omp_typecheck_section_not_integer) 4953 << 1 << Stride->getSourceRange()); 4954 Stride = Res.get(); 4955 4956 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4957 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4958 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4959 << 1 << Stride->getSourceRange(); 4960 } 4961 4962 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4963 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4964 // type. Note that functions are not objects, and that (in C99 parlance) 4965 // incomplete types are not object types. 4966 if (ResultTy->isFunctionType()) { 4967 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4968 << ResultTy << Base->getSourceRange(); 4969 return ExprError(); 4970 } 4971 4972 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4973 diag::err_omp_section_incomplete_type, Base)) 4974 return ExprError(); 4975 4976 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4977 Expr::EvalResult Result; 4978 if (LowerBound->EvaluateAsInt(Result, Context)) { 4979 // OpenMP 5.0, [2.1.5 Array Sections] 4980 // The array section must be a subset of the original array. 4981 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4982 if (LowerBoundValue.isNegative()) { 4983 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4984 << LowerBound->getSourceRange(); 4985 return ExprError(); 4986 } 4987 } 4988 } 4989 4990 if (Length) { 4991 Expr::EvalResult Result; 4992 if (Length->EvaluateAsInt(Result, Context)) { 4993 // OpenMP 5.0, [2.1.5 Array Sections] 4994 // The length must evaluate to non-negative integers. 4995 llvm::APSInt LengthValue = Result.Val.getInt(); 4996 if (LengthValue.isNegative()) { 4997 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4998 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4999 << Length->getSourceRange(); 5000 return ExprError(); 5001 } 5002 } 5003 } else if (ColonLocFirst.isValid() && 5004 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5005 !OriginalTy->isVariableArrayType()))) { 5006 // OpenMP 5.0, [2.1.5 Array Sections] 5007 // When the size of the array dimension is not known, the length must be 5008 // specified explicitly. 5009 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5010 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5011 return ExprError(); 5012 } 5013 5014 if (Stride) { 5015 Expr::EvalResult Result; 5016 if (Stride->EvaluateAsInt(Result, Context)) { 5017 // OpenMP 5.0, [2.1.5 Array Sections] 5018 // The stride must evaluate to a positive integer. 5019 llvm::APSInt StrideValue = Result.Val.getInt(); 5020 if (!StrideValue.isStrictlyPositive()) { 5021 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5022 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5023 << Stride->getSourceRange(); 5024 return ExprError(); 5025 } 5026 } 5027 } 5028 5029 if (!Base->getType()->isSpecificPlaceholderType( 5030 BuiltinType::OMPArraySection)) { 5031 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5032 if (Result.isInvalid()) 5033 return ExprError(); 5034 Base = Result.get(); 5035 } 5036 return new (Context) OMPArraySectionExpr( 5037 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5038 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5039 } 5040 5041 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5042 SourceLocation RParenLoc, 5043 ArrayRef<Expr *> Dims, 5044 ArrayRef<SourceRange> Brackets) { 5045 if (Base->getType()->isPlaceholderType()) { 5046 ExprResult Result = CheckPlaceholderExpr(Base); 5047 if (Result.isInvalid()) 5048 return ExprError(); 5049 Result = DefaultLvalueConversion(Result.get()); 5050 if (Result.isInvalid()) 5051 return ExprError(); 5052 Base = Result.get(); 5053 } 5054 QualType BaseTy = Base->getType(); 5055 // Delay analysis of the types/expressions if instantiation/specialization is 5056 // required. 5057 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5058 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5059 LParenLoc, RParenLoc, Dims, Brackets); 5060 if (!BaseTy->isPointerType() || 5061 (!Base->isTypeDependent() && 5062 BaseTy->getPointeeType()->isIncompleteType())) 5063 return ExprError(Diag(Base->getExprLoc(), 5064 diag::err_omp_non_pointer_type_array_shaping_base) 5065 << Base->getSourceRange()); 5066 5067 SmallVector<Expr *, 4> NewDims; 5068 bool ErrorFound = false; 5069 for (Expr *Dim : Dims) { 5070 if (Dim->getType()->isPlaceholderType()) { 5071 ExprResult Result = CheckPlaceholderExpr(Dim); 5072 if (Result.isInvalid()) { 5073 ErrorFound = true; 5074 continue; 5075 } 5076 Result = DefaultLvalueConversion(Result.get()); 5077 if (Result.isInvalid()) { 5078 ErrorFound = true; 5079 continue; 5080 } 5081 Dim = Result.get(); 5082 } 5083 if (!Dim->isTypeDependent()) { 5084 ExprResult Result = 5085 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5086 if (Result.isInvalid()) { 5087 ErrorFound = true; 5088 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5089 << Dim->getSourceRange(); 5090 continue; 5091 } 5092 Dim = Result.get(); 5093 Expr::EvalResult EvResult; 5094 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5095 // OpenMP 5.0, [2.1.4 Array Shaping] 5096 // Each si is an integral type expression that must evaluate to a 5097 // positive integer. 5098 llvm::APSInt Value = EvResult.Val.getInt(); 5099 if (!Value.isStrictlyPositive()) { 5100 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5101 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5102 << Dim->getSourceRange(); 5103 ErrorFound = true; 5104 continue; 5105 } 5106 } 5107 } 5108 NewDims.push_back(Dim); 5109 } 5110 if (ErrorFound) 5111 return ExprError(); 5112 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5113 LParenLoc, RParenLoc, NewDims, Brackets); 5114 } 5115 5116 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5117 SourceLocation LLoc, SourceLocation RLoc, 5118 ArrayRef<OMPIteratorData> Data) { 5119 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5120 bool IsCorrect = true; 5121 for (const OMPIteratorData &D : Data) { 5122 TypeSourceInfo *TInfo = nullptr; 5123 SourceLocation StartLoc; 5124 QualType DeclTy; 5125 if (!D.Type.getAsOpaquePtr()) { 5126 // OpenMP 5.0, 2.1.6 Iterators 5127 // In an iterator-specifier, if the iterator-type is not specified then 5128 // the type of that iterator is of int type. 5129 DeclTy = Context.IntTy; 5130 StartLoc = D.DeclIdentLoc; 5131 } else { 5132 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5133 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5134 } 5135 5136 bool IsDeclTyDependent = DeclTy->isDependentType() || 5137 DeclTy->containsUnexpandedParameterPack() || 5138 DeclTy->isInstantiationDependentType(); 5139 if (!IsDeclTyDependent) { 5140 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5141 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5142 // The iterator-type must be an integral or pointer type. 5143 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5144 << DeclTy; 5145 IsCorrect = false; 5146 continue; 5147 } 5148 if (DeclTy.isConstant(Context)) { 5149 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5150 // The iterator-type must not be const qualified. 5151 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5152 << DeclTy; 5153 IsCorrect = false; 5154 continue; 5155 } 5156 } 5157 5158 // Iterator declaration. 5159 assert(D.DeclIdent && "Identifier expected."); 5160 // Always try to create iterator declarator to avoid extra error messages 5161 // about unknown declarations use. 5162 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5163 D.DeclIdent, DeclTy, TInfo, SC_None); 5164 VD->setImplicit(); 5165 if (S) { 5166 // Check for conflicting previous declaration. 5167 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5168 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5169 ForVisibleRedeclaration); 5170 Previous.suppressDiagnostics(); 5171 LookupName(Previous, S); 5172 5173 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5174 /*AllowInlineNamespace=*/false); 5175 if (!Previous.empty()) { 5176 NamedDecl *Old = Previous.getRepresentativeDecl(); 5177 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5178 Diag(Old->getLocation(), diag::note_previous_definition); 5179 } else { 5180 PushOnScopeChains(VD, S); 5181 } 5182 } else { 5183 CurContext->addDecl(VD); 5184 } 5185 Expr *Begin = D.Range.Begin; 5186 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5187 ExprResult BeginRes = 5188 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5189 Begin = BeginRes.get(); 5190 } 5191 Expr *End = D.Range.End; 5192 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5193 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5194 End = EndRes.get(); 5195 } 5196 Expr *Step = D.Range.Step; 5197 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5198 if (!Step->getType()->isIntegralType(Context)) { 5199 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5200 << Step << Step->getSourceRange(); 5201 IsCorrect = false; 5202 continue; 5203 } 5204 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5205 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5206 // If the step expression of a range-specification equals zero, the 5207 // behavior is unspecified. 5208 if (Result && Result->isNullValue()) { 5209 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5210 << Step << Step->getSourceRange(); 5211 IsCorrect = false; 5212 continue; 5213 } 5214 } 5215 if (!Begin || !End || !IsCorrect) { 5216 IsCorrect = false; 5217 continue; 5218 } 5219 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5220 IDElem.IteratorDecl = VD; 5221 IDElem.AssignmentLoc = D.AssignLoc; 5222 IDElem.Range.Begin = Begin; 5223 IDElem.Range.End = End; 5224 IDElem.Range.Step = Step; 5225 IDElem.ColonLoc = D.ColonLoc; 5226 IDElem.SecondColonLoc = D.SecColonLoc; 5227 } 5228 if (!IsCorrect) { 5229 // Invalidate all created iterator declarations if error is found. 5230 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5231 if (Decl *ID = D.IteratorDecl) 5232 ID->setInvalidDecl(); 5233 } 5234 return ExprError(); 5235 } 5236 SmallVector<OMPIteratorHelperData, 4> Helpers; 5237 if (!CurContext->isDependentContext()) { 5238 // Build number of ityeration for each iteration range. 5239 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5240 // ((Begini-Stepi-1-Endi) / -Stepi); 5241 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5242 // (Endi - Begini) 5243 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5244 D.Range.Begin); 5245 if(!Res.isUsable()) { 5246 IsCorrect = false; 5247 continue; 5248 } 5249 ExprResult St, St1; 5250 if (D.Range.Step) { 5251 St = D.Range.Step; 5252 // (Endi - Begini) + Stepi 5253 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5254 if (!Res.isUsable()) { 5255 IsCorrect = false; 5256 continue; 5257 } 5258 // (Endi - Begini) + Stepi - 1 5259 Res = 5260 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5261 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5262 if (!Res.isUsable()) { 5263 IsCorrect = false; 5264 continue; 5265 } 5266 // ((Endi - Begini) + Stepi - 1) / Stepi 5267 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5268 if (!Res.isUsable()) { 5269 IsCorrect = false; 5270 continue; 5271 } 5272 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5273 // (Begini - Endi) 5274 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5275 D.Range.Begin, D.Range.End); 5276 if (!Res1.isUsable()) { 5277 IsCorrect = false; 5278 continue; 5279 } 5280 // (Begini - Endi) - Stepi 5281 Res1 = 5282 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5283 if (!Res1.isUsable()) { 5284 IsCorrect = false; 5285 continue; 5286 } 5287 // (Begini - Endi) - Stepi - 1 5288 Res1 = 5289 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5290 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5291 if (!Res1.isUsable()) { 5292 IsCorrect = false; 5293 continue; 5294 } 5295 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5296 Res1 = 5297 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5298 if (!Res1.isUsable()) { 5299 IsCorrect = false; 5300 continue; 5301 } 5302 // Stepi > 0. 5303 ExprResult CmpRes = 5304 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5305 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5306 if (!CmpRes.isUsable()) { 5307 IsCorrect = false; 5308 continue; 5309 } 5310 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5311 Res.get(), Res1.get()); 5312 if (!Res.isUsable()) { 5313 IsCorrect = false; 5314 continue; 5315 } 5316 } 5317 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5318 if (!Res.isUsable()) { 5319 IsCorrect = false; 5320 continue; 5321 } 5322 5323 // Build counter update. 5324 // Build counter. 5325 auto *CounterVD = 5326 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5327 D.IteratorDecl->getBeginLoc(), nullptr, 5328 Res.get()->getType(), nullptr, SC_None); 5329 CounterVD->setImplicit(); 5330 ExprResult RefRes = 5331 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5332 D.IteratorDecl->getBeginLoc()); 5333 // Build counter update. 5334 // I = Begini + counter * Stepi; 5335 ExprResult UpdateRes; 5336 if (D.Range.Step) { 5337 UpdateRes = CreateBuiltinBinOp( 5338 D.AssignmentLoc, BO_Mul, 5339 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5340 } else { 5341 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5342 } 5343 if (!UpdateRes.isUsable()) { 5344 IsCorrect = false; 5345 continue; 5346 } 5347 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5348 UpdateRes.get()); 5349 if (!UpdateRes.isUsable()) { 5350 IsCorrect = false; 5351 continue; 5352 } 5353 ExprResult VDRes = 5354 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5355 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5356 D.IteratorDecl->getBeginLoc()); 5357 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5358 UpdateRes.get()); 5359 if (!UpdateRes.isUsable()) { 5360 IsCorrect = false; 5361 continue; 5362 } 5363 UpdateRes = 5364 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5365 if (!UpdateRes.isUsable()) { 5366 IsCorrect = false; 5367 continue; 5368 } 5369 ExprResult CounterUpdateRes = 5370 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5371 if (!CounterUpdateRes.isUsable()) { 5372 IsCorrect = false; 5373 continue; 5374 } 5375 CounterUpdateRes = 5376 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5377 if (!CounterUpdateRes.isUsable()) { 5378 IsCorrect = false; 5379 continue; 5380 } 5381 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5382 HD.CounterVD = CounterVD; 5383 HD.Upper = Res.get(); 5384 HD.Update = UpdateRes.get(); 5385 HD.CounterUpdate = CounterUpdateRes.get(); 5386 } 5387 } else { 5388 Helpers.assign(ID.size(), {}); 5389 } 5390 if (!IsCorrect) { 5391 // Invalidate all created iterator declarations if error is found. 5392 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5393 if (Decl *ID = D.IteratorDecl) 5394 ID->setInvalidDecl(); 5395 } 5396 return ExprError(); 5397 } 5398 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5399 LLoc, RLoc, ID, Helpers); 5400 } 5401 5402 ExprResult 5403 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5404 Expr *Idx, SourceLocation RLoc) { 5405 Expr *LHSExp = Base; 5406 Expr *RHSExp = Idx; 5407 5408 ExprValueKind VK = VK_LValue; 5409 ExprObjectKind OK = OK_Ordinary; 5410 5411 // Per C++ core issue 1213, the result is an xvalue if either operand is 5412 // a non-lvalue array, and an lvalue otherwise. 5413 if (getLangOpts().CPlusPlus11) { 5414 for (auto *Op : {LHSExp, RHSExp}) { 5415 Op = Op->IgnoreImplicit(); 5416 if (Op->getType()->isArrayType() && !Op->isLValue()) 5417 VK = VK_XValue; 5418 } 5419 } 5420 5421 // Perform default conversions. 5422 if (!LHSExp->getType()->getAs<VectorType>()) { 5423 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5424 if (Result.isInvalid()) 5425 return ExprError(); 5426 LHSExp = Result.get(); 5427 } 5428 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5429 if (Result.isInvalid()) 5430 return ExprError(); 5431 RHSExp = Result.get(); 5432 5433 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5434 5435 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5436 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5437 // in the subscript position. As a result, we need to derive the array base 5438 // and index from the expression types. 5439 Expr *BaseExpr, *IndexExpr; 5440 QualType ResultType; 5441 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5442 BaseExpr = LHSExp; 5443 IndexExpr = RHSExp; 5444 ResultType = Context.DependentTy; 5445 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5446 BaseExpr = LHSExp; 5447 IndexExpr = RHSExp; 5448 ResultType = PTy->getPointeeType(); 5449 } else if (const ObjCObjectPointerType *PTy = 5450 LHSTy->getAs<ObjCObjectPointerType>()) { 5451 BaseExpr = LHSExp; 5452 IndexExpr = RHSExp; 5453 5454 // Use custom logic if this should be the pseudo-object subscript 5455 // expression. 5456 if (!LangOpts.isSubscriptPointerArithmetic()) 5457 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5458 nullptr); 5459 5460 ResultType = PTy->getPointeeType(); 5461 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5462 // Handle the uncommon case of "123[Ptr]". 5463 BaseExpr = RHSExp; 5464 IndexExpr = LHSExp; 5465 ResultType = PTy->getPointeeType(); 5466 } else if (const ObjCObjectPointerType *PTy = 5467 RHSTy->getAs<ObjCObjectPointerType>()) { 5468 // Handle the uncommon case of "123[Ptr]". 5469 BaseExpr = RHSExp; 5470 IndexExpr = LHSExp; 5471 ResultType = PTy->getPointeeType(); 5472 if (!LangOpts.isSubscriptPointerArithmetic()) { 5473 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5474 << ResultType << BaseExpr->getSourceRange(); 5475 return ExprError(); 5476 } 5477 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5478 BaseExpr = LHSExp; // vectors: V[123] 5479 IndexExpr = RHSExp; 5480 // We apply C++ DR1213 to vector subscripting too. 5481 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5482 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5483 if (Materialized.isInvalid()) 5484 return ExprError(); 5485 LHSExp = Materialized.get(); 5486 } 5487 VK = LHSExp->getValueKind(); 5488 if (VK != VK_RValue) 5489 OK = OK_VectorComponent; 5490 5491 ResultType = VTy->getElementType(); 5492 QualType BaseType = BaseExpr->getType(); 5493 Qualifiers BaseQuals = BaseType.getQualifiers(); 5494 Qualifiers MemberQuals = ResultType.getQualifiers(); 5495 Qualifiers Combined = BaseQuals + MemberQuals; 5496 if (Combined != MemberQuals) 5497 ResultType = Context.getQualifiedType(ResultType, Combined); 5498 } else if (LHSTy->isArrayType()) { 5499 // If we see an array that wasn't promoted by 5500 // DefaultFunctionArrayLvalueConversion, it must be an array that 5501 // wasn't promoted because of the C90 rule that doesn't 5502 // allow promoting non-lvalue arrays. Warn, then 5503 // force the promotion here. 5504 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5505 << LHSExp->getSourceRange(); 5506 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5507 CK_ArrayToPointerDecay).get(); 5508 LHSTy = LHSExp->getType(); 5509 5510 BaseExpr = LHSExp; 5511 IndexExpr = RHSExp; 5512 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5513 } else if (RHSTy->isArrayType()) { 5514 // Same as previous, except for 123[f().a] case 5515 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5516 << RHSExp->getSourceRange(); 5517 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5518 CK_ArrayToPointerDecay).get(); 5519 RHSTy = RHSExp->getType(); 5520 5521 BaseExpr = RHSExp; 5522 IndexExpr = LHSExp; 5523 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5524 } else { 5525 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5526 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5527 } 5528 // C99 6.5.2.1p1 5529 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5530 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5531 << IndexExpr->getSourceRange()); 5532 5533 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5534 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5535 && !IndexExpr->isTypeDependent()) 5536 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5537 5538 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5539 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5540 // type. Note that Functions are not objects, and that (in C99 parlance) 5541 // incomplete types are not object types. 5542 if (ResultType->isFunctionType()) { 5543 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5544 << ResultType << BaseExpr->getSourceRange(); 5545 return ExprError(); 5546 } 5547 5548 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5549 // GNU extension: subscripting on pointer to void 5550 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5551 << BaseExpr->getSourceRange(); 5552 5553 // C forbids expressions of unqualified void type from being l-values. 5554 // See IsCForbiddenLValueType. 5555 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5556 } else if (!ResultType->isDependentType() && 5557 RequireCompleteSizedType( 5558 LLoc, ResultType, 5559 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5560 return ExprError(); 5561 5562 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5563 !ResultType.isCForbiddenLValueType()); 5564 5565 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5566 FunctionScopes.size() > 1) { 5567 if (auto *TT = 5568 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5569 for (auto I = FunctionScopes.rbegin(), 5570 E = std::prev(FunctionScopes.rend()); 5571 I != E; ++I) { 5572 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5573 if (CSI == nullptr) 5574 break; 5575 DeclContext *DC = nullptr; 5576 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5577 DC = LSI->CallOperator; 5578 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5579 DC = CRSI->TheCapturedDecl; 5580 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5581 DC = BSI->TheDecl; 5582 if (DC) { 5583 if (DC->containsDecl(TT->getDecl())) 5584 break; 5585 captureVariablyModifiedType( 5586 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5587 } 5588 } 5589 } 5590 } 5591 5592 return new (Context) 5593 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5594 } 5595 5596 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5597 ParmVarDecl *Param) { 5598 if (Param->hasUnparsedDefaultArg()) { 5599 // If we've already cleared out the location for the default argument, 5600 // that means we're parsing it right now. 5601 if (!UnparsedDefaultArgLocs.count(Param)) { 5602 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5603 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5604 Param->setInvalidDecl(); 5605 return true; 5606 } 5607 5608 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5609 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5610 Diag(UnparsedDefaultArgLocs[Param], 5611 diag::note_default_argument_declared_here); 5612 return true; 5613 } 5614 5615 if (Param->hasUninstantiatedDefaultArg() && 5616 InstantiateDefaultArgument(CallLoc, FD, Param)) 5617 return true; 5618 5619 assert(Param->hasInit() && "default argument but no initializer?"); 5620 5621 // If the default expression creates temporaries, we need to 5622 // push them to the current stack of expression temporaries so they'll 5623 // be properly destroyed. 5624 // FIXME: We should really be rebuilding the default argument with new 5625 // bound temporaries; see the comment in PR5810. 5626 // We don't need to do that with block decls, though, because 5627 // blocks in default argument expression can never capture anything. 5628 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5629 // Set the "needs cleanups" bit regardless of whether there are 5630 // any explicit objects. 5631 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5632 5633 // Append all the objects to the cleanup list. Right now, this 5634 // should always be a no-op, because blocks in default argument 5635 // expressions should never be able to capture anything. 5636 assert(!Init->getNumObjects() && 5637 "default argument expression has capturing blocks?"); 5638 } 5639 5640 // We already type-checked the argument, so we know it works. 5641 // Just mark all of the declarations in this potentially-evaluated expression 5642 // as being "referenced". 5643 EnterExpressionEvaluationContext EvalContext( 5644 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5645 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5646 /*SkipLocalVariables=*/true); 5647 return false; 5648 } 5649 5650 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5651 FunctionDecl *FD, ParmVarDecl *Param) { 5652 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5653 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5654 return ExprError(); 5655 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5656 } 5657 5658 Sema::VariadicCallType 5659 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5660 Expr *Fn) { 5661 if (Proto && Proto->isVariadic()) { 5662 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5663 return VariadicConstructor; 5664 else if (Fn && Fn->getType()->isBlockPointerType()) 5665 return VariadicBlock; 5666 else if (FDecl) { 5667 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5668 if (Method->isInstance()) 5669 return VariadicMethod; 5670 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5671 return VariadicMethod; 5672 return VariadicFunction; 5673 } 5674 return VariadicDoesNotApply; 5675 } 5676 5677 namespace { 5678 class FunctionCallCCC final : public FunctionCallFilterCCC { 5679 public: 5680 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5681 unsigned NumArgs, MemberExpr *ME) 5682 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5683 FunctionName(FuncName) {} 5684 5685 bool ValidateCandidate(const TypoCorrection &candidate) override { 5686 if (!candidate.getCorrectionSpecifier() || 5687 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5688 return false; 5689 } 5690 5691 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5692 } 5693 5694 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5695 return std::make_unique<FunctionCallCCC>(*this); 5696 } 5697 5698 private: 5699 const IdentifierInfo *const FunctionName; 5700 }; 5701 } 5702 5703 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5704 FunctionDecl *FDecl, 5705 ArrayRef<Expr *> Args) { 5706 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5707 DeclarationName FuncName = FDecl->getDeclName(); 5708 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5709 5710 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5711 if (TypoCorrection Corrected = S.CorrectTypo( 5712 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5713 S.getScopeForContext(S.CurContext), nullptr, CCC, 5714 Sema::CTK_ErrorRecovery)) { 5715 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5716 if (Corrected.isOverloaded()) { 5717 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5718 OverloadCandidateSet::iterator Best; 5719 for (NamedDecl *CD : Corrected) { 5720 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5721 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5722 OCS); 5723 } 5724 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5725 case OR_Success: 5726 ND = Best->FoundDecl; 5727 Corrected.setCorrectionDecl(ND); 5728 break; 5729 default: 5730 break; 5731 } 5732 } 5733 ND = ND->getUnderlyingDecl(); 5734 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5735 return Corrected; 5736 } 5737 } 5738 return TypoCorrection(); 5739 } 5740 5741 /// ConvertArgumentsForCall - Converts the arguments specified in 5742 /// Args/NumArgs to the parameter types of the function FDecl with 5743 /// function prototype Proto. Call is the call expression itself, and 5744 /// Fn is the function expression. For a C++ member function, this 5745 /// routine does not attempt to convert the object argument. Returns 5746 /// true if the call is ill-formed. 5747 bool 5748 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5749 FunctionDecl *FDecl, 5750 const FunctionProtoType *Proto, 5751 ArrayRef<Expr *> Args, 5752 SourceLocation RParenLoc, 5753 bool IsExecConfig) { 5754 // Bail out early if calling a builtin with custom typechecking. 5755 if (FDecl) 5756 if (unsigned ID = FDecl->getBuiltinID()) 5757 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5758 return false; 5759 5760 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5761 // assignment, to the types of the corresponding parameter, ... 5762 unsigned NumParams = Proto->getNumParams(); 5763 bool Invalid = false; 5764 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5765 unsigned FnKind = Fn->getType()->isBlockPointerType() 5766 ? 1 /* block */ 5767 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5768 : 0 /* function */); 5769 5770 // If too few arguments are available (and we don't have default 5771 // arguments for the remaining parameters), don't make the call. 5772 if (Args.size() < NumParams) { 5773 if (Args.size() < MinArgs) { 5774 TypoCorrection TC; 5775 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5776 unsigned diag_id = 5777 MinArgs == NumParams && !Proto->isVariadic() 5778 ? diag::err_typecheck_call_too_few_args_suggest 5779 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5780 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5781 << static_cast<unsigned>(Args.size()) 5782 << TC.getCorrectionRange()); 5783 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5784 Diag(RParenLoc, 5785 MinArgs == NumParams && !Proto->isVariadic() 5786 ? diag::err_typecheck_call_too_few_args_one 5787 : diag::err_typecheck_call_too_few_args_at_least_one) 5788 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5789 else 5790 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5791 ? diag::err_typecheck_call_too_few_args 5792 : diag::err_typecheck_call_too_few_args_at_least) 5793 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5794 << Fn->getSourceRange(); 5795 5796 // Emit the location of the prototype. 5797 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5798 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5799 5800 return true; 5801 } 5802 // We reserve space for the default arguments when we create 5803 // the call expression, before calling ConvertArgumentsForCall. 5804 assert((Call->getNumArgs() == NumParams) && 5805 "We should have reserved space for the default arguments before!"); 5806 } 5807 5808 // If too many are passed and not variadic, error on the extras and drop 5809 // them. 5810 if (Args.size() > NumParams) { 5811 if (!Proto->isVariadic()) { 5812 TypoCorrection TC; 5813 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5814 unsigned diag_id = 5815 MinArgs == NumParams && !Proto->isVariadic() 5816 ? diag::err_typecheck_call_too_many_args_suggest 5817 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5818 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5819 << static_cast<unsigned>(Args.size()) 5820 << TC.getCorrectionRange()); 5821 } else if (NumParams == 1 && FDecl && 5822 FDecl->getParamDecl(0)->getDeclName()) 5823 Diag(Args[NumParams]->getBeginLoc(), 5824 MinArgs == NumParams 5825 ? diag::err_typecheck_call_too_many_args_one 5826 : diag::err_typecheck_call_too_many_args_at_most_one) 5827 << FnKind << FDecl->getParamDecl(0) 5828 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5829 << SourceRange(Args[NumParams]->getBeginLoc(), 5830 Args.back()->getEndLoc()); 5831 else 5832 Diag(Args[NumParams]->getBeginLoc(), 5833 MinArgs == NumParams 5834 ? diag::err_typecheck_call_too_many_args 5835 : diag::err_typecheck_call_too_many_args_at_most) 5836 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5837 << Fn->getSourceRange() 5838 << SourceRange(Args[NumParams]->getBeginLoc(), 5839 Args.back()->getEndLoc()); 5840 5841 // Emit the location of the prototype. 5842 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5843 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5844 5845 // This deletes the extra arguments. 5846 Call->shrinkNumArgs(NumParams); 5847 return true; 5848 } 5849 } 5850 SmallVector<Expr *, 8> AllArgs; 5851 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5852 5853 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5854 AllArgs, CallType); 5855 if (Invalid) 5856 return true; 5857 unsigned TotalNumArgs = AllArgs.size(); 5858 for (unsigned i = 0; i < TotalNumArgs; ++i) 5859 Call->setArg(i, AllArgs[i]); 5860 5861 return false; 5862 } 5863 5864 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5865 const FunctionProtoType *Proto, 5866 unsigned FirstParam, ArrayRef<Expr *> Args, 5867 SmallVectorImpl<Expr *> &AllArgs, 5868 VariadicCallType CallType, bool AllowExplicit, 5869 bool IsListInitialization) { 5870 unsigned NumParams = Proto->getNumParams(); 5871 bool Invalid = false; 5872 size_t ArgIx = 0; 5873 // Continue to check argument types (even if we have too few/many args). 5874 for (unsigned i = FirstParam; i < NumParams; i++) { 5875 QualType ProtoArgType = Proto->getParamType(i); 5876 5877 Expr *Arg; 5878 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5879 if (ArgIx < Args.size()) { 5880 Arg = Args[ArgIx++]; 5881 5882 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5883 diag::err_call_incomplete_argument, Arg)) 5884 return true; 5885 5886 // Strip the unbridged-cast placeholder expression off, if applicable. 5887 bool CFAudited = false; 5888 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5889 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5890 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5891 Arg = stripARCUnbridgedCast(Arg); 5892 else if (getLangOpts().ObjCAutoRefCount && 5893 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5894 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5895 CFAudited = true; 5896 5897 if (Proto->getExtParameterInfo(i).isNoEscape()) 5898 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5899 BE->getBlockDecl()->setDoesNotEscape(); 5900 5901 InitializedEntity Entity = 5902 Param ? InitializedEntity::InitializeParameter(Context, Param, 5903 ProtoArgType) 5904 : InitializedEntity::InitializeParameter( 5905 Context, ProtoArgType, Proto->isParamConsumed(i)); 5906 5907 // Remember that parameter belongs to a CF audited API. 5908 if (CFAudited) 5909 Entity.setParameterCFAudited(); 5910 5911 ExprResult ArgE = PerformCopyInitialization( 5912 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5913 if (ArgE.isInvalid()) 5914 return true; 5915 5916 Arg = ArgE.getAs<Expr>(); 5917 } else { 5918 assert(Param && "can't use default arguments without a known callee"); 5919 5920 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5921 if (ArgExpr.isInvalid()) 5922 return true; 5923 5924 Arg = ArgExpr.getAs<Expr>(); 5925 } 5926 5927 // Check for array bounds violations for each argument to the call. This 5928 // check only triggers warnings when the argument isn't a more complex Expr 5929 // with its own checking, such as a BinaryOperator. 5930 CheckArrayAccess(Arg); 5931 5932 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5933 CheckStaticArrayArgument(CallLoc, Param, Arg); 5934 5935 AllArgs.push_back(Arg); 5936 } 5937 5938 // If this is a variadic call, handle args passed through "...". 5939 if (CallType != VariadicDoesNotApply) { 5940 // Assume that extern "C" functions with variadic arguments that 5941 // return __unknown_anytype aren't *really* variadic. 5942 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5943 FDecl->isExternC()) { 5944 for (Expr *A : Args.slice(ArgIx)) { 5945 QualType paramType; // ignored 5946 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5947 Invalid |= arg.isInvalid(); 5948 AllArgs.push_back(arg.get()); 5949 } 5950 5951 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5952 } else { 5953 for (Expr *A : Args.slice(ArgIx)) { 5954 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5955 Invalid |= Arg.isInvalid(); 5956 AllArgs.push_back(Arg.get()); 5957 } 5958 } 5959 5960 // Check for array bounds violations. 5961 for (Expr *A : Args.slice(ArgIx)) 5962 CheckArrayAccess(A); 5963 } 5964 return Invalid; 5965 } 5966 5967 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5968 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5969 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5970 TL = DTL.getOriginalLoc(); 5971 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5972 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5973 << ATL.getLocalSourceRange(); 5974 } 5975 5976 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5977 /// array parameter, check that it is non-null, and that if it is formed by 5978 /// array-to-pointer decay, the underlying array is sufficiently large. 5979 /// 5980 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5981 /// array type derivation, then for each call to the function, the value of the 5982 /// corresponding actual argument shall provide access to the first element of 5983 /// an array with at least as many elements as specified by the size expression. 5984 void 5985 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5986 ParmVarDecl *Param, 5987 const Expr *ArgExpr) { 5988 // Static array parameters are not supported in C++. 5989 if (!Param || getLangOpts().CPlusPlus) 5990 return; 5991 5992 QualType OrigTy = Param->getOriginalType(); 5993 5994 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5995 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5996 return; 5997 5998 if (ArgExpr->isNullPointerConstant(Context, 5999 Expr::NPC_NeverValueDependent)) { 6000 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6001 DiagnoseCalleeStaticArrayParam(*this, Param); 6002 return; 6003 } 6004 6005 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6006 if (!CAT) 6007 return; 6008 6009 const ConstantArrayType *ArgCAT = 6010 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6011 if (!ArgCAT) 6012 return; 6013 6014 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6015 ArgCAT->getElementType())) { 6016 if (ArgCAT->getSize().ult(CAT->getSize())) { 6017 Diag(CallLoc, diag::warn_static_array_too_small) 6018 << ArgExpr->getSourceRange() 6019 << (unsigned)ArgCAT->getSize().getZExtValue() 6020 << (unsigned)CAT->getSize().getZExtValue() << 0; 6021 DiagnoseCalleeStaticArrayParam(*this, Param); 6022 } 6023 return; 6024 } 6025 6026 Optional<CharUnits> ArgSize = 6027 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6028 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6029 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6030 Diag(CallLoc, diag::warn_static_array_too_small) 6031 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6032 << (unsigned)ParmSize->getQuantity() << 1; 6033 DiagnoseCalleeStaticArrayParam(*this, Param); 6034 } 6035 } 6036 6037 /// Given a function expression of unknown-any type, try to rebuild it 6038 /// to have a function type. 6039 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6040 6041 /// Is the given type a placeholder that we need to lower out 6042 /// immediately during argument processing? 6043 static bool isPlaceholderToRemoveAsArg(QualType type) { 6044 // Placeholders are never sugared. 6045 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6046 if (!placeholder) return false; 6047 6048 switch (placeholder->getKind()) { 6049 // Ignore all the non-placeholder types. 6050 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6051 case BuiltinType::Id: 6052 #include "clang/Basic/OpenCLImageTypes.def" 6053 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6054 case BuiltinType::Id: 6055 #include "clang/Basic/OpenCLExtensionTypes.def" 6056 // In practice we'll never use this, since all SVE types are sugared 6057 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6058 #define SVE_TYPE(Name, Id, SingletonId) \ 6059 case BuiltinType::Id: 6060 #include "clang/Basic/AArch64SVEACLETypes.def" 6061 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6062 case BuiltinType::Id: 6063 #include "clang/Basic/PPCTypes.def" 6064 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6065 #include "clang/Basic/RISCVVTypes.def" 6066 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6067 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6068 #include "clang/AST/BuiltinTypes.def" 6069 return false; 6070 6071 // We cannot lower out overload sets; they might validly be resolved 6072 // by the call machinery. 6073 case BuiltinType::Overload: 6074 return false; 6075 6076 // Unbridged casts in ARC can be handled in some call positions and 6077 // should be left in place. 6078 case BuiltinType::ARCUnbridgedCast: 6079 return false; 6080 6081 // Pseudo-objects should be converted as soon as possible. 6082 case BuiltinType::PseudoObject: 6083 return true; 6084 6085 // The debugger mode could theoretically but currently does not try 6086 // to resolve unknown-typed arguments based on known parameter types. 6087 case BuiltinType::UnknownAny: 6088 return true; 6089 6090 // These are always invalid as call arguments and should be reported. 6091 case BuiltinType::BoundMember: 6092 case BuiltinType::BuiltinFn: 6093 case BuiltinType::IncompleteMatrixIdx: 6094 case BuiltinType::OMPArraySection: 6095 case BuiltinType::OMPArrayShaping: 6096 case BuiltinType::OMPIterator: 6097 return true; 6098 6099 } 6100 llvm_unreachable("bad builtin type kind"); 6101 } 6102 6103 /// Check an argument list for placeholders that we won't try to 6104 /// handle later. 6105 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6106 // Apply this processing to all the arguments at once instead of 6107 // dying at the first failure. 6108 bool hasInvalid = false; 6109 for (size_t i = 0, e = args.size(); i != e; i++) { 6110 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6111 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6112 if (result.isInvalid()) hasInvalid = true; 6113 else args[i] = result.get(); 6114 } 6115 } 6116 return hasInvalid; 6117 } 6118 6119 /// If a builtin function has a pointer argument with no explicit address 6120 /// space, then it should be able to accept a pointer to any address 6121 /// space as input. In order to do this, we need to replace the 6122 /// standard builtin declaration with one that uses the same address space 6123 /// as the call. 6124 /// 6125 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6126 /// it does not contain any pointer arguments without 6127 /// an address space qualifer. Otherwise the rewritten 6128 /// FunctionDecl is returned. 6129 /// TODO: Handle pointer return types. 6130 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6131 FunctionDecl *FDecl, 6132 MultiExprArg ArgExprs) { 6133 6134 QualType DeclType = FDecl->getType(); 6135 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6136 6137 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6138 ArgExprs.size() < FT->getNumParams()) 6139 return nullptr; 6140 6141 bool NeedsNewDecl = false; 6142 unsigned i = 0; 6143 SmallVector<QualType, 8> OverloadParams; 6144 6145 for (QualType ParamType : FT->param_types()) { 6146 6147 // Convert array arguments to pointer to simplify type lookup. 6148 ExprResult ArgRes = 6149 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6150 if (ArgRes.isInvalid()) 6151 return nullptr; 6152 Expr *Arg = ArgRes.get(); 6153 QualType ArgType = Arg->getType(); 6154 if (!ParamType->isPointerType() || 6155 ParamType.hasAddressSpace() || 6156 !ArgType->isPointerType() || 6157 !ArgType->getPointeeType().hasAddressSpace()) { 6158 OverloadParams.push_back(ParamType); 6159 continue; 6160 } 6161 6162 QualType PointeeType = ParamType->getPointeeType(); 6163 if (PointeeType.hasAddressSpace()) 6164 continue; 6165 6166 NeedsNewDecl = true; 6167 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6168 6169 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6170 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6171 } 6172 6173 if (!NeedsNewDecl) 6174 return nullptr; 6175 6176 FunctionProtoType::ExtProtoInfo EPI; 6177 EPI.Variadic = FT->isVariadic(); 6178 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6179 OverloadParams, EPI); 6180 DeclContext *Parent = FDecl->getParent(); 6181 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6182 FDecl->getLocation(), 6183 FDecl->getLocation(), 6184 FDecl->getIdentifier(), 6185 OverloadTy, 6186 /*TInfo=*/nullptr, 6187 SC_Extern, false, 6188 /*hasPrototype=*/true); 6189 SmallVector<ParmVarDecl*, 16> Params; 6190 FT = cast<FunctionProtoType>(OverloadTy); 6191 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6192 QualType ParamType = FT->getParamType(i); 6193 ParmVarDecl *Parm = 6194 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6195 SourceLocation(), nullptr, ParamType, 6196 /*TInfo=*/nullptr, SC_None, nullptr); 6197 Parm->setScopeInfo(0, i); 6198 Params.push_back(Parm); 6199 } 6200 OverloadDecl->setParams(Params); 6201 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6202 return OverloadDecl; 6203 } 6204 6205 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6206 FunctionDecl *Callee, 6207 MultiExprArg ArgExprs) { 6208 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6209 // similar attributes) really don't like it when functions are called with an 6210 // invalid number of args. 6211 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6212 /*PartialOverloading=*/false) && 6213 !Callee->isVariadic()) 6214 return; 6215 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6216 return; 6217 6218 if (const EnableIfAttr *Attr = 6219 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6220 S.Diag(Fn->getBeginLoc(), 6221 isa<CXXMethodDecl>(Callee) 6222 ? diag::err_ovl_no_viable_member_function_in_call 6223 : diag::err_ovl_no_viable_function_in_call) 6224 << Callee << Callee->getSourceRange(); 6225 S.Diag(Callee->getLocation(), 6226 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6227 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6228 return; 6229 } 6230 } 6231 6232 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6233 const UnresolvedMemberExpr *const UME, Sema &S) { 6234 6235 const auto GetFunctionLevelDCIfCXXClass = 6236 [](Sema &S) -> const CXXRecordDecl * { 6237 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6238 if (!DC || !DC->getParent()) 6239 return nullptr; 6240 6241 // If the call to some member function was made from within a member 6242 // function body 'M' return return 'M's parent. 6243 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6244 return MD->getParent()->getCanonicalDecl(); 6245 // else the call was made from within a default member initializer of a 6246 // class, so return the class. 6247 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6248 return RD->getCanonicalDecl(); 6249 return nullptr; 6250 }; 6251 // If our DeclContext is neither a member function nor a class (in the 6252 // case of a lambda in a default member initializer), we can't have an 6253 // enclosing 'this'. 6254 6255 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6256 if (!CurParentClass) 6257 return false; 6258 6259 // The naming class for implicit member functions call is the class in which 6260 // name lookup starts. 6261 const CXXRecordDecl *const NamingClass = 6262 UME->getNamingClass()->getCanonicalDecl(); 6263 assert(NamingClass && "Must have naming class even for implicit access"); 6264 6265 // If the unresolved member functions were found in a 'naming class' that is 6266 // related (either the same or derived from) to the class that contains the 6267 // member function that itself contained the implicit member access. 6268 6269 return CurParentClass == NamingClass || 6270 CurParentClass->isDerivedFrom(NamingClass); 6271 } 6272 6273 static void 6274 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6275 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6276 6277 if (!UME) 6278 return; 6279 6280 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6281 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6282 // already been captured, or if this is an implicit member function call (if 6283 // it isn't, an attempt to capture 'this' should already have been made). 6284 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6285 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6286 return; 6287 6288 // Check if the naming class in which the unresolved members were found is 6289 // related (same as or is a base of) to the enclosing class. 6290 6291 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6292 return; 6293 6294 6295 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6296 // If the enclosing function is not dependent, then this lambda is 6297 // capture ready, so if we can capture this, do so. 6298 if (!EnclosingFunctionCtx->isDependentContext()) { 6299 // If the current lambda and all enclosing lambdas can capture 'this' - 6300 // then go ahead and capture 'this' (since our unresolved overload set 6301 // contains at least one non-static member function). 6302 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6303 S.CheckCXXThisCapture(CallLoc); 6304 } else if (S.CurContext->isDependentContext()) { 6305 // ... since this is an implicit member reference, that might potentially 6306 // involve a 'this' capture, mark 'this' for potential capture in 6307 // enclosing lambdas. 6308 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6309 CurLSI->addPotentialThisCapture(CallLoc); 6310 } 6311 } 6312 6313 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6314 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6315 Expr *ExecConfig) { 6316 ExprResult Call = 6317 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6318 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6319 if (Call.isInvalid()) 6320 return Call; 6321 6322 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6323 // language modes. 6324 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6325 if (ULE->hasExplicitTemplateArgs() && 6326 ULE->decls_begin() == ULE->decls_end()) { 6327 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6328 ? diag::warn_cxx17_compat_adl_only_template_id 6329 : diag::ext_adl_only_template_id) 6330 << ULE->getName(); 6331 } 6332 } 6333 6334 if (LangOpts.OpenMP) 6335 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6336 ExecConfig); 6337 6338 return Call; 6339 } 6340 6341 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6342 /// This provides the location of the left/right parens and a list of comma 6343 /// locations. 6344 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6345 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6346 Expr *ExecConfig, bool IsExecConfig, 6347 bool AllowRecovery) { 6348 // Since this might be a postfix expression, get rid of ParenListExprs. 6349 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6350 if (Result.isInvalid()) return ExprError(); 6351 Fn = Result.get(); 6352 6353 if (checkArgsForPlaceholders(*this, ArgExprs)) 6354 return ExprError(); 6355 6356 if (getLangOpts().CPlusPlus) { 6357 // If this is a pseudo-destructor expression, build the call immediately. 6358 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6359 if (!ArgExprs.empty()) { 6360 // Pseudo-destructor calls should not have any arguments. 6361 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6362 << FixItHint::CreateRemoval( 6363 SourceRange(ArgExprs.front()->getBeginLoc(), 6364 ArgExprs.back()->getEndLoc())); 6365 } 6366 6367 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6368 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6369 } 6370 if (Fn->getType() == Context.PseudoObjectTy) { 6371 ExprResult result = CheckPlaceholderExpr(Fn); 6372 if (result.isInvalid()) return ExprError(); 6373 Fn = result.get(); 6374 } 6375 6376 // Determine whether this is a dependent call inside a C++ template, 6377 // in which case we won't do any semantic analysis now. 6378 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6379 if (ExecConfig) { 6380 return CUDAKernelCallExpr::Create( 6381 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6382 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6383 } else { 6384 6385 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6386 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6387 Fn->getBeginLoc()); 6388 6389 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6390 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6391 } 6392 } 6393 6394 // Determine whether this is a call to an object (C++ [over.call.object]). 6395 if (Fn->getType()->isRecordType()) 6396 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6397 RParenLoc); 6398 6399 if (Fn->getType() == Context.UnknownAnyTy) { 6400 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6401 if (result.isInvalid()) return ExprError(); 6402 Fn = result.get(); 6403 } 6404 6405 if (Fn->getType() == Context.BoundMemberTy) { 6406 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6407 RParenLoc, AllowRecovery); 6408 } 6409 } 6410 6411 // Check for overloaded calls. This can happen even in C due to extensions. 6412 if (Fn->getType() == Context.OverloadTy) { 6413 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6414 6415 // We aren't supposed to apply this logic if there's an '&' involved. 6416 if (!find.HasFormOfMemberPointer) { 6417 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6418 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6419 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6420 OverloadExpr *ovl = find.Expression; 6421 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6422 return BuildOverloadedCallExpr( 6423 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6424 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6425 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6426 RParenLoc, AllowRecovery); 6427 } 6428 } 6429 6430 // If we're directly calling a function, get the appropriate declaration. 6431 if (Fn->getType() == Context.UnknownAnyTy) { 6432 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6433 if (result.isInvalid()) return ExprError(); 6434 Fn = result.get(); 6435 } 6436 6437 Expr *NakedFn = Fn->IgnoreParens(); 6438 6439 bool CallingNDeclIndirectly = false; 6440 NamedDecl *NDecl = nullptr; 6441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6442 if (UnOp->getOpcode() == UO_AddrOf) { 6443 CallingNDeclIndirectly = true; 6444 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6445 } 6446 } 6447 6448 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6449 NDecl = DRE->getDecl(); 6450 6451 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6452 if (FDecl && FDecl->getBuiltinID()) { 6453 // Rewrite the function decl for this builtin by replacing parameters 6454 // with no explicit address space with the address space of the arguments 6455 // in ArgExprs. 6456 if ((FDecl = 6457 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6458 NDecl = FDecl; 6459 Fn = DeclRefExpr::Create( 6460 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6461 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6462 nullptr, DRE->isNonOdrUse()); 6463 } 6464 } 6465 } else if (isa<MemberExpr>(NakedFn)) 6466 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6467 6468 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6469 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6470 FD, /*Complain=*/true, Fn->getBeginLoc())) 6471 return ExprError(); 6472 6473 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6474 return ExprError(); 6475 6476 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6477 } 6478 6479 if (Context.isDependenceAllowed() && 6480 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6481 assert(!getLangOpts().CPlusPlus); 6482 assert((Fn->containsErrors() || 6483 llvm::any_of(ArgExprs, 6484 [](clang::Expr *E) { return E->containsErrors(); })) && 6485 "should only occur in error-recovery path."); 6486 QualType ReturnType = 6487 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6488 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6489 : Context.DependentTy; 6490 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6491 Expr::getValueKindForType(ReturnType), RParenLoc, 6492 CurFPFeatureOverrides()); 6493 } 6494 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6495 ExecConfig, IsExecConfig); 6496 } 6497 6498 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 6499 /// 6500 /// __builtin_astype( value, dst type ) 6501 /// 6502 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6503 SourceLocation BuiltinLoc, 6504 SourceLocation RParenLoc) { 6505 ExprValueKind VK = VK_RValue; 6506 ExprObjectKind OK = OK_Ordinary; 6507 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6508 QualType SrcTy = E->getType(); 6509 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 6510 return ExprError(Diag(BuiltinLoc, 6511 diag::err_invalid_astype_of_different_size) 6512 << DstTy 6513 << SrcTy 6514 << E->getSourceRange()); 6515 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6516 } 6517 6518 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6519 /// provided arguments. 6520 /// 6521 /// __builtin_convertvector( value, dst type ) 6522 /// 6523 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6524 SourceLocation BuiltinLoc, 6525 SourceLocation RParenLoc) { 6526 TypeSourceInfo *TInfo; 6527 GetTypeFromParser(ParsedDestTy, &TInfo); 6528 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6529 } 6530 6531 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6532 /// i.e. an expression not of \p OverloadTy. The expression should 6533 /// unary-convert to an expression of function-pointer or 6534 /// block-pointer type. 6535 /// 6536 /// \param NDecl the declaration being called, if available 6537 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6538 SourceLocation LParenLoc, 6539 ArrayRef<Expr *> Args, 6540 SourceLocation RParenLoc, Expr *Config, 6541 bool IsExecConfig, ADLCallKind UsesADL) { 6542 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6543 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6544 6545 // Functions with 'interrupt' attribute cannot be called directly. 6546 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6547 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6548 return ExprError(); 6549 } 6550 6551 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6552 // so there's some risk when calling out to non-interrupt handler functions 6553 // that the callee might not preserve them. This is easy to diagnose here, 6554 // but can be very challenging to debug. 6555 // Likewise, X86 interrupt handlers may only call routines with attribute 6556 // no_caller_saved_registers since there is no efficient way to 6557 // save and restore the non-GPR state. 6558 if (auto *Caller = getCurFunctionDecl()) { 6559 if (Caller->hasAttr<ARMInterruptAttr>()) { 6560 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6561 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6562 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6563 if (FDecl) 6564 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6565 } 6566 } 6567 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6568 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6569 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_regsave); 6570 if (FDecl) 6571 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6572 } 6573 } 6574 6575 // Promote the function operand. 6576 // We special-case function promotion here because we only allow promoting 6577 // builtin functions to function pointers in the callee of a call. 6578 ExprResult Result; 6579 QualType ResultTy; 6580 if (BuiltinID && 6581 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6582 // Extract the return type from the (builtin) function pointer type. 6583 // FIXME Several builtins still have setType in 6584 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6585 // Builtins.def to ensure they are correct before removing setType calls. 6586 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6587 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6588 ResultTy = FDecl->getCallResultType(); 6589 } else { 6590 Result = CallExprUnaryConversions(Fn); 6591 ResultTy = Context.BoolTy; 6592 } 6593 if (Result.isInvalid()) 6594 return ExprError(); 6595 Fn = Result.get(); 6596 6597 // Check for a valid function type, but only if it is not a builtin which 6598 // requires custom type checking. These will be handled by 6599 // CheckBuiltinFunctionCall below just after creation of the call expression. 6600 const FunctionType *FuncT = nullptr; 6601 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6602 retry: 6603 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6604 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6605 // have type pointer to function". 6606 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6607 if (!FuncT) 6608 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6609 << Fn->getType() << Fn->getSourceRange()); 6610 } else if (const BlockPointerType *BPT = 6611 Fn->getType()->getAs<BlockPointerType>()) { 6612 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6613 } else { 6614 // Handle calls to expressions of unknown-any type. 6615 if (Fn->getType() == Context.UnknownAnyTy) { 6616 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6617 if (rewrite.isInvalid()) 6618 return ExprError(); 6619 Fn = rewrite.get(); 6620 goto retry; 6621 } 6622 6623 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6624 << Fn->getType() << Fn->getSourceRange()); 6625 } 6626 } 6627 6628 // Get the number of parameters in the function prototype, if any. 6629 // We will allocate space for max(Args.size(), NumParams) arguments 6630 // in the call expression. 6631 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6632 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6633 6634 CallExpr *TheCall; 6635 if (Config) { 6636 assert(UsesADL == ADLCallKind::NotADL && 6637 "CUDAKernelCallExpr should not use ADL"); 6638 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6639 Args, ResultTy, VK_RValue, RParenLoc, 6640 CurFPFeatureOverrides(), NumParams); 6641 } else { 6642 TheCall = 6643 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6644 CurFPFeatureOverrides(), NumParams, UsesADL); 6645 } 6646 6647 if (!Context.isDependenceAllowed()) { 6648 // Forget about the nulled arguments since typo correction 6649 // do not handle them well. 6650 TheCall->shrinkNumArgs(Args.size()); 6651 // C cannot always handle TypoExpr nodes in builtin calls and direct 6652 // function calls as their argument checking don't necessarily handle 6653 // dependent types properly, so make sure any TypoExprs have been 6654 // dealt with. 6655 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6656 if (!Result.isUsable()) return ExprError(); 6657 CallExpr *TheOldCall = TheCall; 6658 TheCall = dyn_cast<CallExpr>(Result.get()); 6659 bool CorrectedTypos = TheCall != TheOldCall; 6660 if (!TheCall) return Result; 6661 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6662 6663 // A new call expression node was created if some typos were corrected. 6664 // However it may not have been constructed with enough storage. In this 6665 // case, rebuild the node with enough storage. The waste of space is 6666 // immaterial since this only happens when some typos were corrected. 6667 if (CorrectedTypos && Args.size() < NumParams) { 6668 if (Config) 6669 TheCall = CUDAKernelCallExpr::Create( 6670 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6671 RParenLoc, CurFPFeatureOverrides(), NumParams); 6672 else 6673 TheCall = 6674 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6675 CurFPFeatureOverrides(), NumParams, UsesADL); 6676 } 6677 // We can now handle the nulled arguments for the default arguments. 6678 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6679 } 6680 6681 // Bail out early if calling a builtin with custom type checking. 6682 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6683 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6684 6685 if (getLangOpts().CUDA) { 6686 if (Config) { 6687 // CUDA: Kernel calls must be to global functions 6688 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6689 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6690 << FDecl << Fn->getSourceRange()); 6691 6692 // CUDA: Kernel function must have 'void' return type 6693 if (!FuncT->getReturnType()->isVoidType() && 6694 !FuncT->getReturnType()->getAs<AutoType>() && 6695 !FuncT->getReturnType()->isInstantiationDependentType()) 6696 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6697 << Fn->getType() << Fn->getSourceRange()); 6698 } else { 6699 // CUDA: Calls to global functions must be configured 6700 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6701 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6702 << FDecl << Fn->getSourceRange()); 6703 } 6704 } 6705 6706 // Check for a valid return type 6707 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6708 FDecl)) 6709 return ExprError(); 6710 6711 // We know the result type of the call, set it. 6712 TheCall->setType(FuncT->getCallResultType(Context)); 6713 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6714 6715 if (Proto) { 6716 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6717 IsExecConfig)) 6718 return ExprError(); 6719 } else { 6720 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6721 6722 if (FDecl) { 6723 // Check if we have too few/too many template arguments, based 6724 // on our knowledge of the function definition. 6725 const FunctionDecl *Def = nullptr; 6726 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6727 Proto = Def->getType()->getAs<FunctionProtoType>(); 6728 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6729 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6730 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6731 } 6732 6733 // If the function we're calling isn't a function prototype, but we have 6734 // a function prototype from a prior declaratiom, use that prototype. 6735 if (!FDecl->hasPrototype()) 6736 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6737 } 6738 6739 // Promote the arguments (C99 6.5.2.2p6). 6740 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6741 Expr *Arg = Args[i]; 6742 6743 if (Proto && i < Proto->getNumParams()) { 6744 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6745 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6746 ExprResult ArgE = 6747 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6748 if (ArgE.isInvalid()) 6749 return true; 6750 6751 Arg = ArgE.getAs<Expr>(); 6752 6753 } else { 6754 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6755 6756 if (ArgE.isInvalid()) 6757 return true; 6758 6759 Arg = ArgE.getAs<Expr>(); 6760 } 6761 6762 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6763 diag::err_call_incomplete_argument, Arg)) 6764 return ExprError(); 6765 6766 TheCall->setArg(i, Arg); 6767 } 6768 } 6769 6770 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6771 if (!Method->isStatic()) 6772 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6773 << Fn->getSourceRange()); 6774 6775 // Check for sentinels 6776 if (NDecl) 6777 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6778 6779 // Warn for unions passing across security boundary (CMSE). 6780 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6781 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6782 if (const auto *RT = 6783 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6784 if (RT->getDecl()->isOrContainsUnion()) 6785 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6786 << 0 << i; 6787 } 6788 } 6789 } 6790 6791 // Do special checking on direct calls to functions. 6792 if (FDecl) { 6793 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6794 return ExprError(); 6795 6796 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6797 6798 if (BuiltinID) 6799 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6800 } else if (NDecl) { 6801 if (CheckPointerCall(NDecl, TheCall, Proto)) 6802 return ExprError(); 6803 } else { 6804 if (CheckOtherCall(TheCall, Proto)) 6805 return ExprError(); 6806 } 6807 6808 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6809 } 6810 6811 ExprResult 6812 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6813 SourceLocation RParenLoc, Expr *InitExpr) { 6814 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6815 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6816 6817 TypeSourceInfo *TInfo; 6818 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6819 if (!TInfo) 6820 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6821 6822 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6823 } 6824 6825 ExprResult 6826 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6827 SourceLocation RParenLoc, Expr *LiteralExpr) { 6828 QualType literalType = TInfo->getType(); 6829 6830 if (literalType->isArrayType()) { 6831 if (RequireCompleteSizedType( 6832 LParenLoc, Context.getBaseElementType(literalType), 6833 diag::err_array_incomplete_or_sizeless_type, 6834 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6835 return ExprError(); 6836 if (literalType->isVariableArrayType()) 6837 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6838 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6839 } else if (!literalType->isDependentType() && 6840 RequireCompleteType(LParenLoc, literalType, 6841 diag::err_typecheck_decl_incomplete_type, 6842 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6843 return ExprError(); 6844 6845 InitializedEntity Entity 6846 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6847 InitializationKind Kind 6848 = InitializationKind::CreateCStyleCast(LParenLoc, 6849 SourceRange(LParenLoc, RParenLoc), 6850 /*InitList=*/true); 6851 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6852 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6853 &literalType); 6854 if (Result.isInvalid()) 6855 return ExprError(); 6856 LiteralExpr = Result.get(); 6857 6858 bool isFileScope = !CurContext->isFunctionOrMethod(); 6859 6860 // In C, compound literals are l-values for some reason. 6861 // For GCC compatibility, in C++, file-scope array compound literals with 6862 // constant initializers are also l-values, and compound literals are 6863 // otherwise prvalues. 6864 // 6865 // (GCC also treats C++ list-initialized file-scope array prvalues with 6866 // constant initializers as l-values, but that's non-conforming, so we don't 6867 // follow it there.) 6868 // 6869 // FIXME: It would be better to handle the lvalue cases as materializing and 6870 // lifetime-extending a temporary object, but our materialized temporaries 6871 // representation only supports lifetime extension from a variable, not "out 6872 // of thin air". 6873 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6874 // is bound to the result of applying array-to-pointer decay to the compound 6875 // literal. 6876 // FIXME: GCC supports compound literals of reference type, which should 6877 // obviously have a value kind derived from the kind of reference involved. 6878 ExprValueKind VK = 6879 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6880 ? VK_RValue 6881 : VK_LValue; 6882 6883 if (isFileScope) 6884 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6885 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6886 Expr *Init = ILE->getInit(i); 6887 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6888 } 6889 6890 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6891 VK, LiteralExpr, isFileScope); 6892 if (isFileScope) { 6893 if (!LiteralExpr->isTypeDependent() && 6894 !LiteralExpr->isValueDependent() && 6895 !literalType->isDependentType()) // C99 6.5.2.5p3 6896 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6897 return ExprError(); 6898 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6899 literalType.getAddressSpace() != LangAS::Default) { 6900 // Embedded-C extensions to C99 6.5.2.5: 6901 // "If the compound literal occurs inside the body of a function, the 6902 // type name shall not be qualified by an address-space qualifier." 6903 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6904 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6905 return ExprError(); 6906 } 6907 6908 if (!isFileScope && !getLangOpts().CPlusPlus) { 6909 // Compound literals that have automatic storage duration are destroyed at 6910 // the end of the scope in C; in C++, they're just temporaries. 6911 6912 // Emit diagnostics if it is or contains a C union type that is non-trivial 6913 // to destruct. 6914 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6915 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6916 NTCUC_CompoundLiteral, NTCUK_Destruct); 6917 6918 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6919 if (literalType.isDestructedType()) { 6920 Cleanup.setExprNeedsCleanups(true); 6921 ExprCleanupObjects.push_back(E); 6922 getCurFunction()->setHasBranchProtectedScope(); 6923 } 6924 } 6925 6926 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6927 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6928 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6929 E->getInitializer()->getExprLoc()); 6930 6931 return MaybeBindToTemporary(E); 6932 } 6933 6934 ExprResult 6935 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6936 SourceLocation RBraceLoc) { 6937 // Only produce each kind of designated initialization diagnostic once. 6938 SourceLocation FirstDesignator; 6939 bool DiagnosedArrayDesignator = false; 6940 bool DiagnosedNestedDesignator = false; 6941 bool DiagnosedMixedDesignator = false; 6942 6943 // Check that any designated initializers are syntactically valid in the 6944 // current language mode. 6945 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6946 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6947 if (FirstDesignator.isInvalid()) 6948 FirstDesignator = DIE->getBeginLoc(); 6949 6950 if (!getLangOpts().CPlusPlus) 6951 break; 6952 6953 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6954 DiagnosedNestedDesignator = true; 6955 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6956 << DIE->getDesignatorsSourceRange(); 6957 } 6958 6959 for (auto &Desig : DIE->designators()) { 6960 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6961 DiagnosedArrayDesignator = true; 6962 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6963 << Desig.getSourceRange(); 6964 } 6965 } 6966 6967 if (!DiagnosedMixedDesignator && 6968 !isa<DesignatedInitExpr>(InitArgList[0])) { 6969 DiagnosedMixedDesignator = true; 6970 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6971 << DIE->getSourceRange(); 6972 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6973 << InitArgList[0]->getSourceRange(); 6974 } 6975 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6976 isa<DesignatedInitExpr>(InitArgList[0])) { 6977 DiagnosedMixedDesignator = true; 6978 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6979 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6980 << DIE->getSourceRange(); 6981 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6982 << InitArgList[I]->getSourceRange(); 6983 } 6984 } 6985 6986 if (FirstDesignator.isValid()) { 6987 // Only diagnose designated initiaization as a C++20 extension if we didn't 6988 // already diagnose use of (non-C++20) C99 designator syntax. 6989 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6990 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6991 Diag(FirstDesignator, getLangOpts().CPlusPlus20 6992 ? diag::warn_cxx17_compat_designated_init 6993 : diag::ext_cxx_designated_init); 6994 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6995 Diag(FirstDesignator, diag::ext_designated_init); 6996 } 6997 } 6998 6999 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7000 } 7001 7002 ExprResult 7003 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7004 SourceLocation RBraceLoc) { 7005 // Semantic analysis for initializers is done by ActOnDeclarator() and 7006 // CheckInitializer() - it requires knowledge of the object being initialized. 7007 7008 // Immediately handle non-overload placeholders. Overloads can be 7009 // resolved contextually, but everything else here can't. 7010 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7011 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7012 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7013 7014 // Ignore failures; dropping the entire initializer list because 7015 // of one failure would be terrible for indexing/etc. 7016 if (result.isInvalid()) continue; 7017 7018 InitArgList[I] = result.get(); 7019 } 7020 } 7021 7022 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7023 RBraceLoc); 7024 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7025 return E; 7026 } 7027 7028 /// Do an explicit extend of the given block pointer if we're in ARC. 7029 void Sema::maybeExtendBlockObject(ExprResult &E) { 7030 assert(E.get()->getType()->isBlockPointerType()); 7031 assert(E.get()->isRValue()); 7032 7033 // Only do this in an r-value context. 7034 if (!getLangOpts().ObjCAutoRefCount) return; 7035 7036 E = ImplicitCastExpr::Create( 7037 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7038 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7039 Cleanup.setExprNeedsCleanups(true); 7040 } 7041 7042 /// Prepare a conversion of the given expression to an ObjC object 7043 /// pointer type. 7044 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7045 QualType type = E.get()->getType(); 7046 if (type->isObjCObjectPointerType()) { 7047 return CK_BitCast; 7048 } else if (type->isBlockPointerType()) { 7049 maybeExtendBlockObject(E); 7050 return CK_BlockPointerToObjCPointerCast; 7051 } else { 7052 assert(type->isPointerType()); 7053 return CK_CPointerToObjCPointerCast; 7054 } 7055 } 7056 7057 /// Prepares for a scalar cast, performing all the necessary stages 7058 /// except the final cast and returning the kind required. 7059 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7060 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7061 // Also, callers should have filtered out the invalid cases with 7062 // pointers. Everything else should be possible. 7063 7064 QualType SrcTy = Src.get()->getType(); 7065 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7066 return CK_NoOp; 7067 7068 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7069 case Type::STK_MemberPointer: 7070 llvm_unreachable("member pointer type in C"); 7071 7072 case Type::STK_CPointer: 7073 case Type::STK_BlockPointer: 7074 case Type::STK_ObjCObjectPointer: 7075 switch (DestTy->getScalarTypeKind()) { 7076 case Type::STK_CPointer: { 7077 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7078 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7079 if (SrcAS != DestAS) 7080 return CK_AddressSpaceConversion; 7081 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7082 return CK_NoOp; 7083 return CK_BitCast; 7084 } 7085 case Type::STK_BlockPointer: 7086 return (SrcKind == Type::STK_BlockPointer 7087 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7088 case Type::STK_ObjCObjectPointer: 7089 if (SrcKind == Type::STK_ObjCObjectPointer) 7090 return CK_BitCast; 7091 if (SrcKind == Type::STK_CPointer) 7092 return CK_CPointerToObjCPointerCast; 7093 maybeExtendBlockObject(Src); 7094 return CK_BlockPointerToObjCPointerCast; 7095 case Type::STK_Bool: 7096 return CK_PointerToBoolean; 7097 case Type::STK_Integral: 7098 return CK_PointerToIntegral; 7099 case Type::STK_Floating: 7100 case Type::STK_FloatingComplex: 7101 case Type::STK_IntegralComplex: 7102 case Type::STK_MemberPointer: 7103 case Type::STK_FixedPoint: 7104 llvm_unreachable("illegal cast from pointer"); 7105 } 7106 llvm_unreachable("Should have returned before this"); 7107 7108 case Type::STK_FixedPoint: 7109 switch (DestTy->getScalarTypeKind()) { 7110 case Type::STK_FixedPoint: 7111 return CK_FixedPointCast; 7112 case Type::STK_Bool: 7113 return CK_FixedPointToBoolean; 7114 case Type::STK_Integral: 7115 return CK_FixedPointToIntegral; 7116 case Type::STK_Floating: 7117 return CK_FixedPointToFloating; 7118 case Type::STK_IntegralComplex: 7119 case Type::STK_FloatingComplex: 7120 Diag(Src.get()->getExprLoc(), 7121 diag::err_unimplemented_conversion_with_fixed_point_type) 7122 << DestTy; 7123 return CK_IntegralCast; 7124 case Type::STK_CPointer: 7125 case Type::STK_ObjCObjectPointer: 7126 case Type::STK_BlockPointer: 7127 case Type::STK_MemberPointer: 7128 llvm_unreachable("illegal cast to pointer type"); 7129 } 7130 llvm_unreachable("Should have returned before this"); 7131 7132 case Type::STK_Bool: // casting from bool is like casting from an integer 7133 case Type::STK_Integral: 7134 switch (DestTy->getScalarTypeKind()) { 7135 case Type::STK_CPointer: 7136 case Type::STK_ObjCObjectPointer: 7137 case Type::STK_BlockPointer: 7138 if (Src.get()->isNullPointerConstant(Context, 7139 Expr::NPC_ValueDependentIsNull)) 7140 return CK_NullToPointer; 7141 return CK_IntegralToPointer; 7142 case Type::STK_Bool: 7143 return CK_IntegralToBoolean; 7144 case Type::STK_Integral: 7145 return CK_IntegralCast; 7146 case Type::STK_Floating: 7147 return CK_IntegralToFloating; 7148 case Type::STK_IntegralComplex: 7149 Src = ImpCastExprToType(Src.get(), 7150 DestTy->castAs<ComplexType>()->getElementType(), 7151 CK_IntegralCast); 7152 return CK_IntegralRealToComplex; 7153 case Type::STK_FloatingComplex: 7154 Src = ImpCastExprToType(Src.get(), 7155 DestTy->castAs<ComplexType>()->getElementType(), 7156 CK_IntegralToFloating); 7157 return CK_FloatingRealToComplex; 7158 case Type::STK_MemberPointer: 7159 llvm_unreachable("member pointer type in C"); 7160 case Type::STK_FixedPoint: 7161 return CK_IntegralToFixedPoint; 7162 } 7163 llvm_unreachable("Should have returned before this"); 7164 7165 case Type::STK_Floating: 7166 switch (DestTy->getScalarTypeKind()) { 7167 case Type::STK_Floating: 7168 return CK_FloatingCast; 7169 case Type::STK_Bool: 7170 return CK_FloatingToBoolean; 7171 case Type::STK_Integral: 7172 return CK_FloatingToIntegral; 7173 case Type::STK_FloatingComplex: 7174 Src = ImpCastExprToType(Src.get(), 7175 DestTy->castAs<ComplexType>()->getElementType(), 7176 CK_FloatingCast); 7177 return CK_FloatingRealToComplex; 7178 case Type::STK_IntegralComplex: 7179 Src = ImpCastExprToType(Src.get(), 7180 DestTy->castAs<ComplexType>()->getElementType(), 7181 CK_FloatingToIntegral); 7182 return CK_IntegralRealToComplex; 7183 case Type::STK_CPointer: 7184 case Type::STK_ObjCObjectPointer: 7185 case Type::STK_BlockPointer: 7186 llvm_unreachable("valid float->pointer cast?"); 7187 case Type::STK_MemberPointer: 7188 llvm_unreachable("member pointer type in C"); 7189 case Type::STK_FixedPoint: 7190 return CK_FloatingToFixedPoint; 7191 } 7192 llvm_unreachable("Should have returned before this"); 7193 7194 case Type::STK_FloatingComplex: 7195 switch (DestTy->getScalarTypeKind()) { 7196 case Type::STK_FloatingComplex: 7197 return CK_FloatingComplexCast; 7198 case Type::STK_IntegralComplex: 7199 return CK_FloatingComplexToIntegralComplex; 7200 case Type::STK_Floating: { 7201 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7202 if (Context.hasSameType(ET, DestTy)) 7203 return CK_FloatingComplexToReal; 7204 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7205 return CK_FloatingCast; 7206 } 7207 case Type::STK_Bool: 7208 return CK_FloatingComplexToBoolean; 7209 case Type::STK_Integral: 7210 Src = ImpCastExprToType(Src.get(), 7211 SrcTy->castAs<ComplexType>()->getElementType(), 7212 CK_FloatingComplexToReal); 7213 return CK_FloatingToIntegral; 7214 case Type::STK_CPointer: 7215 case Type::STK_ObjCObjectPointer: 7216 case Type::STK_BlockPointer: 7217 llvm_unreachable("valid complex float->pointer cast?"); 7218 case Type::STK_MemberPointer: 7219 llvm_unreachable("member pointer type in C"); 7220 case Type::STK_FixedPoint: 7221 Diag(Src.get()->getExprLoc(), 7222 diag::err_unimplemented_conversion_with_fixed_point_type) 7223 << SrcTy; 7224 return CK_IntegralCast; 7225 } 7226 llvm_unreachable("Should have returned before this"); 7227 7228 case Type::STK_IntegralComplex: 7229 switch (DestTy->getScalarTypeKind()) { 7230 case Type::STK_FloatingComplex: 7231 return CK_IntegralComplexToFloatingComplex; 7232 case Type::STK_IntegralComplex: 7233 return CK_IntegralComplexCast; 7234 case Type::STK_Integral: { 7235 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7236 if (Context.hasSameType(ET, DestTy)) 7237 return CK_IntegralComplexToReal; 7238 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7239 return CK_IntegralCast; 7240 } 7241 case Type::STK_Bool: 7242 return CK_IntegralComplexToBoolean; 7243 case Type::STK_Floating: 7244 Src = ImpCastExprToType(Src.get(), 7245 SrcTy->castAs<ComplexType>()->getElementType(), 7246 CK_IntegralComplexToReal); 7247 return CK_IntegralToFloating; 7248 case Type::STK_CPointer: 7249 case Type::STK_ObjCObjectPointer: 7250 case Type::STK_BlockPointer: 7251 llvm_unreachable("valid complex int->pointer cast?"); 7252 case Type::STK_MemberPointer: 7253 llvm_unreachable("member pointer type in C"); 7254 case Type::STK_FixedPoint: 7255 Diag(Src.get()->getExprLoc(), 7256 diag::err_unimplemented_conversion_with_fixed_point_type) 7257 << SrcTy; 7258 return CK_IntegralCast; 7259 } 7260 llvm_unreachable("Should have returned before this"); 7261 } 7262 7263 llvm_unreachable("Unhandled scalar cast"); 7264 } 7265 7266 static bool breakDownVectorType(QualType type, uint64_t &len, 7267 QualType &eltType) { 7268 // Vectors are simple. 7269 if (const VectorType *vecType = type->getAs<VectorType>()) { 7270 len = vecType->getNumElements(); 7271 eltType = vecType->getElementType(); 7272 assert(eltType->isScalarType()); 7273 return true; 7274 } 7275 7276 // We allow lax conversion to and from non-vector types, but only if 7277 // they're real types (i.e. non-complex, non-pointer scalar types). 7278 if (!type->isRealType()) return false; 7279 7280 len = 1; 7281 eltType = type; 7282 return true; 7283 } 7284 7285 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7286 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7287 /// allowed? 7288 /// 7289 /// This will also return false if the two given types do not make sense from 7290 /// the perspective of SVE bitcasts. 7291 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7292 assert(srcTy->isVectorType() || destTy->isVectorType()); 7293 7294 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7295 if (!FirstType->isSizelessBuiltinType()) 7296 return false; 7297 7298 const auto *VecTy = SecondType->getAs<VectorType>(); 7299 return VecTy && 7300 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7301 }; 7302 7303 return ValidScalableConversion(srcTy, destTy) || 7304 ValidScalableConversion(destTy, srcTy); 7305 } 7306 7307 /// Are the two types lax-compatible vector types? That is, given 7308 /// that one of them is a vector, do they have equal storage sizes, 7309 /// where the storage size is the number of elements times the element 7310 /// size? 7311 /// 7312 /// This will also return false if either of the types is neither a 7313 /// vector nor a real type. 7314 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7315 assert(destTy->isVectorType() || srcTy->isVectorType()); 7316 7317 // Disallow lax conversions between scalars and ExtVectors (these 7318 // conversions are allowed for other vector types because common headers 7319 // depend on them). Most scalar OP ExtVector cases are handled by the 7320 // splat path anyway, which does what we want (convert, not bitcast). 7321 // What this rules out for ExtVectors is crazy things like char4*float. 7322 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7323 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7324 7325 uint64_t srcLen, destLen; 7326 QualType srcEltTy, destEltTy; 7327 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7328 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7329 7330 // ASTContext::getTypeSize will return the size rounded up to a 7331 // power of 2, so instead of using that, we need to use the raw 7332 // element size multiplied by the element count. 7333 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7334 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7335 7336 return (srcLen * srcEltSize == destLen * destEltSize); 7337 } 7338 7339 /// Is this a legal conversion between two types, one of which is 7340 /// known to be a vector type? 7341 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7342 assert(destTy->isVectorType() || srcTy->isVectorType()); 7343 7344 switch (Context.getLangOpts().getLaxVectorConversions()) { 7345 case LangOptions::LaxVectorConversionKind::None: 7346 return false; 7347 7348 case LangOptions::LaxVectorConversionKind::Integer: 7349 if (!srcTy->isIntegralOrEnumerationType()) { 7350 auto *Vec = srcTy->getAs<VectorType>(); 7351 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7352 return false; 7353 } 7354 if (!destTy->isIntegralOrEnumerationType()) { 7355 auto *Vec = destTy->getAs<VectorType>(); 7356 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7357 return false; 7358 } 7359 // OK, integer (vector) -> integer (vector) bitcast. 7360 break; 7361 7362 case LangOptions::LaxVectorConversionKind::All: 7363 break; 7364 } 7365 7366 return areLaxCompatibleVectorTypes(srcTy, destTy); 7367 } 7368 7369 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7370 CastKind &Kind) { 7371 assert(VectorTy->isVectorType() && "Not a vector type!"); 7372 7373 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7374 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7375 return Diag(R.getBegin(), 7376 Ty->isVectorType() ? 7377 diag::err_invalid_conversion_between_vectors : 7378 diag::err_invalid_conversion_between_vector_and_integer) 7379 << VectorTy << Ty << R; 7380 } else 7381 return Diag(R.getBegin(), 7382 diag::err_invalid_conversion_between_vector_and_scalar) 7383 << VectorTy << Ty << R; 7384 7385 Kind = CK_BitCast; 7386 return false; 7387 } 7388 7389 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7390 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7391 7392 if (DestElemTy == SplattedExpr->getType()) 7393 return SplattedExpr; 7394 7395 assert(DestElemTy->isFloatingType() || 7396 DestElemTy->isIntegralOrEnumerationType()); 7397 7398 CastKind CK; 7399 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7400 // OpenCL requires that we convert `true` boolean expressions to -1, but 7401 // only when splatting vectors. 7402 if (DestElemTy->isFloatingType()) { 7403 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7404 // in two steps: boolean to signed integral, then to floating. 7405 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7406 CK_BooleanToSignedIntegral); 7407 SplattedExpr = CastExprRes.get(); 7408 CK = CK_IntegralToFloating; 7409 } else { 7410 CK = CK_BooleanToSignedIntegral; 7411 } 7412 } else { 7413 ExprResult CastExprRes = SplattedExpr; 7414 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7415 if (CastExprRes.isInvalid()) 7416 return ExprError(); 7417 SplattedExpr = CastExprRes.get(); 7418 } 7419 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7420 } 7421 7422 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7423 Expr *CastExpr, CastKind &Kind) { 7424 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7425 7426 QualType SrcTy = CastExpr->getType(); 7427 7428 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7429 // an ExtVectorType. 7430 // In OpenCL, casts between vectors of different types are not allowed. 7431 // (See OpenCL 6.2). 7432 if (SrcTy->isVectorType()) { 7433 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7434 (getLangOpts().OpenCL && 7435 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7436 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7437 << DestTy << SrcTy << R; 7438 return ExprError(); 7439 } 7440 Kind = CK_BitCast; 7441 return CastExpr; 7442 } 7443 7444 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7445 // conversion will take place first from scalar to elt type, and then 7446 // splat from elt type to vector. 7447 if (SrcTy->isPointerType()) 7448 return Diag(R.getBegin(), 7449 diag::err_invalid_conversion_between_vector_and_scalar) 7450 << DestTy << SrcTy << R; 7451 7452 Kind = CK_VectorSplat; 7453 return prepareVectorSplat(DestTy, CastExpr); 7454 } 7455 7456 ExprResult 7457 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7458 Declarator &D, ParsedType &Ty, 7459 SourceLocation RParenLoc, Expr *CastExpr) { 7460 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7461 "ActOnCastExpr(): missing type or expr"); 7462 7463 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7464 if (D.isInvalidType()) 7465 return ExprError(); 7466 7467 if (getLangOpts().CPlusPlus) { 7468 // Check that there are no default arguments (C++ only). 7469 CheckExtraCXXDefaultArguments(D); 7470 } else { 7471 // Make sure any TypoExprs have been dealt with. 7472 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7473 if (!Res.isUsable()) 7474 return ExprError(); 7475 CastExpr = Res.get(); 7476 } 7477 7478 checkUnusedDeclAttributes(D); 7479 7480 QualType castType = castTInfo->getType(); 7481 Ty = CreateParsedType(castType, castTInfo); 7482 7483 bool isVectorLiteral = false; 7484 7485 // Check for an altivec or OpenCL literal, 7486 // i.e. all the elements are integer constants. 7487 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7488 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7489 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7490 && castType->isVectorType() && (PE || PLE)) { 7491 if (PLE && PLE->getNumExprs() == 0) { 7492 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7493 return ExprError(); 7494 } 7495 if (PE || PLE->getNumExprs() == 1) { 7496 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7497 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7498 isVectorLiteral = true; 7499 } 7500 else 7501 isVectorLiteral = true; 7502 } 7503 7504 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7505 // then handle it as such. 7506 if (isVectorLiteral) 7507 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7508 7509 // If the Expr being casted is a ParenListExpr, handle it specially. 7510 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7511 // sequence of BinOp comma operators. 7512 if (isa<ParenListExpr>(CastExpr)) { 7513 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7514 if (Result.isInvalid()) return ExprError(); 7515 CastExpr = Result.get(); 7516 } 7517 7518 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7519 !getSourceManager().isInSystemMacro(LParenLoc)) 7520 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7521 7522 CheckTollFreeBridgeCast(castType, CastExpr); 7523 7524 CheckObjCBridgeRelatedCast(castType, CastExpr); 7525 7526 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7527 7528 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7529 } 7530 7531 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7532 SourceLocation RParenLoc, Expr *E, 7533 TypeSourceInfo *TInfo) { 7534 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7535 "Expected paren or paren list expression"); 7536 7537 Expr **exprs; 7538 unsigned numExprs; 7539 Expr *subExpr; 7540 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7541 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7542 LiteralLParenLoc = PE->getLParenLoc(); 7543 LiteralRParenLoc = PE->getRParenLoc(); 7544 exprs = PE->getExprs(); 7545 numExprs = PE->getNumExprs(); 7546 } else { // isa<ParenExpr> by assertion at function entrance 7547 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7548 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7549 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7550 exprs = &subExpr; 7551 numExprs = 1; 7552 } 7553 7554 QualType Ty = TInfo->getType(); 7555 assert(Ty->isVectorType() && "Expected vector type"); 7556 7557 SmallVector<Expr *, 8> initExprs; 7558 const VectorType *VTy = Ty->castAs<VectorType>(); 7559 unsigned numElems = VTy->getNumElements(); 7560 7561 // '(...)' form of vector initialization in AltiVec: the number of 7562 // initializers must be one or must match the size of the vector. 7563 // If a single value is specified in the initializer then it will be 7564 // replicated to all the components of the vector 7565 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7566 // The number of initializers must be one or must match the size of the 7567 // vector. If a single value is specified in the initializer then it will 7568 // be replicated to all the components of the vector 7569 if (numExprs == 1) { 7570 QualType ElemTy = VTy->getElementType(); 7571 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7572 if (Literal.isInvalid()) 7573 return ExprError(); 7574 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7575 PrepareScalarCast(Literal, ElemTy)); 7576 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7577 } 7578 else if (numExprs < numElems) { 7579 Diag(E->getExprLoc(), 7580 diag::err_incorrect_number_of_vector_initializers); 7581 return ExprError(); 7582 } 7583 else 7584 initExprs.append(exprs, exprs + numExprs); 7585 } 7586 else { 7587 // For OpenCL, when the number of initializers is a single value, 7588 // it will be replicated to all components of the vector. 7589 if (getLangOpts().OpenCL && 7590 VTy->getVectorKind() == VectorType::GenericVector && 7591 numExprs == 1) { 7592 QualType ElemTy = VTy->getElementType(); 7593 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7594 if (Literal.isInvalid()) 7595 return ExprError(); 7596 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7597 PrepareScalarCast(Literal, ElemTy)); 7598 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7599 } 7600 7601 initExprs.append(exprs, exprs + numExprs); 7602 } 7603 // FIXME: This means that pretty-printing the final AST will produce curly 7604 // braces instead of the original commas. 7605 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7606 initExprs, LiteralRParenLoc); 7607 initE->setType(Ty); 7608 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7609 } 7610 7611 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7612 /// the ParenListExpr into a sequence of comma binary operators. 7613 ExprResult 7614 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7615 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7616 if (!E) 7617 return OrigExpr; 7618 7619 ExprResult Result(E->getExpr(0)); 7620 7621 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7622 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7623 E->getExpr(i)); 7624 7625 if (Result.isInvalid()) return ExprError(); 7626 7627 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7628 } 7629 7630 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7631 SourceLocation R, 7632 MultiExprArg Val) { 7633 return ParenListExpr::Create(Context, L, Val, R); 7634 } 7635 7636 /// Emit a specialized diagnostic when one expression is a null pointer 7637 /// constant and the other is not a pointer. Returns true if a diagnostic is 7638 /// emitted. 7639 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7640 SourceLocation QuestionLoc) { 7641 Expr *NullExpr = LHSExpr; 7642 Expr *NonPointerExpr = RHSExpr; 7643 Expr::NullPointerConstantKind NullKind = 7644 NullExpr->isNullPointerConstant(Context, 7645 Expr::NPC_ValueDependentIsNotNull); 7646 7647 if (NullKind == Expr::NPCK_NotNull) { 7648 NullExpr = RHSExpr; 7649 NonPointerExpr = LHSExpr; 7650 NullKind = 7651 NullExpr->isNullPointerConstant(Context, 7652 Expr::NPC_ValueDependentIsNotNull); 7653 } 7654 7655 if (NullKind == Expr::NPCK_NotNull) 7656 return false; 7657 7658 if (NullKind == Expr::NPCK_ZeroExpression) 7659 return false; 7660 7661 if (NullKind == Expr::NPCK_ZeroLiteral) { 7662 // In this case, check to make sure that we got here from a "NULL" 7663 // string in the source code. 7664 NullExpr = NullExpr->IgnoreParenImpCasts(); 7665 SourceLocation loc = NullExpr->getExprLoc(); 7666 if (!findMacroSpelling(loc, "NULL")) 7667 return false; 7668 } 7669 7670 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7671 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7672 << NonPointerExpr->getType() << DiagType 7673 << NonPointerExpr->getSourceRange(); 7674 return true; 7675 } 7676 7677 /// Return false if the condition expression is valid, true otherwise. 7678 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7679 QualType CondTy = Cond->getType(); 7680 7681 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7682 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7683 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7684 << CondTy << Cond->getSourceRange(); 7685 return true; 7686 } 7687 7688 // C99 6.5.15p2 7689 if (CondTy->isScalarType()) return false; 7690 7691 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7692 << CondTy << Cond->getSourceRange(); 7693 return true; 7694 } 7695 7696 /// Handle when one or both operands are void type. 7697 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7698 ExprResult &RHS) { 7699 Expr *LHSExpr = LHS.get(); 7700 Expr *RHSExpr = RHS.get(); 7701 7702 if (!LHSExpr->getType()->isVoidType()) 7703 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7704 << RHSExpr->getSourceRange(); 7705 if (!RHSExpr->getType()->isVoidType()) 7706 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7707 << LHSExpr->getSourceRange(); 7708 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7709 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7710 return S.Context.VoidTy; 7711 } 7712 7713 /// Return false if the NullExpr can be promoted to PointerTy, 7714 /// true otherwise. 7715 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7716 QualType PointerTy) { 7717 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7718 !NullExpr.get()->isNullPointerConstant(S.Context, 7719 Expr::NPC_ValueDependentIsNull)) 7720 return true; 7721 7722 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7723 return false; 7724 } 7725 7726 /// Checks compatibility between two pointers and return the resulting 7727 /// type. 7728 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7729 ExprResult &RHS, 7730 SourceLocation Loc) { 7731 QualType LHSTy = LHS.get()->getType(); 7732 QualType RHSTy = RHS.get()->getType(); 7733 7734 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7735 // Two identical pointers types are always compatible. 7736 return LHSTy; 7737 } 7738 7739 QualType lhptee, rhptee; 7740 7741 // Get the pointee types. 7742 bool IsBlockPointer = false; 7743 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7744 lhptee = LHSBTy->getPointeeType(); 7745 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7746 IsBlockPointer = true; 7747 } else { 7748 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7749 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7750 } 7751 7752 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7753 // differently qualified versions of compatible types, the result type is 7754 // a pointer to an appropriately qualified version of the composite 7755 // type. 7756 7757 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7758 // clause doesn't make sense for our extensions. E.g. address space 2 should 7759 // be incompatible with address space 3: they may live on different devices or 7760 // anything. 7761 Qualifiers lhQual = lhptee.getQualifiers(); 7762 Qualifiers rhQual = rhptee.getQualifiers(); 7763 7764 LangAS ResultAddrSpace = LangAS::Default; 7765 LangAS LAddrSpace = lhQual.getAddressSpace(); 7766 LangAS RAddrSpace = rhQual.getAddressSpace(); 7767 7768 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7769 // spaces is disallowed. 7770 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7771 ResultAddrSpace = LAddrSpace; 7772 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7773 ResultAddrSpace = RAddrSpace; 7774 else { 7775 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7776 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7777 << RHS.get()->getSourceRange(); 7778 return QualType(); 7779 } 7780 7781 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7782 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7783 lhQual.removeCVRQualifiers(); 7784 rhQual.removeCVRQualifiers(); 7785 7786 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7787 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7788 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7789 // qual types are compatible iff 7790 // * corresponded types are compatible 7791 // * CVR qualifiers are equal 7792 // * address spaces are equal 7793 // Thus for conditional operator we merge CVR and address space unqualified 7794 // pointees and if there is a composite type we return a pointer to it with 7795 // merged qualifiers. 7796 LHSCastKind = 7797 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7798 RHSCastKind = 7799 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7800 lhQual.removeAddressSpace(); 7801 rhQual.removeAddressSpace(); 7802 7803 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7804 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7805 7806 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7807 7808 if (CompositeTy.isNull()) { 7809 // In this situation, we assume void* type. No especially good 7810 // reason, but this is what gcc does, and we do have to pick 7811 // to get a consistent AST. 7812 QualType incompatTy; 7813 incompatTy = S.Context.getPointerType( 7814 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7815 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7816 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7817 7818 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7819 // for casts between types with incompatible address space qualifiers. 7820 // For the following code the compiler produces casts between global and 7821 // local address spaces of the corresponded innermost pointees: 7822 // local int *global *a; 7823 // global int *global *b; 7824 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7825 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7826 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7827 << RHS.get()->getSourceRange(); 7828 7829 return incompatTy; 7830 } 7831 7832 // The pointer types are compatible. 7833 // In case of OpenCL ResultTy should have the address space qualifier 7834 // which is a superset of address spaces of both the 2nd and the 3rd 7835 // operands of the conditional operator. 7836 QualType ResultTy = [&, ResultAddrSpace]() { 7837 if (S.getLangOpts().OpenCL) { 7838 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7839 CompositeQuals.setAddressSpace(ResultAddrSpace); 7840 return S.Context 7841 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7842 .withCVRQualifiers(MergedCVRQual); 7843 } 7844 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7845 }(); 7846 if (IsBlockPointer) 7847 ResultTy = S.Context.getBlockPointerType(ResultTy); 7848 else 7849 ResultTy = S.Context.getPointerType(ResultTy); 7850 7851 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7852 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7853 return ResultTy; 7854 } 7855 7856 /// Return the resulting type when the operands are both block pointers. 7857 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7858 ExprResult &LHS, 7859 ExprResult &RHS, 7860 SourceLocation Loc) { 7861 QualType LHSTy = LHS.get()->getType(); 7862 QualType RHSTy = RHS.get()->getType(); 7863 7864 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7865 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7866 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7867 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7868 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7869 return destType; 7870 } 7871 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7872 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7873 << RHS.get()->getSourceRange(); 7874 return QualType(); 7875 } 7876 7877 // We have 2 block pointer types. 7878 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7879 } 7880 7881 /// Return the resulting type when the operands are both pointers. 7882 static QualType 7883 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7884 ExprResult &RHS, 7885 SourceLocation Loc) { 7886 // get the pointer types 7887 QualType LHSTy = LHS.get()->getType(); 7888 QualType RHSTy = RHS.get()->getType(); 7889 7890 // get the "pointed to" types 7891 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7892 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7893 7894 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7895 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7896 // Figure out necessary qualifiers (C99 6.5.15p6) 7897 QualType destPointee 7898 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7899 QualType destType = S.Context.getPointerType(destPointee); 7900 // Add qualifiers if necessary. 7901 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7902 // Promote to void*. 7903 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7904 return destType; 7905 } 7906 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7907 QualType destPointee 7908 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7909 QualType destType = S.Context.getPointerType(destPointee); 7910 // Add qualifiers if necessary. 7911 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7912 // Promote to void*. 7913 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7914 return destType; 7915 } 7916 7917 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7918 } 7919 7920 /// Return false if the first expression is not an integer and the second 7921 /// expression is not a pointer, true otherwise. 7922 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7923 Expr* PointerExpr, SourceLocation Loc, 7924 bool IsIntFirstExpr) { 7925 if (!PointerExpr->getType()->isPointerType() || 7926 !Int.get()->getType()->isIntegerType()) 7927 return false; 7928 7929 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7930 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7931 7932 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7933 << Expr1->getType() << Expr2->getType() 7934 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7935 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7936 CK_IntegralToPointer); 7937 return true; 7938 } 7939 7940 /// Simple conversion between integer and floating point types. 7941 /// 7942 /// Used when handling the OpenCL conditional operator where the 7943 /// condition is a vector while the other operands are scalar. 7944 /// 7945 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7946 /// types are either integer or floating type. Between the two 7947 /// operands, the type with the higher rank is defined as the "result 7948 /// type". The other operand needs to be promoted to the same type. No 7949 /// other type promotion is allowed. We cannot use 7950 /// UsualArithmeticConversions() for this purpose, since it always 7951 /// promotes promotable types. 7952 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7953 ExprResult &RHS, 7954 SourceLocation QuestionLoc) { 7955 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7956 if (LHS.isInvalid()) 7957 return QualType(); 7958 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7959 if (RHS.isInvalid()) 7960 return QualType(); 7961 7962 // For conversion purposes, we ignore any qualifiers. 7963 // For example, "const float" and "float" are equivalent. 7964 QualType LHSType = 7965 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7966 QualType RHSType = 7967 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7968 7969 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7970 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7971 << LHSType << LHS.get()->getSourceRange(); 7972 return QualType(); 7973 } 7974 7975 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7976 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7977 << RHSType << RHS.get()->getSourceRange(); 7978 return QualType(); 7979 } 7980 7981 // If both types are identical, no conversion is needed. 7982 if (LHSType == RHSType) 7983 return LHSType; 7984 7985 // Now handle "real" floating types (i.e. float, double, long double). 7986 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7987 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7988 /*IsCompAssign = */ false); 7989 7990 // Finally, we have two differing integer types. 7991 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7992 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7993 } 7994 7995 /// Convert scalar operands to a vector that matches the 7996 /// condition in length. 7997 /// 7998 /// Used when handling the OpenCL conditional operator where the 7999 /// condition is a vector while the other operands are scalar. 8000 /// 8001 /// We first compute the "result type" for the scalar operands 8002 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8003 /// into a vector of that type where the length matches the condition 8004 /// vector type. s6.11.6 requires that the element types of the result 8005 /// and the condition must have the same number of bits. 8006 static QualType 8007 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8008 QualType CondTy, SourceLocation QuestionLoc) { 8009 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8010 if (ResTy.isNull()) return QualType(); 8011 8012 const VectorType *CV = CondTy->getAs<VectorType>(); 8013 assert(CV); 8014 8015 // Determine the vector result type 8016 unsigned NumElements = CV->getNumElements(); 8017 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8018 8019 // Ensure that all types have the same number of bits 8020 if (S.Context.getTypeSize(CV->getElementType()) 8021 != S.Context.getTypeSize(ResTy)) { 8022 // Since VectorTy is created internally, it does not pretty print 8023 // with an OpenCL name. Instead, we just print a description. 8024 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8025 SmallString<64> Str; 8026 llvm::raw_svector_ostream OS(Str); 8027 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8028 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8029 << CondTy << OS.str(); 8030 return QualType(); 8031 } 8032 8033 // Convert operands to the vector result type 8034 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8035 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8036 8037 return VectorTy; 8038 } 8039 8040 /// Return false if this is a valid OpenCL condition vector 8041 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8042 SourceLocation QuestionLoc) { 8043 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8044 // integral type. 8045 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8046 assert(CondTy); 8047 QualType EleTy = CondTy->getElementType(); 8048 if (EleTy->isIntegerType()) return false; 8049 8050 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8051 << Cond->getType() << Cond->getSourceRange(); 8052 return true; 8053 } 8054 8055 /// Return false if the vector condition type and the vector 8056 /// result type are compatible. 8057 /// 8058 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8059 /// number of elements, and their element types have the same number 8060 /// of bits. 8061 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8062 SourceLocation QuestionLoc) { 8063 const VectorType *CV = CondTy->getAs<VectorType>(); 8064 const VectorType *RV = VecResTy->getAs<VectorType>(); 8065 assert(CV && RV); 8066 8067 if (CV->getNumElements() != RV->getNumElements()) { 8068 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8069 << CondTy << VecResTy; 8070 return true; 8071 } 8072 8073 QualType CVE = CV->getElementType(); 8074 QualType RVE = RV->getElementType(); 8075 8076 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8077 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8078 << CondTy << VecResTy; 8079 return true; 8080 } 8081 8082 return false; 8083 } 8084 8085 /// Return the resulting type for the conditional operator in 8086 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8087 /// s6.3.i) when the condition is a vector type. 8088 static QualType 8089 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8090 ExprResult &LHS, ExprResult &RHS, 8091 SourceLocation QuestionLoc) { 8092 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8093 if (Cond.isInvalid()) 8094 return QualType(); 8095 QualType CondTy = Cond.get()->getType(); 8096 8097 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8098 return QualType(); 8099 8100 // If either operand is a vector then find the vector type of the 8101 // result as specified in OpenCL v1.1 s6.3.i. 8102 if (LHS.get()->getType()->isVectorType() || 8103 RHS.get()->getType()->isVectorType()) { 8104 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8105 /*isCompAssign*/false, 8106 /*AllowBothBool*/true, 8107 /*AllowBoolConversions*/false); 8108 if (VecResTy.isNull()) return QualType(); 8109 // The result type must match the condition type as specified in 8110 // OpenCL v1.1 s6.11.6. 8111 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8112 return QualType(); 8113 return VecResTy; 8114 } 8115 8116 // Both operands are scalar. 8117 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8118 } 8119 8120 /// Return true if the Expr is block type 8121 static bool checkBlockType(Sema &S, const Expr *E) { 8122 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8123 QualType Ty = CE->getCallee()->getType(); 8124 if (Ty->isBlockPointerType()) { 8125 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8126 return true; 8127 } 8128 } 8129 return false; 8130 } 8131 8132 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8133 /// In that case, LHS = cond. 8134 /// C99 6.5.15 8135 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8136 ExprResult &RHS, ExprValueKind &VK, 8137 ExprObjectKind &OK, 8138 SourceLocation QuestionLoc) { 8139 8140 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8141 if (!LHSResult.isUsable()) return QualType(); 8142 LHS = LHSResult; 8143 8144 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8145 if (!RHSResult.isUsable()) return QualType(); 8146 RHS = RHSResult; 8147 8148 // C++ is sufficiently different to merit its own checker. 8149 if (getLangOpts().CPlusPlus) 8150 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8151 8152 VK = VK_RValue; 8153 OK = OK_Ordinary; 8154 8155 if (Context.isDependenceAllowed() && 8156 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8157 RHS.get()->isTypeDependent())) { 8158 assert(!getLangOpts().CPlusPlus); 8159 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8160 RHS.get()->containsErrors()) && 8161 "should only occur in error-recovery path."); 8162 return Context.DependentTy; 8163 } 8164 8165 // The OpenCL operator with a vector condition is sufficiently 8166 // different to merit its own checker. 8167 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8168 Cond.get()->getType()->isExtVectorType()) 8169 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8170 8171 // First, check the condition. 8172 Cond = UsualUnaryConversions(Cond.get()); 8173 if (Cond.isInvalid()) 8174 return QualType(); 8175 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8176 return QualType(); 8177 8178 // Now check the two expressions. 8179 if (LHS.get()->getType()->isVectorType() || 8180 RHS.get()->getType()->isVectorType()) 8181 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8182 /*AllowBothBool*/true, 8183 /*AllowBoolConversions*/false); 8184 8185 QualType ResTy = 8186 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8187 if (LHS.isInvalid() || RHS.isInvalid()) 8188 return QualType(); 8189 8190 QualType LHSTy = LHS.get()->getType(); 8191 QualType RHSTy = RHS.get()->getType(); 8192 8193 // Diagnose attempts to convert between __float128 and long double where 8194 // such conversions currently can't be handled. 8195 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8196 Diag(QuestionLoc, 8197 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8198 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8199 return QualType(); 8200 } 8201 8202 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8203 // selection operator (?:). 8204 if (getLangOpts().OpenCL && 8205 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8206 return QualType(); 8207 } 8208 8209 // If both operands have arithmetic type, do the usual arithmetic conversions 8210 // to find a common type: C99 6.5.15p3,5. 8211 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8212 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8213 // different sizes, or between ExtInts and other types. 8214 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8215 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8216 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8217 << RHS.get()->getSourceRange(); 8218 return QualType(); 8219 } 8220 8221 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8222 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8223 8224 return ResTy; 8225 } 8226 8227 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8228 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8229 return LHSTy; 8230 } 8231 8232 // If both operands are the same structure or union type, the result is that 8233 // type. 8234 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8235 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8236 if (LHSRT->getDecl() == RHSRT->getDecl()) 8237 // "If both the operands have structure or union type, the result has 8238 // that type." This implies that CV qualifiers are dropped. 8239 return LHSTy.getUnqualifiedType(); 8240 // FIXME: Type of conditional expression must be complete in C mode. 8241 } 8242 8243 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8244 // The following || allows only one side to be void (a GCC-ism). 8245 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8246 return checkConditionalVoidType(*this, LHS, RHS); 8247 } 8248 8249 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8250 // the type of the other operand." 8251 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8252 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8253 8254 // All objective-c pointer type analysis is done here. 8255 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8256 QuestionLoc); 8257 if (LHS.isInvalid() || RHS.isInvalid()) 8258 return QualType(); 8259 if (!compositeType.isNull()) 8260 return compositeType; 8261 8262 8263 // Handle block pointer types. 8264 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8265 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8266 QuestionLoc); 8267 8268 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8269 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8270 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8271 QuestionLoc); 8272 8273 // GCC compatibility: soften pointer/integer mismatch. Note that 8274 // null pointers have been filtered out by this point. 8275 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8276 /*IsIntFirstExpr=*/true)) 8277 return RHSTy; 8278 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8279 /*IsIntFirstExpr=*/false)) 8280 return LHSTy; 8281 8282 // Allow ?: operations in which both operands have the same 8283 // built-in sizeless type. 8284 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8285 return LHSTy; 8286 8287 // Emit a better diagnostic if one of the expressions is a null pointer 8288 // constant and the other is not a pointer type. In this case, the user most 8289 // likely forgot to take the address of the other expression. 8290 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8291 return QualType(); 8292 8293 // Otherwise, the operands are not compatible. 8294 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8295 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8296 << RHS.get()->getSourceRange(); 8297 return QualType(); 8298 } 8299 8300 /// FindCompositeObjCPointerType - Helper method to find composite type of 8301 /// two objective-c pointer types of the two input expressions. 8302 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8303 SourceLocation QuestionLoc) { 8304 QualType LHSTy = LHS.get()->getType(); 8305 QualType RHSTy = RHS.get()->getType(); 8306 8307 // Handle things like Class and struct objc_class*. Here we case the result 8308 // to the pseudo-builtin, because that will be implicitly cast back to the 8309 // redefinition type if an attempt is made to access its fields. 8310 if (LHSTy->isObjCClassType() && 8311 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8312 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8313 return LHSTy; 8314 } 8315 if (RHSTy->isObjCClassType() && 8316 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8317 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8318 return RHSTy; 8319 } 8320 // And the same for struct objc_object* / id 8321 if (LHSTy->isObjCIdType() && 8322 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8323 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8324 return LHSTy; 8325 } 8326 if (RHSTy->isObjCIdType() && 8327 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8328 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8329 return RHSTy; 8330 } 8331 // And the same for struct objc_selector* / SEL 8332 if (Context.isObjCSelType(LHSTy) && 8333 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8334 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8335 return LHSTy; 8336 } 8337 if (Context.isObjCSelType(RHSTy) && 8338 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8339 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8340 return RHSTy; 8341 } 8342 // Check constraints for Objective-C object pointers types. 8343 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8344 8345 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8346 // Two identical object pointer types are always compatible. 8347 return LHSTy; 8348 } 8349 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8350 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8351 QualType compositeType = LHSTy; 8352 8353 // If both operands are interfaces and either operand can be 8354 // assigned to the other, use that type as the composite 8355 // type. This allows 8356 // xxx ? (A*) a : (B*) b 8357 // where B is a subclass of A. 8358 // 8359 // Additionally, as for assignment, if either type is 'id' 8360 // allow silent coercion. Finally, if the types are 8361 // incompatible then make sure to use 'id' as the composite 8362 // type so the result is acceptable for sending messages to. 8363 8364 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8365 // It could return the composite type. 8366 if (!(compositeType = 8367 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8368 // Nothing more to do. 8369 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8370 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8371 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8372 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8373 } else if ((LHSOPT->isObjCQualifiedIdType() || 8374 RHSOPT->isObjCQualifiedIdType()) && 8375 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8376 true)) { 8377 // Need to handle "id<xx>" explicitly. 8378 // GCC allows qualified id and any Objective-C type to devolve to 8379 // id. Currently localizing to here until clear this should be 8380 // part of ObjCQualifiedIdTypesAreCompatible. 8381 compositeType = Context.getObjCIdType(); 8382 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8383 compositeType = Context.getObjCIdType(); 8384 } else { 8385 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8386 << LHSTy << RHSTy 8387 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8388 QualType incompatTy = Context.getObjCIdType(); 8389 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8390 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8391 return incompatTy; 8392 } 8393 // The object pointer types are compatible. 8394 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8395 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8396 return compositeType; 8397 } 8398 // Check Objective-C object pointer types and 'void *' 8399 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 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<PointerType>()->getPointeeType(); 8409 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8410 QualType destPointee 8411 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8412 QualType destType = Context.getPointerType(destPointee); 8413 // Add qualifiers if necessary. 8414 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8415 // Promote to void*. 8416 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8417 return destType; 8418 } 8419 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8420 if (getLangOpts().ObjCAutoRefCount) { 8421 // ARC forbids the implicit conversion of object pointers to 'void *', 8422 // so these types are not compatible. 8423 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8424 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8425 LHS = RHS = true; 8426 return QualType(); 8427 } 8428 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8429 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8430 QualType destPointee 8431 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8432 QualType destType = Context.getPointerType(destPointee); 8433 // Add qualifiers if necessary. 8434 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8435 // Promote to void*. 8436 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8437 return destType; 8438 } 8439 return QualType(); 8440 } 8441 8442 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8443 /// ParenRange in parentheses. 8444 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8445 const PartialDiagnostic &Note, 8446 SourceRange ParenRange) { 8447 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8448 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8449 EndLoc.isValid()) { 8450 Self.Diag(Loc, Note) 8451 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8452 << FixItHint::CreateInsertion(EndLoc, ")"); 8453 } else { 8454 // We can't display the parentheses, so just show the bare note. 8455 Self.Diag(Loc, Note) << ParenRange; 8456 } 8457 } 8458 8459 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8460 return BinaryOperator::isAdditiveOp(Opc) || 8461 BinaryOperator::isMultiplicativeOp(Opc) || 8462 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8463 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8464 // not any of the logical operators. Bitwise-xor is commonly used as a 8465 // logical-xor because there is no logical-xor operator. The logical 8466 // operators, including uses of xor, have a high false positive rate for 8467 // precedence warnings. 8468 } 8469 8470 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8471 /// expression, either using a built-in or overloaded operator, 8472 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8473 /// expression. 8474 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8475 Expr **RHSExprs) { 8476 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8477 E = E->IgnoreImpCasts(); 8478 E = E->IgnoreConversionOperatorSingleStep(); 8479 E = E->IgnoreImpCasts(); 8480 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8481 E = MTE->getSubExpr(); 8482 E = E->IgnoreImpCasts(); 8483 } 8484 8485 // Built-in binary operator. 8486 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8487 if (IsArithmeticOp(OP->getOpcode())) { 8488 *Opcode = OP->getOpcode(); 8489 *RHSExprs = OP->getRHS(); 8490 return true; 8491 } 8492 } 8493 8494 // Overloaded operator. 8495 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8496 if (Call->getNumArgs() != 2) 8497 return false; 8498 8499 // Make sure this is really a binary operator that is safe to pass into 8500 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8501 OverloadedOperatorKind OO = Call->getOperator(); 8502 if (OO < OO_Plus || OO > OO_Arrow || 8503 OO == OO_PlusPlus || OO == OO_MinusMinus) 8504 return false; 8505 8506 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8507 if (IsArithmeticOp(OpKind)) { 8508 *Opcode = OpKind; 8509 *RHSExprs = Call->getArg(1); 8510 return true; 8511 } 8512 } 8513 8514 return false; 8515 } 8516 8517 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8518 /// or is a logical expression such as (x==y) which has int type, but is 8519 /// commonly interpreted as boolean. 8520 static bool ExprLooksBoolean(Expr *E) { 8521 E = E->IgnoreParenImpCasts(); 8522 8523 if (E->getType()->isBooleanType()) 8524 return true; 8525 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8526 return OP->isComparisonOp() || OP->isLogicalOp(); 8527 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8528 return OP->getOpcode() == UO_LNot; 8529 if (E->getType()->isPointerType()) 8530 return true; 8531 // FIXME: What about overloaded operator calls returning "unspecified boolean 8532 // type"s (commonly pointer-to-members)? 8533 8534 return false; 8535 } 8536 8537 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8538 /// and binary operator are mixed in a way that suggests the programmer assumed 8539 /// the conditional operator has higher precedence, for example: 8540 /// "int x = a + someBinaryCondition ? 1 : 2". 8541 static void DiagnoseConditionalPrecedence(Sema &Self, 8542 SourceLocation OpLoc, 8543 Expr *Condition, 8544 Expr *LHSExpr, 8545 Expr *RHSExpr) { 8546 BinaryOperatorKind CondOpcode; 8547 Expr *CondRHS; 8548 8549 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8550 return; 8551 if (!ExprLooksBoolean(CondRHS)) 8552 return; 8553 8554 // The condition is an arithmetic binary expression, with a right- 8555 // hand side that looks boolean, so warn. 8556 8557 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8558 ? diag::warn_precedence_bitwise_conditional 8559 : diag::warn_precedence_conditional; 8560 8561 Self.Diag(OpLoc, DiagID) 8562 << Condition->getSourceRange() 8563 << BinaryOperator::getOpcodeStr(CondOpcode); 8564 8565 SuggestParentheses( 8566 Self, OpLoc, 8567 Self.PDiag(diag::note_precedence_silence) 8568 << BinaryOperator::getOpcodeStr(CondOpcode), 8569 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8570 8571 SuggestParentheses(Self, OpLoc, 8572 Self.PDiag(diag::note_precedence_conditional_first), 8573 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8574 } 8575 8576 /// Compute the nullability of a conditional expression. 8577 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8578 QualType LHSTy, QualType RHSTy, 8579 ASTContext &Ctx) { 8580 if (!ResTy->isAnyPointerType()) 8581 return ResTy; 8582 8583 auto GetNullability = [&Ctx](QualType Ty) { 8584 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8585 if (Kind) { 8586 // For our purposes, treat _Nullable_result as _Nullable. 8587 if (*Kind == NullabilityKind::NullableResult) 8588 return NullabilityKind::Nullable; 8589 return *Kind; 8590 } 8591 return NullabilityKind::Unspecified; 8592 }; 8593 8594 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8595 NullabilityKind MergedKind; 8596 8597 // Compute nullability of a binary conditional expression. 8598 if (IsBin) { 8599 if (LHSKind == NullabilityKind::NonNull) 8600 MergedKind = NullabilityKind::NonNull; 8601 else 8602 MergedKind = RHSKind; 8603 // Compute nullability of a normal conditional expression. 8604 } else { 8605 if (LHSKind == NullabilityKind::Nullable || 8606 RHSKind == NullabilityKind::Nullable) 8607 MergedKind = NullabilityKind::Nullable; 8608 else if (LHSKind == NullabilityKind::NonNull) 8609 MergedKind = RHSKind; 8610 else if (RHSKind == NullabilityKind::NonNull) 8611 MergedKind = LHSKind; 8612 else 8613 MergedKind = NullabilityKind::Unspecified; 8614 } 8615 8616 // Return if ResTy already has the correct nullability. 8617 if (GetNullability(ResTy) == MergedKind) 8618 return ResTy; 8619 8620 // Strip all nullability from ResTy. 8621 while (ResTy->getNullability(Ctx)) 8622 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8623 8624 // Create a new AttributedType with the new nullability kind. 8625 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8626 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8627 } 8628 8629 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8630 /// in the case of a the GNU conditional expr extension. 8631 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8632 SourceLocation ColonLoc, 8633 Expr *CondExpr, Expr *LHSExpr, 8634 Expr *RHSExpr) { 8635 if (!Context.isDependenceAllowed()) { 8636 // C cannot handle TypoExpr nodes in the condition because it 8637 // doesn't handle dependent types properly, so make sure any TypoExprs have 8638 // been dealt with before checking the operands. 8639 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8640 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8641 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8642 8643 if (!CondResult.isUsable()) 8644 return ExprError(); 8645 8646 if (LHSExpr) { 8647 if (!LHSResult.isUsable()) 8648 return ExprError(); 8649 } 8650 8651 if (!RHSResult.isUsable()) 8652 return ExprError(); 8653 8654 CondExpr = CondResult.get(); 8655 LHSExpr = LHSResult.get(); 8656 RHSExpr = RHSResult.get(); 8657 } 8658 8659 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8660 // was the condition. 8661 OpaqueValueExpr *opaqueValue = nullptr; 8662 Expr *commonExpr = nullptr; 8663 if (!LHSExpr) { 8664 commonExpr = CondExpr; 8665 // Lower out placeholder types first. This is important so that we don't 8666 // try to capture a placeholder. This happens in few cases in C++; such 8667 // as Objective-C++'s dictionary subscripting syntax. 8668 if (commonExpr->hasPlaceholderType()) { 8669 ExprResult result = CheckPlaceholderExpr(commonExpr); 8670 if (!result.isUsable()) return ExprError(); 8671 commonExpr = result.get(); 8672 } 8673 // We usually want to apply unary conversions *before* saving, except 8674 // in the special case of a C++ l-value conditional. 8675 if (!(getLangOpts().CPlusPlus 8676 && !commonExpr->isTypeDependent() 8677 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8678 && commonExpr->isGLValue() 8679 && commonExpr->isOrdinaryOrBitFieldObject() 8680 && RHSExpr->isOrdinaryOrBitFieldObject() 8681 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8682 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8683 if (commonRes.isInvalid()) 8684 return ExprError(); 8685 commonExpr = commonRes.get(); 8686 } 8687 8688 // If the common expression is a class or array prvalue, materialize it 8689 // so that we can safely refer to it multiple times. 8690 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8691 commonExpr->getType()->isArrayType())) { 8692 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8693 if (MatExpr.isInvalid()) 8694 return ExprError(); 8695 commonExpr = MatExpr.get(); 8696 } 8697 8698 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8699 commonExpr->getType(), 8700 commonExpr->getValueKind(), 8701 commonExpr->getObjectKind(), 8702 commonExpr); 8703 LHSExpr = CondExpr = opaqueValue; 8704 } 8705 8706 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8707 ExprValueKind VK = VK_RValue; 8708 ExprObjectKind OK = OK_Ordinary; 8709 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8710 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8711 VK, OK, QuestionLoc); 8712 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8713 RHS.isInvalid()) 8714 return ExprError(); 8715 8716 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8717 RHS.get()); 8718 8719 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8720 8721 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8722 Context); 8723 8724 if (!commonExpr) 8725 return new (Context) 8726 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8727 RHS.get(), result, VK, OK); 8728 8729 return new (Context) BinaryConditionalOperator( 8730 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8731 ColonLoc, result, VK, OK); 8732 } 8733 8734 // Check if we have a conversion between incompatible cmse function pointer 8735 // types, that is, a conversion between a function pointer with the 8736 // cmse_nonsecure_call attribute and one without. 8737 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8738 QualType ToType) { 8739 if (const auto *ToFn = 8740 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8741 if (const auto *FromFn = 8742 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8743 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8744 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8745 8746 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8747 } 8748 } 8749 return false; 8750 } 8751 8752 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8753 // being closely modeled after the C99 spec:-). The odd characteristic of this 8754 // routine is it effectively iqnores the qualifiers on the top level pointee. 8755 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8756 // FIXME: add a couple examples in this comment. 8757 static Sema::AssignConvertType 8758 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8759 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8760 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8761 8762 // get the "pointed to" type (ignoring qualifiers at the top level) 8763 const Type *lhptee, *rhptee; 8764 Qualifiers lhq, rhq; 8765 std::tie(lhptee, lhq) = 8766 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8767 std::tie(rhptee, rhq) = 8768 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8769 8770 Sema::AssignConvertType ConvTy = Sema::Compatible; 8771 8772 // C99 6.5.16.1p1: This following citation is common to constraints 8773 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8774 // qualifiers of the type *pointed to* by the right; 8775 8776 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8777 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8778 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8779 // Ignore lifetime for further calculation. 8780 lhq.removeObjCLifetime(); 8781 rhq.removeObjCLifetime(); 8782 } 8783 8784 if (!lhq.compatiblyIncludes(rhq)) { 8785 // Treat address-space mismatches as fatal. 8786 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8787 return Sema::IncompatiblePointerDiscardsQualifiers; 8788 8789 // It's okay to add or remove GC or lifetime qualifiers when converting to 8790 // and from void*. 8791 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8792 .compatiblyIncludes( 8793 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8794 && (lhptee->isVoidType() || rhptee->isVoidType())) 8795 ; // keep old 8796 8797 // Treat lifetime mismatches as fatal. 8798 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8799 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8800 8801 // For GCC/MS compatibility, other qualifier mismatches are treated 8802 // as still compatible in C. 8803 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8804 } 8805 8806 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8807 // incomplete type and the other is a pointer to a qualified or unqualified 8808 // version of void... 8809 if (lhptee->isVoidType()) { 8810 if (rhptee->isIncompleteOrObjectType()) 8811 return ConvTy; 8812 8813 // As an extension, we allow cast to/from void* to function pointer. 8814 assert(rhptee->isFunctionType()); 8815 return Sema::FunctionVoidPointer; 8816 } 8817 8818 if (rhptee->isVoidType()) { 8819 if (lhptee->isIncompleteOrObjectType()) 8820 return ConvTy; 8821 8822 // As an extension, we allow cast to/from void* to function pointer. 8823 assert(lhptee->isFunctionType()); 8824 return Sema::FunctionVoidPointer; 8825 } 8826 8827 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8828 // unqualified versions of compatible types, ... 8829 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8830 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8831 // Check if the pointee types are compatible ignoring the sign. 8832 // We explicitly check for char so that we catch "char" vs 8833 // "unsigned char" on systems where "char" is unsigned. 8834 if (lhptee->isCharType()) 8835 ltrans = S.Context.UnsignedCharTy; 8836 else if (lhptee->hasSignedIntegerRepresentation()) 8837 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8838 8839 if (rhptee->isCharType()) 8840 rtrans = S.Context.UnsignedCharTy; 8841 else if (rhptee->hasSignedIntegerRepresentation()) 8842 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8843 8844 if (ltrans == rtrans) { 8845 // Types are compatible ignoring the sign. Qualifier incompatibility 8846 // takes priority over sign incompatibility because the sign 8847 // warning can be disabled. 8848 if (ConvTy != Sema::Compatible) 8849 return ConvTy; 8850 8851 return Sema::IncompatiblePointerSign; 8852 } 8853 8854 // If we are a multi-level pointer, it's possible that our issue is simply 8855 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8856 // the eventual target type is the same and the pointers have the same 8857 // level of indirection, this must be the issue. 8858 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8859 do { 8860 std::tie(lhptee, lhq) = 8861 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8862 std::tie(rhptee, rhq) = 8863 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8864 8865 // Inconsistent address spaces at this point is invalid, even if the 8866 // address spaces would be compatible. 8867 // FIXME: This doesn't catch address space mismatches for pointers of 8868 // different nesting levels, like: 8869 // __local int *** a; 8870 // int ** b = a; 8871 // It's not clear how to actually determine when such pointers are 8872 // invalidly incompatible. 8873 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8874 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8875 8876 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8877 8878 if (lhptee == rhptee) 8879 return Sema::IncompatibleNestedPointerQualifiers; 8880 } 8881 8882 // General pointer incompatibility takes priority over qualifiers. 8883 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8884 return Sema::IncompatibleFunctionPointer; 8885 return Sema::IncompatiblePointer; 8886 } 8887 if (!S.getLangOpts().CPlusPlus && 8888 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8889 return Sema::IncompatibleFunctionPointer; 8890 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8891 return Sema::IncompatibleFunctionPointer; 8892 return ConvTy; 8893 } 8894 8895 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8896 /// block pointer types are compatible or whether a block and normal pointer 8897 /// are compatible. It is more restrict than comparing two function pointer 8898 // types. 8899 static Sema::AssignConvertType 8900 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8901 QualType RHSType) { 8902 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8903 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8904 8905 QualType lhptee, rhptee; 8906 8907 // get the "pointed to" type (ignoring qualifiers at the top level) 8908 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8909 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8910 8911 // In C++, the types have to match exactly. 8912 if (S.getLangOpts().CPlusPlus) 8913 return Sema::IncompatibleBlockPointer; 8914 8915 Sema::AssignConvertType ConvTy = Sema::Compatible; 8916 8917 // For blocks we enforce that qualifiers are identical. 8918 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8919 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8920 if (S.getLangOpts().OpenCL) { 8921 LQuals.removeAddressSpace(); 8922 RQuals.removeAddressSpace(); 8923 } 8924 if (LQuals != RQuals) 8925 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8926 8927 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8928 // assignment. 8929 // The current behavior is similar to C++ lambdas. A block might be 8930 // assigned to a variable iff its return type and parameters are compatible 8931 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8932 // an assignment. Presumably it should behave in way that a function pointer 8933 // assignment does in C, so for each parameter and return type: 8934 // * CVR and address space of LHS should be a superset of CVR and address 8935 // space of RHS. 8936 // * unqualified types should be compatible. 8937 if (S.getLangOpts().OpenCL) { 8938 if (!S.Context.typesAreBlockPointerCompatible( 8939 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8940 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8941 return Sema::IncompatibleBlockPointer; 8942 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8943 return Sema::IncompatibleBlockPointer; 8944 8945 return ConvTy; 8946 } 8947 8948 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8949 /// for assignment compatibility. 8950 static Sema::AssignConvertType 8951 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8952 QualType RHSType) { 8953 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8954 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8955 8956 if (LHSType->isObjCBuiltinType()) { 8957 // Class is not compatible with ObjC object pointers. 8958 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8959 !RHSType->isObjCQualifiedClassType()) 8960 return Sema::IncompatiblePointer; 8961 return Sema::Compatible; 8962 } 8963 if (RHSType->isObjCBuiltinType()) { 8964 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8965 !LHSType->isObjCQualifiedClassType()) 8966 return Sema::IncompatiblePointer; 8967 return Sema::Compatible; 8968 } 8969 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8970 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8971 8972 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8973 // make an exception for id<P> 8974 !LHSType->isObjCQualifiedIdType()) 8975 return Sema::CompatiblePointerDiscardsQualifiers; 8976 8977 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8978 return Sema::Compatible; 8979 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8980 return Sema::IncompatibleObjCQualifiedId; 8981 return Sema::IncompatiblePointer; 8982 } 8983 8984 Sema::AssignConvertType 8985 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8986 QualType LHSType, QualType RHSType) { 8987 // Fake up an opaque expression. We don't actually care about what 8988 // cast operations are required, so if CheckAssignmentConstraints 8989 // adds casts to this they'll be wasted, but fortunately that doesn't 8990 // usually happen on valid code. 8991 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8992 ExprResult RHSPtr = &RHSExpr; 8993 CastKind K; 8994 8995 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8996 } 8997 8998 /// This helper function returns true if QT is a vector type that has element 8999 /// type ElementType. 9000 static bool isVector(QualType QT, QualType ElementType) { 9001 if (const VectorType *VT = QT->getAs<VectorType>()) 9002 return VT->getElementType().getCanonicalType() == ElementType; 9003 return false; 9004 } 9005 9006 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9007 /// has code to accommodate several GCC extensions when type checking 9008 /// pointers. Here are some objectionable examples that GCC considers warnings: 9009 /// 9010 /// int a, *pint; 9011 /// short *pshort; 9012 /// struct foo *pfoo; 9013 /// 9014 /// pint = pshort; // warning: assignment from incompatible pointer type 9015 /// a = pint; // warning: assignment makes integer from pointer without a cast 9016 /// pint = a; // warning: assignment makes pointer from integer without a cast 9017 /// pint = pfoo; // warning: assignment from incompatible pointer type 9018 /// 9019 /// As a result, the code for dealing with pointers is more complex than the 9020 /// C99 spec dictates. 9021 /// 9022 /// Sets 'Kind' for any result kind except Incompatible. 9023 Sema::AssignConvertType 9024 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9025 CastKind &Kind, bool ConvertRHS) { 9026 QualType RHSType = RHS.get()->getType(); 9027 QualType OrigLHSType = LHSType; 9028 9029 // Get canonical types. We're not formatting these types, just comparing 9030 // them. 9031 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9032 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9033 9034 // Common case: no conversion required. 9035 if (LHSType == RHSType) { 9036 Kind = CK_NoOp; 9037 return Compatible; 9038 } 9039 9040 // If we have an atomic type, try a non-atomic assignment, then just add an 9041 // atomic qualification step. 9042 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9043 Sema::AssignConvertType result = 9044 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9045 if (result != Compatible) 9046 return result; 9047 if (Kind != CK_NoOp && ConvertRHS) 9048 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9049 Kind = CK_NonAtomicToAtomic; 9050 return Compatible; 9051 } 9052 9053 // If the left-hand side is a reference type, then we are in a 9054 // (rare!) case where we've allowed the use of references in C, 9055 // e.g., as a parameter type in a built-in function. In this case, 9056 // just make sure that the type referenced is compatible with the 9057 // right-hand side type. The caller is responsible for adjusting 9058 // LHSType so that the resulting expression does not have reference 9059 // type. 9060 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9061 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9062 Kind = CK_LValueBitCast; 9063 return Compatible; 9064 } 9065 return Incompatible; 9066 } 9067 9068 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9069 // to the same ExtVector type. 9070 if (LHSType->isExtVectorType()) { 9071 if (RHSType->isExtVectorType()) 9072 return Incompatible; 9073 if (RHSType->isArithmeticType()) { 9074 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9075 if (ConvertRHS) 9076 RHS = prepareVectorSplat(LHSType, RHS.get()); 9077 Kind = CK_VectorSplat; 9078 return Compatible; 9079 } 9080 } 9081 9082 // Conversions to or from vector type. 9083 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9084 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9085 // Allow assignments of an AltiVec vector type to an equivalent GCC 9086 // vector type and vice versa 9087 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9088 Kind = CK_BitCast; 9089 return Compatible; 9090 } 9091 9092 // If we are allowing lax vector conversions, and LHS and RHS are both 9093 // vectors, the total size only needs to be the same. This is a bitcast; 9094 // no bits are changed but the result type is different. 9095 if (isLaxVectorConversion(RHSType, LHSType)) { 9096 Kind = CK_BitCast; 9097 return IncompatibleVectors; 9098 } 9099 } 9100 9101 // When the RHS comes from another lax conversion (e.g. binops between 9102 // scalars and vectors) the result is canonicalized as a vector. When the 9103 // LHS is also a vector, the lax is allowed by the condition above. Handle 9104 // the case where LHS is a scalar. 9105 if (LHSType->isScalarType()) { 9106 const VectorType *VecType = RHSType->getAs<VectorType>(); 9107 if (VecType && VecType->getNumElements() == 1 && 9108 isLaxVectorConversion(RHSType, LHSType)) { 9109 ExprResult *VecExpr = &RHS; 9110 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9111 Kind = CK_BitCast; 9112 return Compatible; 9113 } 9114 } 9115 9116 // Allow assignments between fixed-length and sizeless SVE vectors. 9117 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9118 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9119 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9120 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9121 Kind = CK_BitCast; 9122 return Compatible; 9123 } 9124 9125 return Incompatible; 9126 } 9127 9128 // Diagnose attempts to convert between __float128 and long double where 9129 // such conversions currently can't be handled. 9130 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9131 return Incompatible; 9132 9133 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9134 // discards the imaginary part. 9135 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9136 !LHSType->getAs<ComplexType>()) 9137 return Incompatible; 9138 9139 // Arithmetic conversions. 9140 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9141 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9142 if (ConvertRHS) 9143 Kind = PrepareScalarCast(RHS, LHSType); 9144 return Compatible; 9145 } 9146 9147 // Conversions to normal pointers. 9148 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9149 // U* -> T* 9150 if (isa<PointerType>(RHSType)) { 9151 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9152 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9153 if (AddrSpaceL != AddrSpaceR) 9154 Kind = CK_AddressSpaceConversion; 9155 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9156 Kind = CK_NoOp; 9157 else 9158 Kind = CK_BitCast; 9159 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9160 } 9161 9162 // int -> T* 9163 if (RHSType->isIntegerType()) { 9164 Kind = CK_IntegralToPointer; // FIXME: null? 9165 return IntToPointer; 9166 } 9167 9168 // C pointers are not compatible with ObjC object pointers, 9169 // with two exceptions: 9170 if (isa<ObjCObjectPointerType>(RHSType)) { 9171 // - conversions to void* 9172 if (LHSPointer->getPointeeType()->isVoidType()) { 9173 Kind = CK_BitCast; 9174 return Compatible; 9175 } 9176 9177 // - conversions from 'Class' to the redefinition type 9178 if (RHSType->isObjCClassType() && 9179 Context.hasSameType(LHSType, 9180 Context.getObjCClassRedefinitionType())) { 9181 Kind = CK_BitCast; 9182 return Compatible; 9183 } 9184 9185 Kind = CK_BitCast; 9186 return IncompatiblePointer; 9187 } 9188 9189 // U^ -> void* 9190 if (RHSType->getAs<BlockPointerType>()) { 9191 if (LHSPointer->getPointeeType()->isVoidType()) { 9192 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9193 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9194 ->getPointeeType() 9195 .getAddressSpace(); 9196 Kind = 9197 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9198 return Compatible; 9199 } 9200 } 9201 9202 return Incompatible; 9203 } 9204 9205 // Conversions to block pointers. 9206 if (isa<BlockPointerType>(LHSType)) { 9207 // U^ -> T^ 9208 if (RHSType->isBlockPointerType()) { 9209 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9210 ->getPointeeType() 9211 .getAddressSpace(); 9212 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9213 ->getPointeeType() 9214 .getAddressSpace(); 9215 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9216 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9217 } 9218 9219 // int or null -> T^ 9220 if (RHSType->isIntegerType()) { 9221 Kind = CK_IntegralToPointer; // FIXME: null 9222 return IntToBlockPointer; 9223 } 9224 9225 // id -> T^ 9226 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9227 Kind = CK_AnyPointerToBlockPointerCast; 9228 return Compatible; 9229 } 9230 9231 // void* -> T^ 9232 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9233 if (RHSPT->getPointeeType()->isVoidType()) { 9234 Kind = CK_AnyPointerToBlockPointerCast; 9235 return Compatible; 9236 } 9237 9238 return Incompatible; 9239 } 9240 9241 // Conversions to Objective-C pointers. 9242 if (isa<ObjCObjectPointerType>(LHSType)) { 9243 // A* -> B* 9244 if (RHSType->isObjCObjectPointerType()) { 9245 Kind = CK_BitCast; 9246 Sema::AssignConvertType result = 9247 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9248 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9249 result == Compatible && 9250 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9251 result = IncompatibleObjCWeakRef; 9252 return result; 9253 } 9254 9255 // int or null -> A* 9256 if (RHSType->isIntegerType()) { 9257 Kind = CK_IntegralToPointer; // FIXME: null 9258 return IntToPointer; 9259 } 9260 9261 // In general, C pointers are not compatible with ObjC object pointers, 9262 // with two exceptions: 9263 if (isa<PointerType>(RHSType)) { 9264 Kind = CK_CPointerToObjCPointerCast; 9265 9266 // - conversions from 'void*' 9267 if (RHSType->isVoidPointerType()) { 9268 return Compatible; 9269 } 9270 9271 // - conversions to 'Class' from its redefinition type 9272 if (LHSType->isObjCClassType() && 9273 Context.hasSameType(RHSType, 9274 Context.getObjCClassRedefinitionType())) { 9275 return Compatible; 9276 } 9277 9278 return IncompatiblePointer; 9279 } 9280 9281 // Only under strict condition T^ is compatible with an Objective-C pointer. 9282 if (RHSType->isBlockPointerType() && 9283 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9284 if (ConvertRHS) 9285 maybeExtendBlockObject(RHS); 9286 Kind = CK_BlockPointerToObjCPointerCast; 9287 return Compatible; 9288 } 9289 9290 return Incompatible; 9291 } 9292 9293 // Conversions from pointers that are not covered by the above. 9294 if (isa<PointerType>(RHSType)) { 9295 // T* -> _Bool 9296 if (LHSType == Context.BoolTy) { 9297 Kind = CK_PointerToBoolean; 9298 return Compatible; 9299 } 9300 9301 // T* -> int 9302 if (LHSType->isIntegerType()) { 9303 Kind = CK_PointerToIntegral; 9304 return PointerToInt; 9305 } 9306 9307 return Incompatible; 9308 } 9309 9310 // Conversions from Objective-C pointers that are not covered by the above. 9311 if (isa<ObjCObjectPointerType>(RHSType)) { 9312 // T* -> _Bool 9313 if (LHSType == Context.BoolTy) { 9314 Kind = CK_PointerToBoolean; 9315 return Compatible; 9316 } 9317 9318 // T* -> int 9319 if (LHSType->isIntegerType()) { 9320 Kind = CK_PointerToIntegral; 9321 return PointerToInt; 9322 } 9323 9324 return Incompatible; 9325 } 9326 9327 // struct A -> struct B 9328 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9329 if (Context.typesAreCompatible(LHSType, RHSType)) { 9330 Kind = CK_NoOp; 9331 return Compatible; 9332 } 9333 } 9334 9335 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9336 Kind = CK_IntToOCLSampler; 9337 return Compatible; 9338 } 9339 9340 return Incompatible; 9341 } 9342 9343 /// Constructs a transparent union from an expression that is 9344 /// used to initialize the transparent union. 9345 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9346 ExprResult &EResult, QualType UnionType, 9347 FieldDecl *Field) { 9348 // Build an initializer list that designates the appropriate member 9349 // of the transparent union. 9350 Expr *E = EResult.get(); 9351 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9352 E, SourceLocation()); 9353 Initializer->setType(UnionType); 9354 Initializer->setInitializedFieldInUnion(Field); 9355 9356 // Build a compound literal constructing a value of the transparent 9357 // union type from this initializer list. 9358 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9359 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9360 VK_RValue, Initializer, false); 9361 } 9362 9363 Sema::AssignConvertType 9364 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9365 ExprResult &RHS) { 9366 QualType RHSType = RHS.get()->getType(); 9367 9368 // If the ArgType is a Union type, we want to handle a potential 9369 // transparent_union GCC extension. 9370 const RecordType *UT = ArgType->getAsUnionType(); 9371 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9372 return Incompatible; 9373 9374 // The field to initialize within the transparent union. 9375 RecordDecl *UD = UT->getDecl(); 9376 FieldDecl *InitField = nullptr; 9377 // It's compatible if the expression matches any of the fields. 9378 for (auto *it : UD->fields()) { 9379 if (it->getType()->isPointerType()) { 9380 // If the transparent union contains a pointer type, we allow: 9381 // 1) void pointer 9382 // 2) null pointer constant 9383 if (RHSType->isPointerType()) 9384 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9385 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9386 InitField = it; 9387 break; 9388 } 9389 9390 if (RHS.get()->isNullPointerConstant(Context, 9391 Expr::NPC_ValueDependentIsNull)) { 9392 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9393 CK_NullToPointer); 9394 InitField = it; 9395 break; 9396 } 9397 } 9398 9399 CastKind Kind; 9400 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9401 == Compatible) { 9402 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9403 InitField = it; 9404 break; 9405 } 9406 } 9407 9408 if (!InitField) 9409 return Incompatible; 9410 9411 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9412 return Compatible; 9413 } 9414 9415 Sema::AssignConvertType 9416 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9417 bool Diagnose, 9418 bool DiagnoseCFAudited, 9419 bool ConvertRHS) { 9420 // We need to be able to tell the caller whether we diagnosed a problem, if 9421 // they ask us to issue diagnostics. 9422 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9423 9424 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9425 // we can't avoid *all* modifications at the moment, so we need some somewhere 9426 // to put the updated value. 9427 ExprResult LocalRHS = CallerRHS; 9428 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9429 9430 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9431 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9432 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9433 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9434 Diag(RHS.get()->getExprLoc(), 9435 diag::warn_noderef_to_dereferenceable_pointer) 9436 << RHS.get()->getSourceRange(); 9437 } 9438 } 9439 } 9440 9441 if (getLangOpts().CPlusPlus) { 9442 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9443 // C++ 5.17p3: If the left operand is not of class type, the 9444 // expression is implicitly converted (C++ 4) to the 9445 // cv-unqualified type of the left operand. 9446 QualType RHSType = RHS.get()->getType(); 9447 if (Diagnose) { 9448 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9449 AA_Assigning); 9450 } else { 9451 ImplicitConversionSequence ICS = 9452 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9453 /*SuppressUserConversions=*/false, 9454 AllowedExplicit::None, 9455 /*InOverloadResolution=*/false, 9456 /*CStyle=*/false, 9457 /*AllowObjCWritebackConversion=*/false); 9458 if (ICS.isFailure()) 9459 return Incompatible; 9460 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9461 ICS, AA_Assigning); 9462 } 9463 if (RHS.isInvalid()) 9464 return Incompatible; 9465 Sema::AssignConvertType result = Compatible; 9466 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9467 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9468 result = IncompatibleObjCWeakRef; 9469 return result; 9470 } 9471 9472 // FIXME: Currently, we fall through and treat C++ classes like C 9473 // structures. 9474 // FIXME: We also fall through for atomics; not sure what should 9475 // happen there, though. 9476 } else if (RHS.get()->getType() == Context.OverloadTy) { 9477 // As a set of extensions to C, we support overloading on functions. These 9478 // functions need to be resolved here. 9479 DeclAccessPair DAP; 9480 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9481 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9482 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9483 else 9484 return Incompatible; 9485 } 9486 9487 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9488 // a null pointer constant. 9489 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9490 LHSType->isBlockPointerType()) && 9491 RHS.get()->isNullPointerConstant(Context, 9492 Expr::NPC_ValueDependentIsNull)) { 9493 if (Diagnose || ConvertRHS) { 9494 CastKind Kind; 9495 CXXCastPath Path; 9496 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9497 /*IgnoreBaseAccess=*/false, Diagnose); 9498 if (ConvertRHS) 9499 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9500 } 9501 return Compatible; 9502 } 9503 9504 // OpenCL queue_t type assignment. 9505 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9506 Context, Expr::NPC_ValueDependentIsNull)) { 9507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9508 return Compatible; 9509 } 9510 9511 // This check seems unnatural, however it is necessary to ensure the proper 9512 // conversion of functions/arrays. If the conversion were done for all 9513 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9514 // expressions that suppress this implicit conversion (&, sizeof). 9515 // 9516 // Suppress this for references: C++ 8.5.3p5. 9517 if (!LHSType->isReferenceType()) { 9518 // FIXME: We potentially allocate here even if ConvertRHS is false. 9519 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9520 if (RHS.isInvalid()) 9521 return Incompatible; 9522 } 9523 CastKind Kind; 9524 Sema::AssignConvertType result = 9525 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9526 9527 // C99 6.5.16.1p2: The value of the right operand is converted to the 9528 // type of the assignment expression. 9529 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9530 // so that we can use references in built-in functions even in C. 9531 // The getNonReferenceType() call makes sure that the resulting expression 9532 // does not have reference type. 9533 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9534 QualType Ty = LHSType.getNonLValueExprType(Context); 9535 Expr *E = RHS.get(); 9536 9537 // Check for various Objective-C errors. If we are not reporting 9538 // diagnostics and just checking for errors, e.g., during overload 9539 // resolution, return Incompatible to indicate the failure. 9540 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9541 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9542 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9543 if (!Diagnose) 9544 return Incompatible; 9545 } 9546 if (getLangOpts().ObjC && 9547 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9548 E->getType(), E, Diagnose) || 9549 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9550 if (!Diagnose) 9551 return Incompatible; 9552 // Replace the expression with a corrected version and continue so we 9553 // can find further errors. 9554 RHS = E; 9555 return Compatible; 9556 } 9557 9558 if (ConvertRHS) 9559 RHS = ImpCastExprToType(E, Ty, Kind); 9560 } 9561 9562 return result; 9563 } 9564 9565 namespace { 9566 /// The original operand to an operator, prior to the application of the usual 9567 /// arithmetic conversions and converting the arguments of a builtin operator 9568 /// candidate. 9569 struct OriginalOperand { 9570 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9571 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9572 Op = MTE->getSubExpr(); 9573 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9574 Op = BTE->getSubExpr(); 9575 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9576 Orig = ICE->getSubExprAsWritten(); 9577 Conversion = ICE->getConversionFunction(); 9578 } 9579 } 9580 9581 QualType getType() const { return Orig->getType(); } 9582 9583 Expr *Orig; 9584 NamedDecl *Conversion; 9585 }; 9586 } 9587 9588 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9589 ExprResult &RHS) { 9590 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9591 9592 Diag(Loc, diag::err_typecheck_invalid_operands) 9593 << OrigLHS.getType() << OrigRHS.getType() 9594 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9595 9596 // If a user-defined conversion was applied to either of the operands prior 9597 // to applying the built-in operator rules, tell the user about it. 9598 if (OrigLHS.Conversion) { 9599 Diag(OrigLHS.Conversion->getLocation(), 9600 diag::note_typecheck_invalid_operands_converted) 9601 << 0 << LHS.get()->getType(); 9602 } 9603 if (OrigRHS.Conversion) { 9604 Diag(OrigRHS.Conversion->getLocation(), 9605 diag::note_typecheck_invalid_operands_converted) 9606 << 1 << RHS.get()->getType(); 9607 } 9608 9609 return QualType(); 9610 } 9611 9612 // Diagnose cases where a scalar was implicitly converted to a vector and 9613 // diagnose the underlying types. Otherwise, diagnose the error 9614 // as invalid vector logical operands for non-C++ cases. 9615 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9616 ExprResult &RHS) { 9617 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9618 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9619 9620 bool LHSNatVec = LHSType->isVectorType(); 9621 bool RHSNatVec = RHSType->isVectorType(); 9622 9623 if (!(LHSNatVec && RHSNatVec)) { 9624 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9625 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9626 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9627 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9628 << Vector->getSourceRange(); 9629 return QualType(); 9630 } 9631 9632 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9633 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9634 << RHS.get()->getSourceRange(); 9635 9636 return QualType(); 9637 } 9638 9639 /// Try to convert a value of non-vector type to a vector type by converting 9640 /// the type to the element type of the vector and then performing a splat. 9641 /// If the language is OpenCL, we only use conversions that promote scalar 9642 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9643 /// for float->int. 9644 /// 9645 /// OpenCL V2.0 6.2.6.p2: 9646 /// An error shall occur if any scalar operand type has greater rank 9647 /// than the type of the vector element. 9648 /// 9649 /// \param scalar - if non-null, actually perform the conversions 9650 /// \return true if the operation fails (but without diagnosing the failure) 9651 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9652 QualType scalarTy, 9653 QualType vectorEltTy, 9654 QualType vectorTy, 9655 unsigned &DiagID) { 9656 // The conversion to apply to the scalar before splatting it, 9657 // if necessary. 9658 CastKind scalarCast = CK_NoOp; 9659 9660 if (vectorEltTy->isIntegralType(S.Context)) { 9661 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9662 (scalarTy->isIntegerType() && 9663 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9664 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9665 return true; 9666 } 9667 if (!scalarTy->isIntegralType(S.Context)) 9668 return true; 9669 scalarCast = CK_IntegralCast; 9670 } else if (vectorEltTy->isRealFloatingType()) { 9671 if (scalarTy->isRealFloatingType()) { 9672 if (S.getLangOpts().OpenCL && 9673 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9674 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9675 return true; 9676 } 9677 scalarCast = CK_FloatingCast; 9678 } 9679 else if (scalarTy->isIntegralType(S.Context)) 9680 scalarCast = CK_IntegralToFloating; 9681 else 9682 return true; 9683 } else { 9684 return true; 9685 } 9686 9687 // Adjust scalar if desired. 9688 if (scalar) { 9689 if (scalarCast != CK_NoOp) 9690 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9691 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9692 } 9693 return false; 9694 } 9695 9696 /// Convert vector E to a vector with the same number of elements but different 9697 /// element type. 9698 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9699 const auto *VecTy = E->getType()->getAs<VectorType>(); 9700 assert(VecTy && "Expression E must be a vector"); 9701 QualType NewVecTy = S.Context.getVectorType(ElementType, 9702 VecTy->getNumElements(), 9703 VecTy->getVectorKind()); 9704 9705 // Look through the implicit cast. Return the subexpression if its type is 9706 // NewVecTy. 9707 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9708 if (ICE->getSubExpr()->getType() == NewVecTy) 9709 return ICE->getSubExpr(); 9710 9711 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9712 return S.ImpCastExprToType(E, NewVecTy, Cast); 9713 } 9714 9715 /// Test if a (constant) integer Int can be casted to another integer type 9716 /// IntTy without losing precision. 9717 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9718 QualType OtherIntTy) { 9719 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9720 9721 // Reject cases where the value of the Int is unknown as that would 9722 // possibly cause truncation, but accept cases where the scalar can be 9723 // demoted without loss of precision. 9724 Expr::EvalResult EVResult; 9725 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9726 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9727 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9728 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9729 9730 if (CstInt) { 9731 // If the scalar is constant and is of a higher order and has more active 9732 // bits that the vector element type, reject it. 9733 llvm::APSInt Result = EVResult.Val.getInt(); 9734 unsigned NumBits = IntSigned 9735 ? (Result.isNegative() ? Result.getMinSignedBits() 9736 : Result.getActiveBits()) 9737 : Result.getActiveBits(); 9738 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9739 return true; 9740 9741 // If the signedness of the scalar type and the vector element type 9742 // differs and the number of bits is greater than that of the vector 9743 // element reject it. 9744 return (IntSigned != OtherIntSigned && 9745 NumBits > S.Context.getIntWidth(OtherIntTy)); 9746 } 9747 9748 // Reject cases where the value of the scalar is not constant and it's 9749 // order is greater than that of the vector element type. 9750 return (Order < 0); 9751 } 9752 9753 /// Test if a (constant) integer Int can be casted to floating point type 9754 /// FloatTy without losing precision. 9755 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9756 QualType FloatTy) { 9757 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9758 9759 // Determine if the integer constant can be expressed as a floating point 9760 // number of the appropriate type. 9761 Expr::EvalResult EVResult; 9762 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9763 9764 uint64_t Bits = 0; 9765 if (CstInt) { 9766 // Reject constants that would be truncated if they were converted to 9767 // the floating point type. Test by simple to/from conversion. 9768 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9769 // could be avoided if there was a convertFromAPInt method 9770 // which could signal back if implicit truncation occurred. 9771 llvm::APSInt Result = EVResult.Val.getInt(); 9772 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9773 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9774 llvm::APFloat::rmTowardZero); 9775 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9776 !IntTy->hasSignedIntegerRepresentation()); 9777 bool Ignored = false; 9778 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9779 &Ignored); 9780 if (Result != ConvertBack) 9781 return true; 9782 } else { 9783 // Reject types that cannot be fully encoded into the mantissa of 9784 // the float. 9785 Bits = S.Context.getTypeSize(IntTy); 9786 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9787 S.Context.getFloatTypeSemantics(FloatTy)); 9788 if (Bits > FloatPrec) 9789 return true; 9790 } 9791 9792 return false; 9793 } 9794 9795 /// Attempt to convert and splat Scalar into a vector whose types matches 9796 /// Vector following GCC conversion rules. The rule is that implicit 9797 /// conversion can occur when Scalar can be casted to match Vector's element 9798 /// type without causing truncation of Scalar. 9799 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9800 ExprResult *Vector) { 9801 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9802 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9803 const VectorType *VT = VectorTy->getAs<VectorType>(); 9804 9805 assert(!isa<ExtVectorType>(VT) && 9806 "ExtVectorTypes should not be handled here!"); 9807 9808 QualType VectorEltTy = VT->getElementType(); 9809 9810 // Reject cases where the vector element type or the scalar element type are 9811 // not integral or floating point types. 9812 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9813 return true; 9814 9815 // The conversion to apply to the scalar before splatting it, 9816 // if necessary. 9817 CastKind ScalarCast = CK_NoOp; 9818 9819 // Accept cases where the vector elements are integers and the scalar is 9820 // an integer. 9821 // FIXME: Notionally if the scalar was a floating point value with a precise 9822 // integral representation, we could cast it to an appropriate integer 9823 // type and then perform the rest of the checks here. GCC will perform 9824 // this conversion in some cases as determined by the input language. 9825 // We should accept it on a language independent basis. 9826 if (VectorEltTy->isIntegralType(S.Context) && 9827 ScalarTy->isIntegralType(S.Context) && 9828 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9829 9830 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9831 return true; 9832 9833 ScalarCast = CK_IntegralCast; 9834 } else if (VectorEltTy->isIntegralType(S.Context) && 9835 ScalarTy->isRealFloatingType()) { 9836 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9837 ScalarCast = CK_FloatingToIntegral; 9838 else 9839 return true; 9840 } else if (VectorEltTy->isRealFloatingType()) { 9841 if (ScalarTy->isRealFloatingType()) { 9842 9843 // Reject cases where the scalar type is not a constant and has a higher 9844 // Order than the vector element type. 9845 llvm::APFloat Result(0.0); 9846 9847 // Determine whether this is a constant scalar. In the event that the 9848 // value is dependent (and thus cannot be evaluated by the constant 9849 // evaluator), skip the evaluation. This will then diagnose once the 9850 // expression is instantiated. 9851 bool CstScalar = Scalar->get()->isValueDependent() || 9852 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9853 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9854 if (!CstScalar && Order < 0) 9855 return true; 9856 9857 // If the scalar cannot be safely casted to the vector element type, 9858 // reject it. 9859 if (CstScalar) { 9860 bool Truncated = false; 9861 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9862 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9863 if (Truncated) 9864 return true; 9865 } 9866 9867 ScalarCast = CK_FloatingCast; 9868 } else if (ScalarTy->isIntegralType(S.Context)) { 9869 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9870 return true; 9871 9872 ScalarCast = CK_IntegralToFloating; 9873 } else 9874 return true; 9875 } else if (ScalarTy->isEnumeralType()) 9876 return true; 9877 9878 // Adjust scalar if desired. 9879 if (Scalar) { 9880 if (ScalarCast != CK_NoOp) 9881 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9882 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9883 } 9884 return false; 9885 } 9886 9887 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9888 SourceLocation Loc, bool IsCompAssign, 9889 bool AllowBothBool, 9890 bool AllowBoolConversions) { 9891 if (!IsCompAssign) { 9892 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9893 if (LHS.isInvalid()) 9894 return QualType(); 9895 } 9896 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9897 if (RHS.isInvalid()) 9898 return QualType(); 9899 9900 // For conversion purposes, we ignore any qualifiers. 9901 // For example, "const float" and "float" are equivalent. 9902 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9903 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9904 9905 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9906 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9907 assert(LHSVecType || RHSVecType); 9908 9909 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9910 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9911 return InvalidOperands(Loc, LHS, RHS); 9912 9913 // AltiVec-style "vector bool op vector bool" combinations are allowed 9914 // for some operators but not others. 9915 if (!AllowBothBool && 9916 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9917 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9918 return InvalidOperands(Loc, LHS, RHS); 9919 9920 // If the vector types are identical, return. 9921 if (Context.hasSameType(LHSType, RHSType)) 9922 return LHSType; 9923 9924 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9925 if (LHSVecType && RHSVecType && 9926 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9927 if (isa<ExtVectorType>(LHSVecType)) { 9928 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9929 return LHSType; 9930 } 9931 9932 if (!IsCompAssign) 9933 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9934 return RHSType; 9935 } 9936 9937 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9938 // can be mixed, with the result being the non-bool type. The non-bool 9939 // operand must have integer element type. 9940 if (AllowBoolConversions && LHSVecType && RHSVecType && 9941 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9942 (Context.getTypeSize(LHSVecType->getElementType()) == 9943 Context.getTypeSize(RHSVecType->getElementType()))) { 9944 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9945 LHSVecType->getElementType()->isIntegerType() && 9946 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9947 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9948 return LHSType; 9949 } 9950 if (!IsCompAssign && 9951 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9952 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9953 RHSVecType->getElementType()->isIntegerType()) { 9954 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9955 return RHSType; 9956 } 9957 } 9958 9959 // Expressions containing fixed-length and sizeless SVE vectors are invalid 9960 // since the ambiguity can affect the ABI. 9961 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9962 const VectorType *VecType = SecondType->getAs<VectorType>(); 9963 return FirstType->isSizelessBuiltinType() && VecType && 9964 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9965 VecType->getVectorKind() == 9966 VectorType::SveFixedLengthPredicateVector); 9967 }; 9968 9969 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9970 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 9971 return QualType(); 9972 } 9973 9974 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 9975 // since the ambiguity can affect the ABI. 9976 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 9977 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 9978 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 9979 9980 if (FirstVecType && SecondVecType) 9981 return FirstVecType->getVectorKind() == VectorType::GenericVector && 9982 (SecondVecType->getVectorKind() == 9983 VectorType::SveFixedLengthDataVector || 9984 SecondVecType->getVectorKind() == 9985 VectorType::SveFixedLengthPredicateVector); 9986 9987 return FirstType->isSizelessBuiltinType() && SecondVecType && 9988 SecondVecType->getVectorKind() == VectorType::GenericVector; 9989 }; 9990 9991 if (IsSveGnuConversion(LHSType, RHSType) || 9992 IsSveGnuConversion(RHSType, LHSType)) { 9993 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 9994 return QualType(); 9995 } 9996 9997 // If there's a vector type and a scalar, try to convert the scalar to 9998 // the vector element type and splat. 9999 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10000 if (!RHSVecType) { 10001 if (isa<ExtVectorType>(LHSVecType)) { 10002 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10003 LHSVecType->getElementType(), LHSType, 10004 DiagID)) 10005 return LHSType; 10006 } else { 10007 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10008 return LHSType; 10009 } 10010 } 10011 if (!LHSVecType) { 10012 if (isa<ExtVectorType>(RHSVecType)) { 10013 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10014 LHSType, RHSVecType->getElementType(), 10015 RHSType, DiagID)) 10016 return RHSType; 10017 } else { 10018 if (LHS.get()->getValueKind() == VK_LValue || 10019 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10020 return RHSType; 10021 } 10022 } 10023 10024 // FIXME: The code below also handles conversion between vectors and 10025 // non-scalars, we should break this down into fine grained specific checks 10026 // and emit proper diagnostics. 10027 QualType VecType = LHSVecType ? LHSType : RHSType; 10028 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10029 QualType OtherType = LHSVecType ? RHSType : LHSType; 10030 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10031 if (isLaxVectorConversion(OtherType, VecType)) { 10032 // If we're allowing lax vector conversions, only the total (data) size 10033 // needs to be the same. For non compound assignment, if one of the types is 10034 // scalar, the result is always the vector type. 10035 if (!IsCompAssign) { 10036 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10037 return VecType; 10038 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10039 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10040 // type. Note that this is already done by non-compound assignments in 10041 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10042 // <1 x T> -> T. The result is also a vector type. 10043 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10044 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10045 ExprResult *RHSExpr = &RHS; 10046 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10047 return VecType; 10048 } 10049 } 10050 10051 // Okay, the expression is invalid. 10052 10053 // If there's a non-vector, non-real operand, diagnose that. 10054 if ((!RHSVecType && !RHSType->isRealType()) || 10055 (!LHSVecType && !LHSType->isRealType())) { 10056 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10057 << LHSType << RHSType 10058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10059 return QualType(); 10060 } 10061 10062 // OpenCL V1.1 6.2.6.p1: 10063 // If the operands are of more than one vector type, then an error shall 10064 // occur. Implicit conversions between vector types are not permitted, per 10065 // section 6.2.1. 10066 if (getLangOpts().OpenCL && 10067 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10068 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10069 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10070 << RHSType; 10071 return QualType(); 10072 } 10073 10074 10075 // If there is a vector type that is not a ExtVector and a scalar, we reach 10076 // this point if scalar could not be converted to the vector's element type 10077 // without truncation. 10078 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10079 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10080 QualType Scalar = LHSVecType ? RHSType : LHSType; 10081 QualType Vector = LHSVecType ? LHSType : RHSType; 10082 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10083 Diag(Loc, 10084 diag::err_typecheck_vector_not_convertable_implict_truncation) 10085 << ScalarOrVector << Scalar << Vector; 10086 10087 return QualType(); 10088 } 10089 10090 // Otherwise, use the generic diagnostic. 10091 Diag(Loc, DiagID) 10092 << LHSType << RHSType 10093 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10094 return QualType(); 10095 } 10096 10097 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10098 // expression. These are mainly cases where the null pointer is used as an 10099 // integer instead of a pointer. 10100 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10101 SourceLocation Loc, bool IsCompare) { 10102 // The canonical way to check for a GNU null is with isNullPointerConstant, 10103 // but we use a bit of a hack here for speed; this is a relatively 10104 // hot path, and isNullPointerConstant is slow. 10105 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10106 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10107 10108 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10109 10110 // Avoid analyzing cases where the result will either be invalid (and 10111 // diagnosed as such) or entirely valid and not something to warn about. 10112 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10113 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10114 return; 10115 10116 // Comparison operations would not make sense with a null pointer no matter 10117 // what the other expression is. 10118 if (!IsCompare) { 10119 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10120 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10121 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10122 return; 10123 } 10124 10125 // The rest of the operations only make sense with a null pointer 10126 // if the other expression is a pointer. 10127 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10128 NonNullType->canDecayToPointerType()) 10129 return; 10130 10131 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10132 << LHSNull /* LHS is NULL */ << NonNullType 10133 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10134 } 10135 10136 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10137 SourceLocation Loc) { 10138 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10139 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10140 if (!LUE || !RUE) 10141 return; 10142 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10143 RUE->getKind() != UETT_SizeOf) 10144 return; 10145 10146 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10147 QualType LHSTy = LHSArg->getType(); 10148 QualType RHSTy; 10149 10150 if (RUE->isArgumentType()) 10151 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10152 else 10153 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10154 10155 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10156 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10157 return; 10158 10159 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10160 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10161 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10162 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10163 << LHSArgDecl; 10164 } 10165 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10166 QualType ArrayElemTy = ArrayTy->getElementType(); 10167 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10168 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10169 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10170 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10171 return; 10172 S.Diag(Loc, diag::warn_division_sizeof_array) 10173 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10174 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10175 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10176 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10177 << LHSArgDecl; 10178 } 10179 10180 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10181 } 10182 } 10183 10184 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10185 ExprResult &RHS, 10186 SourceLocation Loc, bool IsDiv) { 10187 // Check for division/remainder by zero. 10188 Expr::EvalResult RHSValue; 10189 if (!RHS.get()->isValueDependent() && 10190 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10191 RHSValue.Val.getInt() == 0) 10192 S.DiagRuntimeBehavior(Loc, RHS.get(), 10193 S.PDiag(diag::warn_remainder_division_by_zero) 10194 << IsDiv << RHS.get()->getSourceRange()); 10195 } 10196 10197 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10198 SourceLocation Loc, 10199 bool IsCompAssign, bool IsDiv) { 10200 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10201 10202 if (LHS.get()->getType()->isVectorType() || 10203 RHS.get()->getType()->isVectorType()) 10204 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10205 /*AllowBothBool*/getLangOpts().AltiVec, 10206 /*AllowBoolConversions*/false); 10207 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() || 10208 RHS.get()->getType()->isConstantMatrixType())) 10209 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10210 10211 QualType compType = UsualArithmeticConversions( 10212 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10213 if (LHS.isInvalid() || RHS.isInvalid()) 10214 return QualType(); 10215 10216 10217 if (compType.isNull() || !compType->isArithmeticType()) 10218 return InvalidOperands(Loc, LHS, RHS); 10219 if (IsDiv) { 10220 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10221 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10222 } 10223 return compType; 10224 } 10225 10226 QualType Sema::CheckRemainderOperands( 10227 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10228 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10229 10230 if (LHS.get()->getType()->isVectorType() || 10231 RHS.get()->getType()->isVectorType()) { 10232 if (LHS.get()->getType()->hasIntegerRepresentation() && 10233 RHS.get()->getType()->hasIntegerRepresentation()) 10234 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10235 /*AllowBothBool*/getLangOpts().AltiVec, 10236 /*AllowBoolConversions*/false); 10237 return InvalidOperands(Loc, LHS, RHS); 10238 } 10239 10240 QualType compType = UsualArithmeticConversions( 10241 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10242 if (LHS.isInvalid() || RHS.isInvalid()) 10243 return QualType(); 10244 10245 if (compType.isNull() || !compType->isIntegerType()) 10246 return InvalidOperands(Loc, LHS, RHS); 10247 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10248 return compType; 10249 } 10250 10251 /// Diagnose invalid arithmetic on two void pointers. 10252 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10253 Expr *LHSExpr, Expr *RHSExpr) { 10254 S.Diag(Loc, S.getLangOpts().CPlusPlus 10255 ? diag::err_typecheck_pointer_arith_void_type 10256 : diag::ext_gnu_void_ptr) 10257 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10258 << RHSExpr->getSourceRange(); 10259 } 10260 10261 /// Diagnose invalid arithmetic on a void pointer. 10262 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10263 Expr *Pointer) { 10264 S.Diag(Loc, S.getLangOpts().CPlusPlus 10265 ? diag::err_typecheck_pointer_arith_void_type 10266 : diag::ext_gnu_void_ptr) 10267 << 0 /* one pointer */ << Pointer->getSourceRange(); 10268 } 10269 10270 /// Diagnose invalid arithmetic on a null pointer. 10271 /// 10272 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10273 /// idiom, which we recognize as a GNU extension. 10274 /// 10275 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10276 Expr *Pointer, bool IsGNUIdiom) { 10277 if (IsGNUIdiom) 10278 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10279 << Pointer->getSourceRange(); 10280 else 10281 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10282 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10283 } 10284 10285 /// Diagnose invalid arithmetic on two function pointers. 10286 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10287 Expr *LHS, Expr *RHS) { 10288 assert(LHS->getType()->isAnyPointerType()); 10289 assert(RHS->getType()->isAnyPointerType()); 10290 S.Diag(Loc, S.getLangOpts().CPlusPlus 10291 ? diag::err_typecheck_pointer_arith_function_type 10292 : diag::ext_gnu_ptr_func_arith) 10293 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10294 // We only show the second type if it differs from the first. 10295 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10296 RHS->getType()) 10297 << RHS->getType()->getPointeeType() 10298 << LHS->getSourceRange() << RHS->getSourceRange(); 10299 } 10300 10301 /// Diagnose invalid arithmetic on a function pointer. 10302 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10303 Expr *Pointer) { 10304 assert(Pointer->getType()->isAnyPointerType()); 10305 S.Diag(Loc, S.getLangOpts().CPlusPlus 10306 ? diag::err_typecheck_pointer_arith_function_type 10307 : diag::ext_gnu_ptr_func_arith) 10308 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10309 << 0 /* one pointer, so only one type */ 10310 << Pointer->getSourceRange(); 10311 } 10312 10313 /// Emit error if Operand is incomplete pointer type 10314 /// 10315 /// \returns True if pointer has incomplete type 10316 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10317 Expr *Operand) { 10318 QualType ResType = Operand->getType(); 10319 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10320 ResType = ResAtomicType->getValueType(); 10321 10322 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10323 QualType PointeeTy = ResType->getPointeeType(); 10324 return S.RequireCompleteSizedType( 10325 Loc, PointeeTy, 10326 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10327 Operand->getSourceRange()); 10328 } 10329 10330 /// Check the validity of an arithmetic pointer operand. 10331 /// 10332 /// If the operand has pointer type, this code will check for pointer types 10333 /// which are invalid in arithmetic operations. These will be diagnosed 10334 /// appropriately, including whether or not the use is supported as an 10335 /// extension. 10336 /// 10337 /// \returns True when the operand is valid to use (even if as an extension). 10338 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10339 Expr *Operand) { 10340 QualType ResType = Operand->getType(); 10341 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10342 ResType = ResAtomicType->getValueType(); 10343 10344 if (!ResType->isAnyPointerType()) return true; 10345 10346 QualType PointeeTy = ResType->getPointeeType(); 10347 if (PointeeTy->isVoidType()) { 10348 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10349 return !S.getLangOpts().CPlusPlus; 10350 } 10351 if (PointeeTy->isFunctionType()) { 10352 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10353 return !S.getLangOpts().CPlusPlus; 10354 } 10355 10356 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10357 10358 return true; 10359 } 10360 10361 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10362 /// operands. 10363 /// 10364 /// This routine will diagnose any invalid arithmetic on pointer operands much 10365 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10366 /// for emitting a single diagnostic even for operations where both LHS and RHS 10367 /// are (potentially problematic) pointers. 10368 /// 10369 /// \returns True when the operand is valid to use (even if as an extension). 10370 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10371 Expr *LHSExpr, Expr *RHSExpr) { 10372 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10373 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10374 if (!isLHSPointer && !isRHSPointer) return true; 10375 10376 QualType LHSPointeeTy, RHSPointeeTy; 10377 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10378 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10379 10380 // if both are pointers check if operation is valid wrt address spaces 10381 if (isLHSPointer && isRHSPointer) { 10382 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10383 S.Diag(Loc, 10384 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10385 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10386 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10387 return false; 10388 } 10389 } 10390 10391 // Check for arithmetic on pointers to incomplete types. 10392 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10393 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10394 if (isLHSVoidPtr || isRHSVoidPtr) { 10395 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10396 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10397 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10398 10399 return !S.getLangOpts().CPlusPlus; 10400 } 10401 10402 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10403 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10404 if (isLHSFuncPtr || isRHSFuncPtr) { 10405 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10406 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10407 RHSExpr); 10408 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10409 10410 return !S.getLangOpts().CPlusPlus; 10411 } 10412 10413 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10414 return false; 10415 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10416 return false; 10417 10418 return true; 10419 } 10420 10421 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10422 /// literal. 10423 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10424 Expr *LHSExpr, Expr *RHSExpr) { 10425 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10426 Expr* IndexExpr = RHSExpr; 10427 if (!StrExpr) { 10428 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10429 IndexExpr = LHSExpr; 10430 } 10431 10432 bool IsStringPlusInt = StrExpr && 10433 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10434 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10435 return; 10436 10437 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10438 Self.Diag(OpLoc, diag::warn_string_plus_int) 10439 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10440 10441 // Only print a fixit for "str" + int, not for int + "str". 10442 if (IndexExpr == RHSExpr) { 10443 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10444 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10445 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10446 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10447 << FixItHint::CreateInsertion(EndLoc, "]"); 10448 } else 10449 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10450 } 10451 10452 /// Emit a warning when adding a char literal to a string. 10453 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10454 Expr *LHSExpr, Expr *RHSExpr) { 10455 const Expr *StringRefExpr = LHSExpr; 10456 const CharacterLiteral *CharExpr = 10457 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10458 10459 if (!CharExpr) { 10460 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10461 StringRefExpr = RHSExpr; 10462 } 10463 10464 if (!CharExpr || !StringRefExpr) 10465 return; 10466 10467 const QualType StringType = StringRefExpr->getType(); 10468 10469 // Return if not a PointerType. 10470 if (!StringType->isAnyPointerType()) 10471 return; 10472 10473 // Return if not a CharacterType. 10474 if (!StringType->getPointeeType()->isAnyCharacterType()) 10475 return; 10476 10477 ASTContext &Ctx = Self.getASTContext(); 10478 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10479 10480 const QualType CharType = CharExpr->getType(); 10481 if (!CharType->isAnyCharacterType() && 10482 CharType->isIntegerType() && 10483 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10484 Self.Diag(OpLoc, diag::warn_string_plus_char) 10485 << DiagRange << Ctx.CharTy; 10486 } else { 10487 Self.Diag(OpLoc, diag::warn_string_plus_char) 10488 << DiagRange << CharExpr->getType(); 10489 } 10490 10491 // Only print a fixit for str + char, not for char + str. 10492 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10493 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10494 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10495 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10496 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10497 << FixItHint::CreateInsertion(EndLoc, "]"); 10498 } else { 10499 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10500 } 10501 } 10502 10503 /// Emit error when two pointers are incompatible. 10504 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10505 Expr *LHSExpr, Expr *RHSExpr) { 10506 assert(LHSExpr->getType()->isAnyPointerType()); 10507 assert(RHSExpr->getType()->isAnyPointerType()); 10508 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10509 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10510 << RHSExpr->getSourceRange(); 10511 } 10512 10513 // C99 6.5.6 10514 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10515 SourceLocation Loc, BinaryOperatorKind Opc, 10516 QualType* CompLHSTy) { 10517 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10518 10519 if (LHS.get()->getType()->isVectorType() || 10520 RHS.get()->getType()->isVectorType()) { 10521 QualType compType = CheckVectorOperands( 10522 LHS, RHS, Loc, CompLHSTy, 10523 /*AllowBothBool*/getLangOpts().AltiVec, 10524 /*AllowBoolConversions*/getLangOpts().ZVector); 10525 if (CompLHSTy) *CompLHSTy = compType; 10526 return compType; 10527 } 10528 10529 if (LHS.get()->getType()->isConstantMatrixType() || 10530 RHS.get()->getType()->isConstantMatrixType()) { 10531 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10532 } 10533 10534 QualType compType = UsualArithmeticConversions( 10535 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10536 if (LHS.isInvalid() || RHS.isInvalid()) 10537 return QualType(); 10538 10539 // Diagnose "string literal" '+' int and string '+' "char literal". 10540 if (Opc == BO_Add) { 10541 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10542 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10543 } 10544 10545 // handle the common case first (both operands are arithmetic). 10546 if (!compType.isNull() && compType->isArithmeticType()) { 10547 if (CompLHSTy) *CompLHSTy = compType; 10548 return compType; 10549 } 10550 10551 // Type-checking. Ultimately the pointer's going to be in PExp; 10552 // note that we bias towards the LHS being the pointer. 10553 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10554 10555 bool isObjCPointer; 10556 if (PExp->getType()->isPointerType()) { 10557 isObjCPointer = false; 10558 } else if (PExp->getType()->isObjCObjectPointerType()) { 10559 isObjCPointer = true; 10560 } else { 10561 std::swap(PExp, IExp); 10562 if (PExp->getType()->isPointerType()) { 10563 isObjCPointer = false; 10564 } else if (PExp->getType()->isObjCObjectPointerType()) { 10565 isObjCPointer = true; 10566 } else { 10567 return InvalidOperands(Loc, LHS, RHS); 10568 } 10569 } 10570 assert(PExp->getType()->isAnyPointerType()); 10571 10572 if (!IExp->getType()->isIntegerType()) 10573 return InvalidOperands(Loc, LHS, RHS); 10574 10575 // Adding to a null pointer results in undefined behavior. 10576 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10577 Context, Expr::NPC_ValueDependentIsNotNull)) { 10578 // In C++ adding zero to a null pointer is defined. 10579 Expr::EvalResult KnownVal; 10580 if (!getLangOpts().CPlusPlus || 10581 (!IExp->isValueDependent() && 10582 (!IExp->EvaluateAsInt(KnownVal, Context) || 10583 KnownVal.Val.getInt() != 0))) { 10584 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10585 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10586 Context, BO_Add, PExp, IExp); 10587 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10588 } 10589 } 10590 10591 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10592 return QualType(); 10593 10594 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10595 return QualType(); 10596 10597 // Check array bounds for pointer arithemtic 10598 CheckArrayAccess(PExp, IExp); 10599 10600 if (CompLHSTy) { 10601 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10602 if (LHSTy.isNull()) { 10603 LHSTy = LHS.get()->getType(); 10604 if (LHSTy->isPromotableIntegerType()) 10605 LHSTy = Context.getPromotedIntegerType(LHSTy); 10606 } 10607 *CompLHSTy = LHSTy; 10608 } 10609 10610 return PExp->getType(); 10611 } 10612 10613 // C99 6.5.6 10614 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10615 SourceLocation Loc, 10616 QualType* CompLHSTy) { 10617 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10618 10619 if (LHS.get()->getType()->isVectorType() || 10620 RHS.get()->getType()->isVectorType()) { 10621 QualType compType = CheckVectorOperands( 10622 LHS, RHS, Loc, CompLHSTy, 10623 /*AllowBothBool*/getLangOpts().AltiVec, 10624 /*AllowBoolConversions*/getLangOpts().ZVector); 10625 if (CompLHSTy) *CompLHSTy = compType; 10626 return compType; 10627 } 10628 10629 if (LHS.get()->getType()->isConstantMatrixType() || 10630 RHS.get()->getType()->isConstantMatrixType()) { 10631 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10632 } 10633 10634 QualType compType = UsualArithmeticConversions( 10635 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10636 if (LHS.isInvalid() || RHS.isInvalid()) 10637 return QualType(); 10638 10639 // Enforce type constraints: C99 6.5.6p3. 10640 10641 // Handle the common case first (both operands are arithmetic). 10642 if (!compType.isNull() && compType->isArithmeticType()) { 10643 if (CompLHSTy) *CompLHSTy = compType; 10644 return compType; 10645 } 10646 10647 // Either ptr - int or ptr - ptr. 10648 if (LHS.get()->getType()->isAnyPointerType()) { 10649 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10650 10651 // Diagnose bad cases where we step over interface counts. 10652 if (LHS.get()->getType()->isObjCObjectPointerType() && 10653 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10654 return QualType(); 10655 10656 // The result type of a pointer-int computation is the pointer type. 10657 if (RHS.get()->getType()->isIntegerType()) { 10658 // Subtracting from a null pointer should produce a warning. 10659 // The last argument to the diagnose call says this doesn't match the 10660 // GNU int-to-pointer idiom. 10661 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10662 Expr::NPC_ValueDependentIsNotNull)) { 10663 // In C++ adding zero to a null pointer is defined. 10664 Expr::EvalResult KnownVal; 10665 if (!getLangOpts().CPlusPlus || 10666 (!RHS.get()->isValueDependent() && 10667 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10668 KnownVal.Val.getInt() != 0))) { 10669 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10670 } 10671 } 10672 10673 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10674 return QualType(); 10675 10676 // Check array bounds for pointer arithemtic 10677 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10678 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10679 10680 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10681 return LHS.get()->getType(); 10682 } 10683 10684 // Handle pointer-pointer subtractions. 10685 if (const PointerType *RHSPTy 10686 = RHS.get()->getType()->getAs<PointerType>()) { 10687 QualType rpointee = RHSPTy->getPointeeType(); 10688 10689 if (getLangOpts().CPlusPlus) { 10690 // Pointee types must be the same: C++ [expr.add] 10691 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10692 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10693 } 10694 } else { 10695 // Pointee types must be compatible C99 6.5.6p3 10696 if (!Context.typesAreCompatible( 10697 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10698 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10699 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10700 return QualType(); 10701 } 10702 } 10703 10704 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10705 LHS.get(), RHS.get())) 10706 return QualType(); 10707 10708 // FIXME: Add warnings for nullptr - ptr. 10709 10710 // The pointee type may have zero size. As an extension, a structure or 10711 // union may have zero size or an array may have zero length. In this 10712 // case subtraction does not make sense. 10713 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10714 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10715 if (ElementSize.isZero()) { 10716 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10717 << rpointee.getUnqualifiedType() 10718 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10719 } 10720 } 10721 10722 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10723 return Context.getPointerDiffType(); 10724 } 10725 } 10726 10727 return InvalidOperands(Loc, LHS, RHS); 10728 } 10729 10730 static bool isScopedEnumerationType(QualType T) { 10731 if (const EnumType *ET = T->getAs<EnumType>()) 10732 return ET->getDecl()->isScoped(); 10733 return false; 10734 } 10735 10736 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10737 SourceLocation Loc, BinaryOperatorKind Opc, 10738 QualType LHSType) { 10739 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10740 // so skip remaining warnings as we don't want to modify values within Sema. 10741 if (S.getLangOpts().OpenCL) 10742 return; 10743 10744 // Check right/shifter operand 10745 Expr::EvalResult RHSResult; 10746 if (RHS.get()->isValueDependent() || 10747 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10748 return; 10749 llvm::APSInt Right = RHSResult.Val.getInt(); 10750 10751 if (Right.isNegative()) { 10752 S.DiagRuntimeBehavior(Loc, RHS.get(), 10753 S.PDiag(diag::warn_shift_negative) 10754 << RHS.get()->getSourceRange()); 10755 return; 10756 } 10757 10758 QualType LHSExprType = LHS.get()->getType(); 10759 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10760 if (LHSExprType->isExtIntType()) 10761 LeftSize = S.Context.getIntWidth(LHSExprType); 10762 else if (LHSExprType->isFixedPointType()) { 10763 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10764 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10765 } 10766 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10767 if (Right.uge(LeftBits)) { 10768 S.DiagRuntimeBehavior(Loc, RHS.get(), 10769 S.PDiag(diag::warn_shift_gt_typewidth) 10770 << RHS.get()->getSourceRange()); 10771 return; 10772 } 10773 10774 // FIXME: We probably need to handle fixed point types specially here. 10775 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10776 return; 10777 10778 // When left shifting an ICE which is signed, we can check for overflow which 10779 // according to C++ standards prior to C++2a has undefined behavior 10780 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10781 // more than the maximum value representable in the result type, so never 10782 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10783 // expression is still probably a bug.) 10784 Expr::EvalResult LHSResult; 10785 if (LHS.get()->isValueDependent() || 10786 LHSType->hasUnsignedIntegerRepresentation() || 10787 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10788 return; 10789 llvm::APSInt Left = LHSResult.Val.getInt(); 10790 10791 // If LHS does not have a signed type and non-negative value 10792 // then, the behavior is undefined before C++2a. Warn about it. 10793 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10794 !S.getLangOpts().CPlusPlus20) { 10795 S.DiagRuntimeBehavior(Loc, LHS.get(), 10796 S.PDiag(diag::warn_shift_lhs_negative) 10797 << LHS.get()->getSourceRange()); 10798 return; 10799 } 10800 10801 llvm::APInt ResultBits = 10802 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10803 if (LeftBits.uge(ResultBits)) 10804 return; 10805 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10806 Result = Result.shl(Right); 10807 10808 // Print the bit representation of the signed integer as an unsigned 10809 // hexadecimal number. 10810 SmallString<40> HexResult; 10811 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10812 10813 // If we are only missing a sign bit, this is less likely to result in actual 10814 // bugs -- if the result is cast back to an unsigned type, it will have the 10815 // expected value. Thus we place this behind a different warning that can be 10816 // turned off separately if needed. 10817 if (LeftBits == ResultBits - 1) { 10818 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10819 << HexResult << LHSType 10820 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10821 return; 10822 } 10823 10824 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10825 << HexResult.str() << Result.getMinSignedBits() << LHSType 10826 << Left.getBitWidth() << LHS.get()->getSourceRange() 10827 << RHS.get()->getSourceRange(); 10828 } 10829 10830 /// Return the resulting type when a vector is shifted 10831 /// by a scalar or vector shift amount. 10832 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10833 SourceLocation Loc, bool IsCompAssign) { 10834 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10835 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10836 !LHS.get()->getType()->isVectorType()) { 10837 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10838 << RHS.get()->getType() << LHS.get()->getType() 10839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10840 return QualType(); 10841 } 10842 10843 if (!IsCompAssign) { 10844 LHS = S.UsualUnaryConversions(LHS.get()); 10845 if (LHS.isInvalid()) return QualType(); 10846 } 10847 10848 RHS = S.UsualUnaryConversions(RHS.get()); 10849 if (RHS.isInvalid()) return QualType(); 10850 10851 QualType LHSType = LHS.get()->getType(); 10852 // Note that LHS might be a scalar because the routine calls not only in 10853 // OpenCL case. 10854 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10855 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10856 10857 // Note that RHS might not be a vector. 10858 QualType RHSType = RHS.get()->getType(); 10859 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10860 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10861 10862 // The operands need to be integers. 10863 if (!LHSEleType->isIntegerType()) { 10864 S.Diag(Loc, diag::err_typecheck_expect_int) 10865 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10866 return QualType(); 10867 } 10868 10869 if (!RHSEleType->isIntegerType()) { 10870 S.Diag(Loc, diag::err_typecheck_expect_int) 10871 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10872 return QualType(); 10873 } 10874 10875 if (!LHSVecTy) { 10876 assert(RHSVecTy); 10877 if (IsCompAssign) 10878 return RHSType; 10879 if (LHSEleType != RHSEleType) { 10880 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10881 LHSEleType = RHSEleType; 10882 } 10883 QualType VecTy = 10884 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10885 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10886 LHSType = VecTy; 10887 } else if (RHSVecTy) { 10888 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10889 // are applied component-wise. So if RHS is a vector, then ensure 10890 // that the number of elements is the same as LHS... 10891 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10892 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10893 << LHS.get()->getType() << RHS.get()->getType() 10894 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10895 return QualType(); 10896 } 10897 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10898 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10899 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10900 if (LHSBT != RHSBT && 10901 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10902 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10903 << LHS.get()->getType() << RHS.get()->getType() 10904 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10905 } 10906 } 10907 } else { 10908 // ...else expand RHS to match the number of elements in LHS. 10909 QualType VecTy = 10910 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10911 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10912 } 10913 10914 return LHSType; 10915 } 10916 10917 // C99 6.5.7 10918 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10919 SourceLocation Loc, BinaryOperatorKind Opc, 10920 bool IsCompAssign) { 10921 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10922 10923 // Vector shifts promote their scalar inputs to vector type. 10924 if (LHS.get()->getType()->isVectorType() || 10925 RHS.get()->getType()->isVectorType()) { 10926 if (LangOpts.ZVector) { 10927 // The shift operators for the z vector extensions work basically 10928 // like general shifts, except that neither the LHS nor the RHS is 10929 // allowed to be a "vector bool". 10930 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10931 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10932 return InvalidOperands(Loc, LHS, RHS); 10933 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10934 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10935 return InvalidOperands(Loc, LHS, RHS); 10936 } 10937 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10938 } 10939 10940 // Shifts don't perform usual arithmetic conversions, they just do integer 10941 // promotions on each operand. C99 6.5.7p3 10942 10943 // For the LHS, do usual unary conversions, but then reset them away 10944 // if this is a compound assignment. 10945 ExprResult OldLHS = LHS; 10946 LHS = UsualUnaryConversions(LHS.get()); 10947 if (LHS.isInvalid()) 10948 return QualType(); 10949 QualType LHSType = LHS.get()->getType(); 10950 if (IsCompAssign) LHS = OldLHS; 10951 10952 // The RHS is simpler. 10953 RHS = UsualUnaryConversions(RHS.get()); 10954 if (RHS.isInvalid()) 10955 return QualType(); 10956 QualType RHSType = RHS.get()->getType(); 10957 10958 // C99 6.5.7p2: Each of the operands shall have integer type. 10959 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10960 if ((!LHSType->isFixedPointOrIntegerType() && 10961 !LHSType->hasIntegerRepresentation()) || 10962 !RHSType->hasIntegerRepresentation()) 10963 return InvalidOperands(Loc, LHS, RHS); 10964 10965 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10966 // hasIntegerRepresentation() above instead of this. 10967 if (isScopedEnumerationType(LHSType) || 10968 isScopedEnumerationType(RHSType)) { 10969 return InvalidOperands(Loc, LHS, RHS); 10970 } 10971 // Sanity-check shift operands 10972 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10973 10974 // "The type of the result is that of the promoted left operand." 10975 return LHSType; 10976 } 10977 10978 /// Diagnose bad pointer comparisons. 10979 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10980 ExprResult &LHS, ExprResult &RHS, 10981 bool IsError) { 10982 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10983 : diag::ext_typecheck_comparison_of_distinct_pointers) 10984 << LHS.get()->getType() << RHS.get()->getType() 10985 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10986 } 10987 10988 /// Returns false if the pointers are converted to a composite type, 10989 /// true otherwise. 10990 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10991 ExprResult &LHS, ExprResult &RHS) { 10992 // C++ [expr.rel]p2: 10993 // [...] Pointer conversions (4.10) and qualification 10994 // conversions (4.4) are performed on pointer operands (or on 10995 // a pointer operand and a null pointer constant) to bring 10996 // them to their composite pointer type. [...] 10997 // 10998 // C++ [expr.eq]p1 uses the same notion for (in)equality 10999 // comparisons of pointers. 11000 11001 QualType LHSType = LHS.get()->getType(); 11002 QualType RHSType = RHS.get()->getType(); 11003 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11004 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11005 11006 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11007 if (T.isNull()) { 11008 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11009 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11010 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11011 else 11012 S.InvalidOperands(Loc, LHS, RHS); 11013 return true; 11014 } 11015 11016 return false; 11017 } 11018 11019 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11020 ExprResult &LHS, 11021 ExprResult &RHS, 11022 bool IsError) { 11023 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11024 : diag::ext_typecheck_comparison_of_fptr_to_void) 11025 << LHS.get()->getType() << RHS.get()->getType() 11026 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11027 } 11028 11029 static bool isObjCObjectLiteral(ExprResult &E) { 11030 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11031 case Stmt::ObjCArrayLiteralClass: 11032 case Stmt::ObjCDictionaryLiteralClass: 11033 case Stmt::ObjCStringLiteralClass: 11034 case Stmt::ObjCBoxedExprClass: 11035 return true; 11036 default: 11037 // Note that ObjCBoolLiteral is NOT an object literal! 11038 return false; 11039 } 11040 } 11041 11042 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11043 const ObjCObjectPointerType *Type = 11044 LHS->getType()->getAs<ObjCObjectPointerType>(); 11045 11046 // If this is not actually an Objective-C object, bail out. 11047 if (!Type) 11048 return false; 11049 11050 // Get the LHS object's interface type. 11051 QualType InterfaceType = Type->getPointeeType(); 11052 11053 // If the RHS isn't an Objective-C object, bail out. 11054 if (!RHS->getType()->isObjCObjectPointerType()) 11055 return false; 11056 11057 // Try to find the -isEqual: method. 11058 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11059 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11060 InterfaceType, 11061 /*IsInstance=*/true); 11062 if (!Method) { 11063 if (Type->isObjCIdType()) { 11064 // For 'id', just check the global pool. 11065 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11066 /*receiverId=*/true); 11067 } else { 11068 // Check protocols. 11069 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11070 /*IsInstance=*/true); 11071 } 11072 } 11073 11074 if (!Method) 11075 return false; 11076 11077 QualType T = Method->parameters()[0]->getType(); 11078 if (!T->isObjCObjectPointerType()) 11079 return false; 11080 11081 QualType R = Method->getReturnType(); 11082 if (!R->isScalarType()) 11083 return false; 11084 11085 return true; 11086 } 11087 11088 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11089 FromE = FromE->IgnoreParenImpCasts(); 11090 switch (FromE->getStmtClass()) { 11091 default: 11092 break; 11093 case Stmt::ObjCStringLiteralClass: 11094 // "string literal" 11095 return LK_String; 11096 case Stmt::ObjCArrayLiteralClass: 11097 // "array literal" 11098 return LK_Array; 11099 case Stmt::ObjCDictionaryLiteralClass: 11100 // "dictionary literal" 11101 return LK_Dictionary; 11102 case Stmt::BlockExprClass: 11103 return LK_Block; 11104 case Stmt::ObjCBoxedExprClass: { 11105 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11106 switch (Inner->getStmtClass()) { 11107 case Stmt::IntegerLiteralClass: 11108 case Stmt::FloatingLiteralClass: 11109 case Stmt::CharacterLiteralClass: 11110 case Stmt::ObjCBoolLiteralExprClass: 11111 case Stmt::CXXBoolLiteralExprClass: 11112 // "numeric literal" 11113 return LK_Numeric; 11114 case Stmt::ImplicitCastExprClass: { 11115 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11116 // Boolean literals can be represented by implicit casts. 11117 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11118 return LK_Numeric; 11119 break; 11120 } 11121 default: 11122 break; 11123 } 11124 return LK_Boxed; 11125 } 11126 } 11127 return LK_None; 11128 } 11129 11130 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11131 ExprResult &LHS, ExprResult &RHS, 11132 BinaryOperator::Opcode Opc){ 11133 Expr *Literal; 11134 Expr *Other; 11135 if (isObjCObjectLiteral(LHS)) { 11136 Literal = LHS.get(); 11137 Other = RHS.get(); 11138 } else { 11139 Literal = RHS.get(); 11140 Other = LHS.get(); 11141 } 11142 11143 // Don't warn on comparisons against nil. 11144 Other = Other->IgnoreParenCasts(); 11145 if (Other->isNullPointerConstant(S.getASTContext(), 11146 Expr::NPC_ValueDependentIsNotNull)) 11147 return; 11148 11149 // This should be kept in sync with warn_objc_literal_comparison. 11150 // LK_String should always be after the other literals, since it has its own 11151 // warning flag. 11152 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11153 assert(LiteralKind != Sema::LK_Block); 11154 if (LiteralKind == Sema::LK_None) { 11155 llvm_unreachable("Unknown Objective-C object literal kind"); 11156 } 11157 11158 if (LiteralKind == Sema::LK_String) 11159 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11160 << Literal->getSourceRange(); 11161 else 11162 S.Diag(Loc, diag::warn_objc_literal_comparison) 11163 << LiteralKind << Literal->getSourceRange(); 11164 11165 if (BinaryOperator::isEqualityOp(Opc) && 11166 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11167 SourceLocation Start = LHS.get()->getBeginLoc(); 11168 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11169 CharSourceRange OpRange = 11170 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11171 11172 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11173 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11174 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11175 << FixItHint::CreateInsertion(End, "]"); 11176 } 11177 } 11178 11179 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11180 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11181 ExprResult &RHS, SourceLocation Loc, 11182 BinaryOperatorKind Opc) { 11183 // Check that left hand side is !something. 11184 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11185 if (!UO || UO->getOpcode() != UO_LNot) return; 11186 11187 // Only check if the right hand side is non-bool arithmetic type. 11188 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11189 11190 // Make sure that the something in !something is not bool. 11191 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11192 if (SubExpr->isKnownToHaveBooleanValue()) return; 11193 11194 // Emit warning. 11195 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11196 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11197 << Loc << IsBitwiseOp; 11198 11199 // First note suggest !(x < y) 11200 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11201 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11202 FirstClose = S.getLocForEndOfToken(FirstClose); 11203 if (FirstClose.isInvalid()) 11204 FirstOpen = SourceLocation(); 11205 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11206 << IsBitwiseOp 11207 << FixItHint::CreateInsertion(FirstOpen, "(") 11208 << FixItHint::CreateInsertion(FirstClose, ")"); 11209 11210 // Second note suggests (!x) < y 11211 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11212 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11213 SecondClose = S.getLocForEndOfToken(SecondClose); 11214 if (SecondClose.isInvalid()) 11215 SecondOpen = SourceLocation(); 11216 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11217 << FixItHint::CreateInsertion(SecondOpen, "(") 11218 << FixItHint::CreateInsertion(SecondClose, ")"); 11219 } 11220 11221 // Returns true if E refers to a non-weak array. 11222 static bool checkForArray(const Expr *E) { 11223 const ValueDecl *D = nullptr; 11224 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11225 D = DR->getDecl(); 11226 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11227 if (Mem->isImplicitAccess()) 11228 D = Mem->getMemberDecl(); 11229 } 11230 if (!D) 11231 return false; 11232 return D->getType()->isArrayType() && !D->isWeak(); 11233 } 11234 11235 /// Diagnose some forms of syntactically-obvious tautological comparison. 11236 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11237 Expr *LHS, Expr *RHS, 11238 BinaryOperatorKind Opc) { 11239 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11240 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11241 11242 QualType LHSType = LHS->getType(); 11243 QualType RHSType = RHS->getType(); 11244 if (LHSType->hasFloatingRepresentation() || 11245 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11246 S.inTemplateInstantiation()) 11247 return; 11248 11249 // Comparisons between two array types are ill-formed for operator<=>, so 11250 // we shouldn't emit any additional warnings about it. 11251 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11252 return; 11253 11254 // For non-floating point types, check for self-comparisons of the form 11255 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11256 // often indicate logic errors in the program. 11257 // 11258 // NOTE: Don't warn about comparison expressions resulting from macro 11259 // expansion. Also don't warn about comparisons which are only self 11260 // comparisons within a template instantiation. The warnings should catch 11261 // obvious cases in the definition of the template anyways. The idea is to 11262 // warn when the typed comparison operator will always evaluate to the same 11263 // result. 11264 11265 // Used for indexing into %select in warn_comparison_always 11266 enum { 11267 AlwaysConstant, 11268 AlwaysTrue, 11269 AlwaysFalse, 11270 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11271 }; 11272 11273 // C++2a [depr.array.comp]: 11274 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11275 // operands of array type are deprecated. 11276 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11277 RHSStripped->getType()->isArrayType()) { 11278 S.Diag(Loc, diag::warn_depr_array_comparison) 11279 << LHS->getSourceRange() << RHS->getSourceRange() 11280 << LHSStripped->getType() << RHSStripped->getType(); 11281 // Carry on to produce the tautological comparison warning, if this 11282 // expression is potentially-evaluated, we can resolve the array to a 11283 // non-weak declaration, and so on. 11284 } 11285 11286 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11287 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11288 unsigned Result; 11289 switch (Opc) { 11290 case BO_EQ: 11291 case BO_LE: 11292 case BO_GE: 11293 Result = AlwaysTrue; 11294 break; 11295 case BO_NE: 11296 case BO_LT: 11297 case BO_GT: 11298 Result = AlwaysFalse; 11299 break; 11300 case BO_Cmp: 11301 Result = AlwaysEqual; 11302 break; 11303 default: 11304 Result = AlwaysConstant; 11305 break; 11306 } 11307 S.DiagRuntimeBehavior(Loc, nullptr, 11308 S.PDiag(diag::warn_comparison_always) 11309 << 0 /*self-comparison*/ 11310 << Result); 11311 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11312 // What is it always going to evaluate to? 11313 unsigned Result; 11314 switch (Opc) { 11315 case BO_EQ: // e.g. array1 == array2 11316 Result = AlwaysFalse; 11317 break; 11318 case BO_NE: // e.g. array1 != array2 11319 Result = AlwaysTrue; 11320 break; 11321 default: // e.g. array1 <= array2 11322 // The best we can say is 'a constant' 11323 Result = AlwaysConstant; 11324 break; 11325 } 11326 S.DiagRuntimeBehavior(Loc, nullptr, 11327 S.PDiag(diag::warn_comparison_always) 11328 << 1 /*array comparison*/ 11329 << Result); 11330 } 11331 } 11332 11333 if (isa<CastExpr>(LHSStripped)) 11334 LHSStripped = LHSStripped->IgnoreParenCasts(); 11335 if (isa<CastExpr>(RHSStripped)) 11336 RHSStripped = RHSStripped->IgnoreParenCasts(); 11337 11338 // Warn about comparisons against a string constant (unless the other 11339 // operand is null); the user probably wants string comparison function. 11340 Expr *LiteralString = nullptr; 11341 Expr *LiteralStringStripped = nullptr; 11342 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11343 !RHSStripped->isNullPointerConstant(S.Context, 11344 Expr::NPC_ValueDependentIsNull)) { 11345 LiteralString = LHS; 11346 LiteralStringStripped = LHSStripped; 11347 } else if ((isa<StringLiteral>(RHSStripped) || 11348 isa<ObjCEncodeExpr>(RHSStripped)) && 11349 !LHSStripped->isNullPointerConstant(S.Context, 11350 Expr::NPC_ValueDependentIsNull)) { 11351 LiteralString = RHS; 11352 LiteralStringStripped = RHSStripped; 11353 } 11354 11355 if (LiteralString) { 11356 S.DiagRuntimeBehavior(Loc, nullptr, 11357 S.PDiag(diag::warn_stringcompare) 11358 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11359 << LiteralString->getSourceRange()); 11360 } 11361 } 11362 11363 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11364 switch (CK) { 11365 default: { 11366 #ifndef NDEBUG 11367 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11368 << "\n"; 11369 #endif 11370 llvm_unreachable("unhandled cast kind"); 11371 } 11372 case CK_UserDefinedConversion: 11373 return ICK_Identity; 11374 case CK_LValueToRValue: 11375 return ICK_Lvalue_To_Rvalue; 11376 case CK_ArrayToPointerDecay: 11377 return ICK_Array_To_Pointer; 11378 case CK_FunctionToPointerDecay: 11379 return ICK_Function_To_Pointer; 11380 case CK_IntegralCast: 11381 return ICK_Integral_Conversion; 11382 case CK_FloatingCast: 11383 return ICK_Floating_Conversion; 11384 case CK_IntegralToFloating: 11385 case CK_FloatingToIntegral: 11386 return ICK_Floating_Integral; 11387 case CK_IntegralComplexCast: 11388 case CK_FloatingComplexCast: 11389 case CK_FloatingComplexToIntegralComplex: 11390 case CK_IntegralComplexToFloatingComplex: 11391 return ICK_Complex_Conversion; 11392 case CK_FloatingComplexToReal: 11393 case CK_FloatingRealToComplex: 11394 case CK_IntegralComplexToReal: 11395 case CK_IntegralRealToComplex: 11396 return ICK_Complex_Real; 11397 } 11398 } 11399 11400 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11401 QualType FromType, 11402 SourceLocation Loc) { 11403 // Check for a narrowing implicit conversion. 11404 StandardConversionSequence SCS; 11405 SCS.setAsIdentityConversion(); 11406 SCS.setToType(0, FromType); 11407 SCS.setToType(1, ToType); 11408 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11409 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11410 11411 APValue PreNarrowingValue; 11412 QualType PreNarrowingType; 11413 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11414 PreNarrowingType, 11415 /*IgnoreFloatToIntegralConversion*/ true)) { 11416 case NK_Dependent_Narrowing: 11417 // Implicit conversion to a narrower type, but the expression is 11418 // value-dependent so we can't tell whether it's actually narrowing. 11419 case NK_Not_Narrowing: 11420 return false; 11421 11422 case NK_Constant_Narrowing: 11423 // Implicit conversion to a narrower type, and the value is not a constant 11424 // expression. 11425 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11426 << /*Constant*/ 1 11427 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11428 return true; 11429 11430 case NK_Variable_Narrowing: 11431 // Implicit conversion to a narrower type, and the value is not a constant 11432 // expression. 11433 case NK_Type_Narrowing: 11434 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11435 << /*Constant*/ 0 << FromType << ToType; 11436 // TODO: It's not a constant expression, but what if the user intended it 11437 // to be? Can we produce notes to help them figure out why it isn't? 11438 return true; 11439 } 11440 llvm_unreachable("unhandled case in switch"); 11441 } 11442 11443 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11444 ExprResult &LHS, 11445 ExprResult &RHS, 11446 SourceLocation Loc) { 11447 QualType LHSType = LHS.get()->getType(); 11448 QualType RHSType = RHS.get()->getType(); 11449 // Dig out the original argument type and expression before implicit casts 11450 // were applied. These are the types/expressions we need to check the 11451 // [expr.spaceship] requirements against. 11452 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11453 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11454 QualType LHSStrippedType = LHSStripped.get()->getType(); 11455 QualType RHSStrippedType = RHSStripped.get()->getType(); 11456 11457 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11458 // other is not, the program is ill-formed. 11459 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11460 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11461 return QualType(); 11462 } 11463 11464 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11465 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11466 RHSStrippedType->isEnumeralType(); 11467 if (NumEnumArgs == 1) { 11468 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11469 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11470 if (OtherTy->hasFloatingRepresentation()) { 11471 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11472 return QualType(); 11473 } 11474 } 11475 if (NumEnumArgs == 2) { 11476 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11477 // type E, the operator yields the result of converting the operands 11478 // to the underlying type of E and applying <=> to the converted operands. 11479 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11480 S.InvalidOperands(Loc, LHS, RHS); 11481 return QualType(); 11482 } 11483 QualType IntType = 11484 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11485 assert(IntType->isArithmeticType()); 11486 11487 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11488 // promote the boolean type, and all other promotable integer types, to 11489 // avoid this. 11490 if (IntType->isPromotableIntegerType()) 11491 IntType = S.Context.getPromotedIntegerType(IntType); 11492 11493 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11494 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11495 LHSType = RHSType = IntType; 11496 } 11497 11498 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11499 // usual arithmetic conversions are applied to the operands. 11500 QualType Type = 11501 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11502 if (LHS.isInvalid() || RHS.isInvalid()) 11503 return QualType(); 11504 if (Type.isNull()) 11505 return S.InvalidOperands(Loc, LHS, RHS); 11506 11507 Optional<ComparisonCategoryType> CCT = 11508 getComparisonCategoryForBuiltinCmp(Type); 11509 if (!CCT) 11510 return S.InvalidOperands(Loc, LHS, RHS); 11511 11512 bool HasNarrowing = checkThreeWayNarrowingConversion( 11513 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11514 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11515 RHS.get()->getBeginLoc()); 11516 if (HasNarrowing) 11517 return QualType(); 11518 11519 assert(!Type.isNull() && "composite type for <=> has not been set"); 11520 11521 return S.CheckComparisonCategoryType( 11522 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11523 } 11524 11525 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11526 ExprResult &RHS, 11527 SourceLocation Loc, 11528 BinaryOperatorKind Opc) { 11529 if (Opc == BO_Cmp) 11530 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11531 11532 // C99 6.5.8p3 / C99 6.5.9p4 11533 QualType Type = 11534 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11535 if (LHS.isInvalid() || RHS.isInvalid()) 11536 return QualType(); 11537 if (Type.isNull()) 11538 return S.InvalidOperands(Loc, LHS, RHS); 11539 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11540 11541 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11542 return S.InvalidOperands(Loc, LHS, RHS); 11543 11544 // Check for comparisons of floating point operands using != and ==. 11545 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11546 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11547 11548 // The result of comparisons is 'bool' in C++, 'int' in C. 11549 return S.Context.getLogicalOperationType(); 11550 } 11551 11552 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11553 if (!NullE.get()->getType()->isAnyPointerType()) 11554 return; 11555 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11556 if (!E.get()->getType()->isAnyPointerType() && 11557 E.get()->isNullPointerConstant(Context, 11558 Expr::NPC_ValueDependentIsNotNull) == 11559 Expr::NPCK_ZeroExpression) { 11560 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11561 if (CL->getValue() == 0) 11562 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11563 << NullValue 11564 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11565 NullValue ? "NULL" : "(void *)0"); 11566 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11567 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11568 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11569 if (T == Context.CharTy) 11570 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11571 << NullValue 11572 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11573 NullValue ? "NULL" : "(void *)0"); 11574 } 11575 } 11576 } 11577 11578 // C99 6.5.8, C++ [expr.rel] 11579 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11580 SourceLocation Loc, 11581 BinaryOperatorKind Opc) { 11582 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11583 bool IsThreeWay = Opc == BO_Cmp; 11584 bool IsOrdered = IsRelational || IsThreeWay; 11585 auto IsAnyPointerType = [](ExprResult E) { 11586 QualType Ty = E.get()->getType(); 11587 return Ty->isPointerType() || Ty->isMemberPointerType(); 11588 }; 11589 11590 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11591 // type, array-to-pointer, ..., conversions are performed on both operands to 11592 // bring them to their composite type. 11593 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11594 // any type-related checks. 11595 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11596 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11597 if (LHS.isInvalid()) 11598 return QualType(); 11599 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11600 if (RHS.isInvalid()) 11601 return QualType(); 11602 } else { 11603 LHS = DefaultLvalueConversion(LHS.get()); 11604 if (LHS.isInvalid()) 11605 return QualType(); 11606 RHS = DefaultLvalueConversion(RHS.get()); 11607 if (RHS.isInvalid()) 11608 return QualType(); 11609 } 11610 11611 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11612 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11613 CheckPtrComparisonWithNullChar(LHS, RHS); 11614 CheckPtrComparisonWithNullChar(RHS, LHS); 11615 } 11616 11617 // Handle vector comparisons separately. 11618 if (LHS.get()->getType()->isVectorType() || 11619 RHS.get()->getType()->isVectorType()) 11620 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11621 11622 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11623 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11624 11625 QualType LHSType = LHS.get()->getType(); 11626 QualType RHSType = RHS.get()->getType(); 11627 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11628 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11629 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11630 11631 const Expr::NullPointerConstantKind LHSNullKind = 11632 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11633 const Expr::NullPointerConstantKind RHSNullKind = 11634 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11635 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11636 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11637 11638 auto computeResultTy = [&]() { 11639 if (Opc != BO_Cmp) 11640 return Context.getLogicalOperationType(); 11641 assert(getLangOpts().CPlusPlus); 11642 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11643 11644 QualType CompositeTy = LHS.get()->getType(); 11645 assert(!CompositeTy->isReferenceType()); 11646 11647 Optional<ComparisonCategoryType> CCT = 11648 getComparisonCategoryForBuiltinCmp(CompositeTy); 11649 if (!CCT) 11650 return InvalidOperands(Loc, LHS, RHS); 11651 11652 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11653 // P0946R0: Comparisons between a null pointer constant and an object 11654 // pointer result in std::strong_equality, which is ill-formed under 11655 // P1959R0. 11656 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11657 << (LHSIsNull ? LHS.get()->getSourceRange() 11658 : RHS.get()->getSourceRange()); 11659 return QualType(); 11660 } 11661 11662 return CheckComparisonCategoryType( 11663 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11664 }; 11665 11666 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11667 bool IsEquality = Opc == BO_EQ; 11668 if (RHSIsNull) 11669 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11670 RHS.get()->getSourceRange()); 11671 else 11672 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11673 LHS.get()->getSourceRange()); 11674 } 11675 11676 if ((LHSType->isIntegerType() && !LHSIsNull) || 11677 (RHSType->isIntegerType() && !RHSIsNull)) { 11678 // Skip normal pointer conversion checks in this case; we have better 11679 // diagnostics for this below. 11680 } else if (getLangOpts().CPlusPlus) { 11681 // Equality comparison of a function pointer to a void pointer is invalid, 11682 // but we allow it as an extension. 11683 // FIXME: If we really want to allow this, should it be part of composite 11684 // pointer type computation so it works in conditionals too? 11685 if (!IsOrdered && 11686 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11687 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11688 // This is a gcc extension compatibility comparison. 11689 // In a SFINAE context, we treat this as a hard error to maintain 11690 // conformance with the C++ standard. 11691 diagnoseFunctionPointerToVoidComparison( 11692 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11693 11694 if (isSFINAEContext()) 11695 return QualType(); 11696 11697 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11698 return computeResultTy(); 11699 } 11700 11701 // C++ [expr.eq]p2: 11702 // If at least one operand is a pointer [...] bring them to their 11703 // composite pointer type. 11704 // C++ [expr.spaceship]p6 11705 // If at least one of the operands is of pointer type, [...] bring them 11706 // to their composite pointer type. 11707 // C++ [expr.rel]p2: 11708 // If both operands are pointers, [...] bring them to their composite 11709 // pointer type. 11710 // For <=>, the only valid non-pointer types are arrays and functions, and 11711 // we already decayed those, so this is really the same as the relational 11712 // comparison rule. 11713 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11714 (IsOrdered ? 2 : 1) && 11715 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11716 RHSType->isObjCObjectPointerType()))) { 11717 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11718 return QualType(); 11719 return computeResultTy(); 11720 } 11721 } else if (LHSType->isPointerType() && 11722 RHSType->isPointerType()) { // C99 6.5.8p2 11723 // All of the following pointer-related warnings are GCC extensions, except 11724 // when handling null pointer constants. 11725 QualType LCanPointeeTy = 11726 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11727 QualType RCanPointeeTy = 11728 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11729 11730 // C99 6.5.9p2 and C99 6.5.8p2 11731 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11732 RCanPointeeTy.getUnqualifiedType())) { 11733 if (IsRelational) { 11734 // Pointers both need to point to complete or incomplete types 11735 if ((LCanPointeeTy->isIncompleteType() != 11736 RCanPointeeTy->isIncompleteType()) && 11737 !getLangOpts().C11) { 11738 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11740 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11741 << RCanPointeeTy->isIncompleteType(); 11742 } 11743 if (LCanPointeeTy->isFunctionType()) { 11744 // Valid unless a relational comparison of function pointers 11745 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11746 << LHSType << RHSType << LHS.get()->getSourceRange() 11747 << RHS.get()->getSourceRange(); 11748 } 11749 } 11750 } else if (!IsRelational && 11751 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11752 // Valid unless comparison between non-null pointer and function pointer 11753 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11754 && !LHSIsNull && !RHSIsNull) 11755 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11756 /*isError*/false); 11757 } else { 11758 // Invalid 11759 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11760 } 11761 if (LCanPointeeTy != RCanPointeeTy) { 11762 // Treat NULL constant as a special case in OpenCL. 11763 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11764 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11765 Diag(Loc, 11766 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11767 << LHSType << RHSType << 0 /* comparison */ 11768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11769 } 11770 } 11771 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11772 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11773 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11774 : CK_BitCast; 11775 if (LHSIsNull && !RHSIsNull) 11776 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11777 else 11778 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11779 } 11780 return computeResultTy(); 11781 } 11782 11783 if (getLangOpts().CPlusPlus) { 11784 // C++ [expr.eq]p4: 11785 // Two operands of type std::nullptr_t or one operand of type 11786 // std::nullptr_t and the other a null pointer constant compare equal. 11787 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11788 if (LHSType->isNullPtrType()) { 11789 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11790 return computeResultTy(); 11791 } 11792 if (RHSType->isNullPtrType()) { 11793 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11794 return computeResultTy(); 11795 } 11796 } 11797 11798 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11799 // These aren't covered by the composite pointer type rules. 11800 if (!IsOrdered && RHSType->isNullPtrType() && 11801 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11802 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11803 return computeResultTy(); 11804 } 11805 if (!IsOrdered && LHSType->isNullPtrType() && 11806 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11807 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11808 return computeResultTy(); 11809 } 11810 11811 if (IsRelational && 11812 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11813 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11814 // HACK: Relational comparison of nullptr_t against a pointer type is 11815 // invalid per DR583, but we allow it within std::less<> and friends, 11816 // since otherwise common uses of it break. 11817 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11818 // friends to have std::nullptr_t overload candidates. 11819 DeclContext *DC = CurContext; 11820 if (isa<FunctionDecl>(DC)) 11821 DC = DC->getParent(); 11822 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11823 if (CTSD->isInStdNamespace() && 11824 llvm::StringSwitch<bool>(CTSD->getName()) 11825 .Cases("less", "less_equal", "greater", "greater_equal", true) 11826 .Default(false)) { 11827 if (RHSType->isNullPtrType()) 11828 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11829 else 11830 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11831 return computeResultTy(); 11832 } 11833 } 11834 } 11835 11836 // C++ [expr.eq]p2: 11837 // If at least one operand is a pointer to member, [...] bring them to 11838 // their composite pointer type. 11839 if (!IsOrdered && 11840 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11841 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11842 return QualType(); 11843 else 11844 return computeResultTy(); 11845 } 11846 } 11847 11848 // Handle block pointer types. 11849 if (!IsOrdered && LHSType->isBlockPointerType() && 11850 RHSType->isBlockPointerType()) { 11851 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11852 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11853 11854 if (!LHSIsNull && !RHSIsNull && 11855 !Context.typesAreCompatible(lpointee, rpointee)) { 11856 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11857 << LHSType << RHSType << LHS.get()->getSourceRange() 11858 << RHS.get()->getSourceRange(); 11859 } 11860 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11861 return computeResultTy(); 11862 } 11863 11864 // Allow block pointers to be compared with null pointer constants. 11865 if (!IsOrdered 11866 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11867 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11868 if (!LHSIsNull && !RHSIsNull) { 11869 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11870 ->getPointeeType()->isVoidType()) 11871 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11872 ->getPointeeType()->isVoidType()))) 11873 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11874 << LHSType << RHSType << LHS.get()->getSourceRange() 11875 << RHS.get()->getSourceRange(); 11876 } 11877 if (LHSIsNull && !RHSIsNull) 11878 LHS = ImpCastExprToType(LHS.get(), RHSType, 11879 RHSType->isPointerType() ? CK_BitCast 11880 : CK_AnyPointerToBlockPointerCast); 11881 else 11882 RHS = ImpCastExprToType(RHS.get(), LHSType, 11883 LHSType->isPointerType() ? CK_BitCast 11884 : CK_AnyPointerToBlockPointerCast); 11885 return computeResultTy(); 11886 } 11887 11888 if (LHSType->isObjCObjectPointerType() || 11889 RHSType->isObjCObjectPointerType()) { 11890 const PointerType *LPT = LHSType->getAs<PointerType>(); 11891 const PointerType *RPT = RHSType->getAs<PointerType>(); 11892 if (LPT || RPT) { 11893 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11894 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11895 11896 if (!LPtrToVoid && !RPtrToVoid && 11897 !Context.typesAreCompatible(LHSType, RHSType)) { 11898 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11899 /*isError*/false); 11900 } 11901 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11902 // the RHS, but we have test coverage for this behavior. 11903 // FIXME: Consider using convertPointersToCompositeType in C++. 11904 if (LHSIsNull && !RHSIsNull) { 11905 Expr *E = LHS.get(); 11906 if (getLangOpts().ObjCAutoRefCount) 11907 CheckObjCConversion(SourceRange(), RHSType, E, 11908 CCK_ImplicitConversion); 11909 LHS = ImpCastExprToType(E, RHSType, 11910 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11911 } 11912 else { 11913 Expr *E = RHS.get(); 11914 if (getLangOpts().ObjCAutoRefCount) 11915 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11916 /*Diagnose=*/true, 11917 /*DiagnoseCFAudited=*/false, Opc); 11918 RHS = ImpCastExprToType(E, LHSType, 11919 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11920 } 11921 return computeResultTy(); 11922 } 11923 if (LHSType->isObjCObjectPointerType() && 11924 RHSType->isObjCObjectPointerType()) { 11925 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11926 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11927 /*isError*/false); 11928 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11929 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11930 11931 if (LHSIsNull && !RHSIsNull) 11932 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11933 else 11934 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11935 return computeResultTy(); 11936 } 11937 11938 if (!IsOrdered && LHSType->isBlockPointerType() && 11939 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11940 LHS = ImpCastExprToType(LHS.get(), RHSType, 11941 CK_BlockPointerToObjCPointerCast); 11942 return computeResultTy(); 11943 } else if (!IsOrdered && 11944 LHSType->isBlockCompatibleObjCPointerType(Context) && 11945 RHSType->isBlockPointerType()) { 11946 RHS = ImpCastExprToType(RHS.get(), LHSType, 11947 CK_BlockPointerToObjCPointerCast); 11948 return computeResultTy(); 11949 } 11950 } 11951 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11952 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11953 unsigned DiagID = 0; 11954 bool isError = false; 11955 if (LangOpts.DebuggerSupport) { 11956 // Under a debugger, allow the comparison of pointers to integers, 11957 // since users tend to want to compare addresses. 11958 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11959 (RHSIsNull && RHSType->isIntegerType())) { 11960 if (IsOrdered) { 11961 isError = getLangOpts().CPlusPlus; 11962 DiagID = 11963 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11964 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11965 } 11966 } else if (getLangOpts().CPlusPlus) { 11967 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11968 isError = true; 11969 } else if (IsOrdered) 11970 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11971 else 11972 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11973 11974 if (DiagID) { 11975 Diag(Loc, DiagID) 11976 << LHSType << RHSType << LHS.get()->getSourceRange() 11977 << RHS.get()->getSourceRange(); 11978 if (isError) 11979 return QualType(); 11980 } 11981 11982 if (LHSType->isIntegerType()) 11983 LHS = ImpCastExprToType(LHS.get(), RHSType, 11984 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11985 else 11986 RHS = ImpCastExprToType(RHS.get(), LHSType, 11987 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11988 return computeResultTy(); 11989 } 11990 11991 // Handle block pointers. 11992 if (!IsOrdered && RHSIsNull 11993 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11994 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11995 return computeResultTy(); 11996 } 11997 if (!IsOrdered && LHSIsNull 11998 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11999 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12000 return computeResultTy(); 12001 } 12002 12003 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12004 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12005 return computeResultTy(); 12006 } 12007 12008 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12009 return computeResultTy(); 12010 } 12011 12012 if (LHSIsNull && RHSType->isQueueT()) { 12013 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12014 return computeResultTy(); 12015 } 12016 12017 if (LHSType->isQueueT() && RHSIsNull) { 12018 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12019 return computeResultTy(); 12020 } 12021 } 12022 12023 return InvalidOperands(Loc, LHS, RHS); 12024 } 12025 12026 // Return a signed ext_vector_type that is of identical size and number of 12027 // elements. For floating point vectors, return an integer type of identical 12028 // size and number of elements. In the non ext_vector_type case, search from 12029 // the largest type to the smallest type to avoid cases where long long == long, 12030 // where long gets picked over long long. 12031 QualType Sema::GetSignedVectorType(QualType V) { 12032 const VectorType *VTy = V->castAs<VectorType>(); 12033 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12034 12035 if (isa<ExtVectorType>(VTy)) { 12036 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12037 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12038 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12039 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12040 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12041 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12042 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12043 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12044 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12045 "Unhandled vector element size in vector compare"); 12046 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12047 } 12048 12049 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12050 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12051 VectorType::GenericVector); 12052 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12053 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12054 VectorType::GenericVector); 12055 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12056 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12057 VectorType::GenericVector); 12058 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12059 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12060 VectorType::GenericVector); 12061 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12062 "Unhandled vector element size in vector compare"); 12063 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12064 VectorType::GenericVector); 12065 } 12066 12067 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12068 /// operates on extended vector types. Instead of producing an IntTy result, 12069 /// like a scalar comparison, a vector comparison produces a vector of integer 12070 /// types. 12071 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12072 SourceLocation Loc, 12073 BinaryOperatorKind Opc) { 12074 if (Opc == BO_Cmp) { 12075 Diag(Loc, diag::err_three_way_vector_comparison); 12076 return QualType(); 12077 } 12078 12079 // Check to make sure we're operating on vectors of the same type and width, 12080 // Allowing one side to be a scalar of element type. 12081 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12082 /*AllowBothBool*/true, 12083 /*AllowBoolConversions*/getLangOpts().ZVector); 12084 if (vType.isNull()) 12085 return vType; 12086 12087 QualType LHSType = LHS.get()->getType(); 12088 12089 // If AltiVec, the comparison results in a numeric type, i.e. 12090 // bool for C++, int for C 12091 if (getLangOpts().AltiVec && 12092 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12093 return Context.getLogicalOperationType(); 12094 12095 // For non-floating point types, check for self-comparisons of the form 12096 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12097 // often indicate logic errors in the program. 12098 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12099 12100 // Check for comparisons of floating point operands using != and ==. 12101 if (BinaryOperator::isEqualityOp(Opc) && 12102 LHSType->hasFloatingRepresentation()) { 12103 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12104 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12105 } 12106 12107 // Return a signed type for the vector. 12108 return GetSignedVectorType(vType); 12109 } 12110 12111 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12112 const ExprResult &XorRHS, 12113 const SourceLocation Loc) { 12114 // Do not diagnose macros. 12115 if (Loc.isMacroID()) 12116 return; 12117 12118 // Do not diagnose if both LHS and RHS are macros. 12119 if (XorLHS.get()->getExprLoc().isMacroID() && 12120 XorRHS.get()->getExprLoc().isMacroID()) 12121 return; 12122 12123 bool Negative = false; 12124 bool ExplicitPlus = false; 12125 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12126 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12127 12128 if (!LHSInt) 12129 return; 12130 if (!RHSInt) { 12131 // Check negative literals. 12132 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12133 UnaryOperatorKind Opc = UO->getOpcode(); 12134 if (Opc != UO_Minus && Opc != UO_Plus) 12135 return; 12136 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12137 if (!RHSInt) 12138 return; 12139 Negative = (Opc == UO_Minus); 12140 ExplicitPlus = !Negative; 12141 } else { 12142 return; 12143 } 12144 } 12145 12146 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12147 llvm::APInt RightSideValue = RHSInt->getValue(); 12148 if (LeftSideValue != 2 && LeftSideValue != 10) 12149 return; 12150 12151 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12152 return; 12153 12154 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12155 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12156 llvm::StringRef ExprStr = 12157 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12158 12159 CharSourceRange XorRange = 12160 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12161 llvm::StringRef XorStr = 12162 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12163 // Do not diagnose if xor keyword/macro is used. 12164 if (XorStr == "xor") 12165 return; 12166 12167 std::string LHSStr = std::string(Lexer::getSourceText( 12168 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12169 S.getSourceManager(), S.getLangOpts())); 12170 std::string RHSStr = std::string(Lexer::getSourceText( 12171 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12172 S.getSourceManager(), S.getLangOpts())); 12173 12174 if (Negative) { 12175 RightSideValue = -RightSideValue; 12176 RHSStr = "-" + RHSStr; 12177 } else if (ExplicitPlus) { 12178 RHSStr = "+" + RHSStr; 12179 } 12180 12181 StringRef LHSStrRef = LHSStr; 12182 StringRef RHSStrRef = RHSStr; 12183 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12184 // literals. 12185 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12186 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12187 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12188 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12189 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12190 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12191 LHSStrRef.find('\'') != StringRef::npos || 12192 RHSStrRef.find('\'') != StringRef::npos) 12193 return; 12194 12195 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12196 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12197 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12198 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12199 std::string SuggestedExpr = "1 << " + RHSStr; 12200 bool Overflow = false; 12201 llvm::APInt One = (LeftSideValue - 1); 12202 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12203 if (Overflow) { 12204 if (RightSideIntValue < 64) 12205 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12206 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12207 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12208 else if (RightSideIntValue == 64) 12209 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12210 else 12211 return; 12212 } else { 12213 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12214 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12215 << PowValue.toString(10, true) 12216 << FixItHint::CreateReplacement( 12217 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12218 } 12219 12220 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12221 } else if (LeftSideValue == 10) { 12222 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12223 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12224 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12225 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12226 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12227 } 12228 } 12229 12230 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12231 SourceLocation Loc) { 12232 // Ensure that either both operands are of the same vector type, or 12233 // one operand is of a vector type and the other is of its element type. 12234 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12235 /*AllowBothBool*/true, 12236 /*AllowBoolConversions*/false); 12237 if (vType.isNull()) 12238 return InvalidOperands(Loc, LHS, RHS); 12239 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12240 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12241 return InvalidOperands(Loc, LHS, RHS); 12242 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12243 // usage of the logical operators && and || with vectors in C. This 12244 // check could be notionally dropped. 12245 if (!getLangOpts().CPlusPlus && 12246 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12247 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12248 12249 return GetSignedVectorType(LHS.get()->getType()); 12250 } 12251 12252 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12253 SourceLocation Loc, 12254 bool IsCompAssign) { 12255 if (!IsCompAssign) { 12256 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12257 if (LHS.isInvalid()) 12258 return QualType(); 12259 } 12260 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12261 if (RHS.isInvalid()) 12262 return QualType(); 12263 12264 // For conversion purposes, we ignore any qualifiers. 12265 // For example, "const float" and "float" are equivalent. 12266 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12267 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12268 12269 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12270 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12271 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12272 12273 if (Context.hasSameType(LHSType, RHSType)) 12274 return LHSType; 12275 12276 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12277 // case we have to return InvalidOperands. 12278 ExprResult OriginalLHS = LHS; 12279 ExprResult OriginalRHS = RHS; 12280 if (LHSMatType && !RHSMatType) { 12281 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12282 if (!RHS.isInvalid()) 12283 return LHSType; 12284 12285 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12286 } 12287 12288 if (!LHSMatType && RHSMatType) { 12289 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12290 if (!LHS.isInvalid()) 12291 return RHSType; 12292 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12293 } 12294 12295 return InvalidOperands(Loc, LHS, RHS); 12296 } 12297 12298 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12299 SourceLocation Loc, 12300 bool IsCompAssign) { 12301 if (!IsCompAssign) { 12302 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12303 if (LHS.isInvalid()) 12304 return QualType(); 12305 } 12306 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12307 if (RHS.isInvalid()) 12308 return QualType(); 12309 12310 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12311 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12312 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12313 12314 if (LHSMatType && RHSMatType) { 12315 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12316 return InvalidOperands(Loc, LHS, RHS); 12317 12318 if (!Context.hasSameType(LHSMatType->getElementType(), 12319 RHSMatType->getElementType())) 12320 return InvalidOperands(Loc, LHS, RHS); 12321 12322 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12323 LHSMatType->getNumRows(), 12324 RHSMatType->getNumColumns()); 12325 } 12326 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12327 } 12328 12329 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12330 SourceLocation Loc, 12331 BinaryOperatorKind Opc) { 12332 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12333 12334 bool IsCompAssign = 12335 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12336 12337 if (LHS.get()->getType()->isVectorType() || 12338 RHS.get()->getType()->isVectorType()) { 12339 if (LHS.get()->getType()->hasIntegerRepresentation() && 12340 RHS.get()->getType()->hasIntegerRepresentation()) 12341 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12342 /*AllowBothBool*/true, 12343 /*AllowBoolConversions*/getLangOpts().ZVector); 12344 return InvalidOperands(Loc, LHS, RHS); 12345 } 12346 12347 if (Opc == BO_And) 12348 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12349 12350 if (LHS.get()->getType()->hasFloatingRepresentation() || 12351 RHS.get()->getType()->hasFloatingRepresentation()) 12352 return InvalidOperands(Loc, LHS, RHS); 12353 12354 ExprResult LHSResult = LHS, RHSResult = RHS; 12355 QualType compType = UsualArithmeticConversions( 12356 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12357 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12358 return QualType(); 12359 LHS = LHSResult.get(); 12360 RHS = RHSResult.get(); 12361 12362 if (Opc == BO_Xor) 12363 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12364 12365 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12366 return compType; 12367 return InvalidOperands(Loc, LHS, RHS); 12368 } 12369 12370 // C99 6.5.[13,14] 12371 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12372 SourceLocation Loc, 12373 BinaryOperatorKind Opc) { 12374 // Check vector operands differently. 12375 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12376 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12377 12378 bool EnumConstantInBoolContext = false; 12379 for (const ExprResult &HS : {LHS, RHS}) { 12380 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12381 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12382 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12383 EnumConstantInBoolContext = true; 12384 } 12385 } 12386 12387 if (EnumConstantInBoolContext) 12388 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12389 12390 // Diagnose cases where the user write a logical and/or but probably meant a 12391 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12392 // is a constant. 12393 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12394 !LHS.get()->getType()->isBooleanType() && 12395 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12396 // Don't warn in macros or template instantiations. 12397 !Loc.isMacroID() && !inTemplateInstantiation()) { 12398 // If the RHS can be constant folded, and if it constant folds to something 12399 // that isn't 0 or 1 (which indicate a potential logical operation that 12400 // happened to fold to true/false) then warn. 12401 // Parens on the RHS are ignored. 12402 Expr::EvalResult EVResult; 12403 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12404 llvm::APSInt Result = EVResult.Val.getInt(); 12405 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12406 !RHS.get()->getExprLoc().isMacroID()) || 12407 (Result != 0 && Result != 1)) { 12408 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12409 << RHS.get()->getSourceRange() 12410 << (Opc == BO_LAnd ? "&&" : "||"); 12411 // Suggest replacing the logical operator with the bitwise version 12412 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12413 << (Opc == BO_LAnd ? "&" : "|") 12414 << FixItHint::CreateReplacement(SourceRange( 12415 Loc, getLocForEndOfToken(Loc)), 12416 Opc == BO_LAnd ? "&" : "|"); 12417 if (Opc == BO_LAnd) 12418 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12419 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12420 << FixItHint::CreateRemoval( 12421 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12422 RHS.get()->getEndLoc())); 12423 } 12424 } 12425 } 12426 12427 if (!Context.getLangOpts().CPlusPlus) { 12428 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12429 // not operate on the built-in scalar and vector float types. 12430 if (Context.getLangOpts().OpenCL && 12431 Context.getLangOpts().OpenCLVersion < 120) { 12432 if (LHS.get()->getType()->isFloatingType() || 12433 RHS.get()->getType()->isFloatingType()) 12434 return InvalidOperands(Loc, LHS, RHS); 12435 } 12436 12437 LHS = UsualUnaryConversions(LHS.get()); 12438 if (LHS.isInvalid()) 12439 return QualType(); 12440 12441 RHS = UsualUnaryConversions(RHS.get()); 12442 if (RHS.isInvalid()) 12443 return QualType(); 12444 12445 if (!LHS.get()->getType()->isScalarType() || 12446 !RHS.get()->getType()->isScalarType()) 12447 return InvalidOperands(Loc, LHS, RHS); 12448 12449 return Context.IntTy; 12450 } 12451 12452 // The following is safe because we only use this method for 12453 // non-overloadable operands. 12454 12455 // C++ [expr.log.and]p1 12456 // C++ [expr.log.or]p1 12457 // The operands are both contextually converted to type bool. 12458 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12459 if (LHSRes.isInvalid()) 12460 return InvalidOperands(Loc, LHS, RHS); 12461 LHS = LHSRes; 12462 12463 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12464 if (RHSRes.isInvalid()) 12465 return InvalidOperands(Loc, LHS, RHS); 12466 RHS = RHSRes; 12467 12468 // C++ [expr.log.and]p2 12469 // C++ [expr.log.or]p2 12470 // The result is a bool. 12471 return Context.BoolTy; 12472 } 12473 12474 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12475 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12476 if (!ME) return false; 12477 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12478 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12479 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12480 if (!Base) return false; 12481 return Base->getMethodDecl() != nullptr; 12482 } 12483 12484 /// Is the given expression (which must be 'const') a reference to a 12485 /// variable which was originally non-const, but which has become 12486 /// 'const' due to being captured within a block? 12487 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12488 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12489 assert(E->isLValue() && E->getType().isConstQualified()); 12490 E = E->IgnoreParens(); 12491 12492 // Must be a reference to a declaration from an enclosing scope. 12493 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12494 if (!DRE) return NCCK_None; 12495 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12496 12497 // The declaration must be a variable which is not declared 'const'. 12498 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12499 if (!var) return NCCK_None; 12500 if (var->getType().isConstQualified()) return NCCK_None; 12501 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12502 12503 // Decide whether the first capture was for a block or a lambda. 12504 DeclContext *DC = S.CurContext, *Prev = nullptr; 12505 // Decide whether the first capture was for a block or a lambda. 12506 while (DC) { 12507 // For init-capture, it is possible that the variable belongs to the 12508 // template pattern of the current context. 12509 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12510 if (var->isInitCapture() && 12511 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12512 break; 12513 if (DC == var->getDeclContext()) 12514 break; 12515 Prev = DC; 12516 DC = DC->getParent(); 12517 } 12518 // Unless we have an init-capture, we've gone one step too far. 12519 if (!var->isInitCapture()) 12520 DC = Prev; 12521 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12522 } 12523 12524 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12525 Ty = Ty.getNonReferenceType(); 12526 if (IsDereference && Ty->isPointerType()) 12527 Ty = Ty->getPointeeType(); 12528 return !Ty.isConstQualified(); 12529 } 12530 12531 // Update err_typecheck_assign_const and note_typecheck_assign_const 12532 // when this enum is changed. 12533 enum { 12534 ConstFunction, 12535 ConstVariable, 12536 ConstMember, 12537 ConstMethod, 12538 NestedConstMember, 12539 ConstUnknown, // Keep as last element 12540 }; 12541 12542 /// Emit the "read-only variable not assignable" error and print notes to give 12543 /// more information about why the variable is not assignable, such as pointing 12544 /// to the declaration of a const variable, showing that a method is const, or 12545 /// that the function is returning a const reference. 12546 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12547 SourceLocation Loc) { 12548 SourceRange ExprRange = E->getSourceRange(); 12549 12550 // Only emit one error on the first const found. All other consts will emit 12551 // a note to the error. 12552 bool DiagnosticEmitted = false; 12553 12554 // Track if the current expression is the result of a dereference, and if the 12555 // next checked expression is the result of a dereference. 12556 bool IsDereference = false; 12557 bool NextIsDereference = false; 12558 12559 // Loop to process MemberExpr chains. 12560 while (true) { 12561 IsDereference = NextIsDereference; 12562 12563 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12564 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12565 NextIsDereference = ME->isArrow(); 12566 const ValueDecl *VD = ME->getMemberDecl(); 12567 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12568 // Mutable fields can be modified even if the class is const. 12569 if (Field->isMutable()) { 12570 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12571 break; 12572 } 12573 12574 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12575 if (!DiagnosticEmitted) { 12576 S.Diag(Loc, diag::err_typecheck_assign_const) 12577 << ExprRange << ConstMember << false /*static*/ << Field 12578 << Field->getType(); 12579 DiagnosticEmitted = true; 12580 } 12581 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12582 << ConstMember << false /*static*/ << Field << Field->getType() 12583 << Field->getSourceRange(); 12584 } 12585 E = ME->getBase(); 12586 continue; 12587 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12588 if (VDecl->getType().isConstQualified()) { 12589 if (!DiagnosticEmitted) { 12590 S.Diag(Loc, diag::err_typecheck_assign_const) 12591 << ExprRange << ConstMember << true /*static*/ << VDecl 12592 << VDecl->getType(); 12593 DiagnosticEmitted = true; 12594 } 12595 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12596 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12597 << VDecl->getSourceRange(); 12598 } 12599 // Static fields do not inherit constness from parents. 12600 break; 12601 } 12602 break; // End MemberExpr 12603 } else if (const ArraySubscriptExpr *ASE = 12604 dyn_cast<ArraySubscriptExpr>(E)) { 12605 E = ASE->getBase()->IgnoreParenImpCasts(); 12606 continue; 12607 } else if (const ExtVectorElementExpr *EVE = 12608 dyn_cast<ExtVectorElementExpr>(E)) { 12609 E = EVE->getBase()->IgnoreParenImpCasts(); 12610 continue; 12611 } 12612 break; 12613 } 12614 12615 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12616 // Function calls 12617 const FunctionDecl *FD = CE->getDirectCallee(); 12618 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12619 if (!DiagnosticEmitted) { 12620 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12621 << ConstFunction << FD; 12622 DiagnosticEmitted = true; 12623 } 12624 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12625 diag::note_typecheck_assign_const) 12626 << ConstFunction << FD << FD->getReturnType() 12627 << FD->getReturnTypeSourceRange(); 12628 } 12629 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12630 // Point to variable declaration. 12631 if (const ValueDecl *VD = DRE->getDecl()) { 12632 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12633 if (!DiagnosticEmitted) { 12634 S.Diag(Loc, diag::err_typecheck_assign_const) 12635 << ExprRange << ConstVariable << VD << VD->getType(); 12636 DiagnosticEmitted = true; 12637 } 12638 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12639 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12640 } 12641 } 12642 } else if (isa<CXXThisExpr>(E)) { 12643 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12644 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12645 if (MD->isConst()) { 12646 if (!DiagnosticEmitted) { 12647 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12648 << ConstMethod << MD; 12649 DiagnosticEmitted = true; 12650 } 12651 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12652 << ConstMethod << MD << MD->getSourceRange(); 12653 } 12654 } 12655 } 12656 } 12657 12658 if (DiagnosticEmitted) 12659 return; 12660 12661 // Can't determine a more specific message, so display the generic error. 12662 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12663 } 12664 12665 enum OriginalExprKind { 12666 OEK_Variable, 12667 OEK_Member, 12668 OEK_LValue 12669 }; 12670 12671 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12672 const RecordType *Ty, 12673 SourceLocation Loc, SourceRange Range, 12674 OriginalExprKind OEK, 12675 bool &DiagnosticEmitted) { 12676 std::vector<const RecordType *> RecordTypeList; 12677 RecordTypeList.push_back(Ty); 12678 unsigned NextToCheckIndex = 0; 12679 // We walk the record hierarchy breadth-first to ensure that we print 12680 // diagnostics in field nesting order. 12681 while (RecordTypeList.size() > NextToCheckIndex) { 12682 bool IsNested = NextToCheckIndex > 0; 12683 for (const FieldDecl *Field : 12684 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12685 // First, check every field for constness. 12686 QualType FieldTy = Field->getType(); 12687 if (FieldTy.isConstQualified()) { 12688 if (!DiagnosticEmitted) { 12689 S.Diag(Loc, diag::err_typecheck_assign_const) 12690 << Range << NestedConstMember << OEK << VD 12691 << IsNested << Field; 12692 DiagnosticEmitted = true; 12693 } 12694 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12695 << NestedConstMember << IsNested << Field 12696 << FieldTy << Field->getSourceRange(); 12697 } 12698 12699 // Then we append it to the list to check next in order. 12700 FieldTy = FieldTy.getCanonicalType(); 12701 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12702 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12703 RecordTypeList.push_back(FieldRecTy); 12704 } 12705 } 12706 ++NextToCheckIndex; 12707 } 12708 } 12709 12710 /// Emit an error for the case where a record we are trying to assign to has a 12711 /// const-qualified field somewhere in its hierarchy. 12712 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12713 SourceLocation Loc) { 12714 QualType Ty = E->getType(); 12715 assert(Ty->isRecordType() && "lvalue was not record?"); 12716 SourceRange Range = E->getSourceRange(); 12717 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12718 bool DiagEmitted = false; 12719 12720 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12721 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12722 Range, OEK_Member, DiagEmitted); 12723 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12724 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12725 Range, OEK_Variable, DiagEmitted); 12726 else 12727 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12728 Range, OEK_LValue, DiagEmitted); 12729 if (!DiagEmitted) 12730 DiagnoseConstAssignment(S, E, Loc); 12731 } 12732 12733 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12734 /// emit an error and return true. If so, return false. 12735 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12736 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12737 12738 S.CheckShadowingDeclModification(E, Loc); 12739 12740 SourceLocation OrigLoc = Loc; 12741 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12742 &Loc); 12743 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12744 IsLV = Expr::MLV_InvalidMessageExpression; 12745 if (IsLV == Expr::MLV_Valid) 12746 return false; 12747 12748 unsigned DiagID = 0; 12749 bool NeedType = false; 12750 switch (IsLV) { // C99 6.5.16p2 12751 case Expr::MLV_ConstQualified: 12752 // Use a specialized diagnostic when we're assigning to an object 12753 // from an enclosing function or block. 12754 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12755 if (NCCK == NCCK_Block) 12756 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12757 else 12758 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12759 break; 12760 } 12761 12762 // In ARC, use some specialized diagnostics for occasions where we 12763 // infer 'const'. These are always pseudo-strong variables. 12764 if (S.getLangOpts().ObjCAutoRefCount) { 12765 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12766 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12767 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12768 12769 // Use the normal diagnostic if it's pseudo-__strong but the 12770 // user actually wrote 'const'. 12771 if (var->isARCPseudoStrong() && 12772 (!var->getTypeSourceInfo() || 12773 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12774 // There are three pseudo-strong cases: 12775 // - self 12776 ObjCMethodDecl *method = S.getCurMethodDecl(); 12777 if (method && var == method->getSelfDecl()) { 12778 DiagID = method->isClassMethod() 12779 ? diag::err_typecheck_arc_assign_self_class_method 12780 : diag::err_typecheck_arc_assign_self; 12781 12782 // - Objective-C externally_retained attribute. 12783 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12784 isa<ParmVarDecl>(var)) { 12785 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12786 12787 // - fast enumeration variables 12788 } else { 12789 DiagID = diag::err_typecheck_arr_assign_enumeration; 12790 } 12791 12792 SourceRange Assign; 12793 if (Loc != OrigLoc) 12794 Assign = SourceRange(OrigLoc, OrigLoc); 12795 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12796 // We need to preserve the AST regardless, so migration tool 12797 // can do its job. 12798 return false; 12799 } 12800 } 12801 } 12802 12803 // If none of the special cases above are triggered, then this is a 12804 // simple const assignment. 12805 if (DiagID == 0) { 12806 DiagnoseConstAssignment(S, E, Loc); 12807 return true; 12808 } 12809 12810 break; 12811 case Expr::MLV_ConstAddrSpace: 12812 DiagnoseConstAssignment(S, E, Loc); 12813 return true; 12814 case Expr::MLV_ConstQualifiedField: 12815 DiagnoseRecursiveConstFields(S, E, Loc); 12816 return true; 12817 case Expr::MLV_ArrayType: 12818 case Expr::MLV_ArrayTemporary: 12819 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12820 NeedType = true; 12821 break; 12822 case Expr::MLV_NotObjectType: 12823 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12824 NeedType = true; 12825 break; 12826 case Expr::MLV_LValueCast: 12827 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12828 break; 12829 case Expr::MLV_Valid: 12830 llvm_unreachable("did not take early return for MLV_Valid"); 12831 case Expr::MLV_InvalidExpression: 12832 case Expr::MLV_MemberFunction: 12833 case Expr::MLV_ClassTemporary: 12834 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12835 break; 12836 case Expr::MLV_IncompleteType: 12837 case Expr::MLV_IncompleteVoidType: 12838 return S.RequireCompleteType(Loc, E->getType(), 12839 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12840 case Expr::MLV_DuplicateVectorComponents: 12841 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12842 break; 12843 case Expr::MLV_NoSetterProperty: 12844 llvm_unreachable("readonly properties should be processed differently"); 12845 case Expr::MLV_InvalidMessageExpression: 12846 DiagID = diag::err_readonly_message_assignment; 12847 break; 12848 case Expr::MLV_SubObjCPropertySetting: 12849 DiagID = diag::err_no_subobject_property_setting; 12850 break; 12851 } 12852 12853 SourceRange Assign; 12854 if (Loc != OrigLoc) 12855 Assign = SourceRange(OrigLoc, OrigLoc); 12856 if (NeedType) 12857 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12858 else 12859 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12860 return true; 12861 } 12862 12863 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12864 SourceLocation Loc, 12865 Sema &Sema) { 12866 if (Sema.inTemplateInstantiation()) 12867 return; 12868 if (Sema.isUnevaluatedContext()) 12869 return; 12870 if (Loc.isInvalid() || Loc.isMacroID()) 12871 return; 12872 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12873 return; 12874 12875 // C / C++ fields 12876 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12877 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12878 if (ML && MR) { 12879 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12880 return; 12881 const ValueDecl *LHSDecl = 12882 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12883 const ValueDecl *RHSDecl = 12884 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12885 if (LHSDecl != RHSDecl) 12886 return; 12887 if (LHSDecl->getType().isVolatileQualified()) 12888 return; 12889 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12890 if (RefTy->getPointeeType().isVolatileQualified()) 12891 return; 12892 12893 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12894 } 12895 12896 // Objective-C instance variables 12897 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12898 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12899 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12900 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12901 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12902 if (RL && RR && RL->getDecl() == RR->getDecl()) 12903 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12904 } 12905 } 12906 12907 // C99 6.5.16.1 12908 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12909 SourceLocation Loc, 12910 QualType CompoundType) { 12911 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12912 12913 // Verify that LHS is a modifiable lvalue, and emit error if not. 12914 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12915 return QualType(); 12916 12917 QualType LHSType = LHSExpr->getType(); 12918 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12919 CompoundType; 12920 // OpenCL v1.2 s6.1.1.1 p2: 12921 // The half data type can only be used to declare a pointer to a buffer that 12922 // contains half values 12923 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12924 LHSType->isHalfType()) { 12925 Diag(Loc, diag::err_opencl_half_load_store) << 1 12926 << LHSType.getUnqualifiedType(); 12927 return QualType(); 12928 } 12929 12930 AssignConvertType ConvTy; 12931 if (CompoundType.isNull()) { 12932 Expr *RHSCheck = RHS.get(); 12933 12934 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12935 12936 QualType LHSTy(LHSType); 12937 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12938 if (RHS.isInvalid()) 12939 return QualType(); 12940 // Special case of NSObject attributes on c-style pointer types. 12941 if (ConvTy == IncompatiblePointer && 12942 ((Context.isObjCNSObjectType(LHSType) && 12943 RHSType->isObjCObjectPointerType()) || 12944 (Context.isObjCNSObjectType(RHSType) && 12945 LHSType->isObjCObjectPointerType()))) 12946 ConvTy = Compatible; 12947 12948 if (ConvTy == Compatible && 12949 LHSType->isObjCObjectType()) 12950 Diag(Loc, diag::err_objc_object_assignment) 12951 << LHSType; 12952 12953 // If the RHS is a unary plus or minus, check to see if they = and + are 12954 // right next to each other. If so, the user may have typo'd "x =+ 4" 12955 // instead of "x += 4". 12956 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12957 RHSCheck = ICE->getSubExpr(); 12958 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12959 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12960 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12961 // Only if the two operators are exactly adjacent. 12962 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12963 // And there is a space or other character before the subexpr of the 12964 // unary +/-. We don't want to warn on "x=-1". 12965 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12966 UO->getSubExpr()->getBeginLoc().isFileID()) { 12967 Diag(Loc, diag::warn_not_compound_assign) 12968 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12969 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12970 } 12971 } 12972 12973 if (ConvTy == Compatible) { 12974 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12975 // Warn about retain cycles where a block captures the LHS, but 12976 // not if the LHS is a simple variable into which the block is 12977 // being stored...unless that variable can be captured by reference! 12978 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12979 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12980 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12981 checkRetainCycles(LHSExpr, RHS.get()); 12982 } 12983 12984 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12985 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12986 // It is safe to assign a weak reference into a strong variable. 12987 // Although this code can still have problems: 12988 // id x = self.weakProp; 12989 // id y = self.weakProp; 12990 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12991 // paths through the function. This should be revisited if 12992 // -Wrepeated-use-of-weak is made flow-sensitive. 12993 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12994 // variable, which will be valid for the current autorelease scope. 12995 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12996 RHS.get()->getBeginLoc())) 12997 getCurFunction()->markSafeWeakUse(RHS.get()); 12998 12999 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13000 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13001 } 13002 } 13003 } else { 13004 // Compound assignment "x += y" 13005 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13006 } 13007 13008 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13009 RHS.get(), AA_Assigning)) 13010 return QualType(); 13011 13012 CheckForNullPointerDereference(*this, LHSExpr); 13013 13014 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13015 if (CompoundType.isNull()) { 13016 // C++2a [expr.ass]p5: 13017 // A simple-assignment whose left operand is of a volatile-qualified 13018 // type is deprecated unless the assignment is either a discarded-value 13019 // expression or an unevaluated operand 13020 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13021 } else { 13022 // C++2a [expr.ass]p6: 13023 // [Compound-assignment] expressions are deprecated if E1 has 13024 // volatile-qualified type 13025 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13026 } 13027 } 13028 13029 // C99 6.5.16p3: The type of an assignment expression is the type of the 13030 // left operand unless the left operand has qualified type, in which case 13031 // it is the unqualified version of the type of the left operand. 13032 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13033 // is converted to the type of the assignment expression (above). 13034 // C++ 5.17p1: the type of the assignment expression is that of its left 13035 // operand. 13036 return (getLangOpts().CPlusPlus 13037 ? LHSType : LHSType.getUnqualifiedType()); 13038 } 13039 13040 // Only ignore explicit casts to void. 13041 static bool IgnoreCommaOperand(const Expr *E) { 13042 E = E->IgnoreParens(); 13043 13044 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13045 if (CE->getCastKind() == CK_ToVoid) { 13046 return true; 13047 } 13048 13049 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13050 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13051 CE->getSubExpr()->getType()->isDependentType()) { 13052 return true; 13053 } 13054 } 13055 13056 return false; 13057 } 13058 13059 // Look for instances where it is likely the comma operator is confused with 13060 // another operator. There is an explicit list of acceptable expressions for 13061 // the left hand side of the comma operator, otherwise emit a warning. 13062 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13063 // No warnings in macros 13064 if (Loc.isMacroID()) 13065 return; 13066 13067 // Don't warn in template instantiations. 13068 if (inTemplateInstantiation()) 13069 return; 13070 13071 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13072 // instead, skip more than needed, then call back into here with the 13073 // CommaVisitor in SemaStmt.cpp. 13074 // The listed locations are the initialization and increment portions 13075 // of a for loop. The additional checks are on the condition of 13076 // if statements, do/while loops, and for loops. 13077 // Differences in scope flags for C89 mode requires the extra logic. 13078 const unsigned ForIncrementFlags = 13079 getLangOpts().C99 || getLangOpts().CPlusPlus 13080 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13081 : Scope::ContinueScope | Scope::BreakScope; 13082 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13083 const unsigned ScopeFlags = getCurScope()->getFlags(); 13084 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13085 (ScopeFlags & ForInitFlags) == ForInitFlags) 13086 return; 13087 13088 // If there are multiple comma operators used together, get the RHS of the 13089 // of the comma operator as the LHS. 13090 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13091 if (BO->getOpcode() != BO_Comma) 13092 break; 13093 LHS = BO->getRHS(); 13094 } 13095 13096 // Only allow some expressions on LHS to not warn. 13097 if (IgnoreCommaOperand(LHS)) 13098 return; 13099 13100 Diag(Loc, diag::warn_comma_operator); 13101 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13102 << LHS->getSourceRange() 13103 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13104 LangOpts.CPlusPlus ? "static_cast<void>(" 13105 : "(void)(") 13106 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13107 ")"); 13108 } 13109 13110 // C99 6.5.17 13111 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13112 SourceLocation Loc) { 13113 LHS = S.CheckPlaceholderExpr(LHS.get()); 13114 RHS = S.CheckPlaceholderExpr(RHS.get()); 13115 if (LHS.isInvalid() || RHS.isInvalid()) 13116 return QualType(); 13117 13118 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13119 // operands, but not unary promotions. 13120 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13121 13122 // So we treat the LHS as a ignored value, and in C++ we allow the 13123 // containing site to determine what should be done with the RHS. 13124 LHS = S.IgnoredValueConversions(LHS.get()); 13125 if (LHS.isInvalid()) 13126 return QualType(); 13127 13128 S.DiagnoseUnusedExprResult(LHS.get()); 13129 13130 if (!S.getLangOpts().CPlusPlus) { 13131 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13132 if (RHS.isInvalid()) 13133 return QualType(); 13134 if (!RHS.get()->getType()->isVoidType()) 13135 S.RequireCompleteType(Loc, RHS.get()->getType(), 13136 diag::err_incomplete_type); 13137 } 13138 13139 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13140 S.DiagnoseCommaOperator(LHS.get(), Loc); 13141 13142 return RHS.get()->getType(); 13143 } 13144 13145 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13146 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13147 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13148 ExprValueKind &VK, 13149 ExprObjectKind &OK, 13150 SourceLocation OpLoc, 13151 bool IsInc, bool IsPrefix) { 13152 if (Op->isTypeDependent()) 13153 return S.Context.DependentTy; 13154 13155 QualType ResType = Op->getType(); 13156 // Atomic types can be used for increment / decrement where the non-atomic 13157 // versions can, so ignore the _Atomic() specifier for the purpose of 13158 // checking. 13159 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13160 ResType = ResAtomicType->getValueType(); 13161 13162 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13163 13164 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13165 // Decrement of bool is not allowed. 13166 if (!IsInc) { 13167 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13168 return QualType(); 13169 } 13170 // Increment of bool sets it to true, but is deprecated. 13171 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13172 : diag::warn_increment_bool) 13173 << Op->getSourceRange(); 13174 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13175 // Error on enum increments and decrements in C++ mode 13176 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13177 return QualType(); 13178 } else if (ResType->isRealType()) { 13179 // OK! 13180 } else if (ResType->isPointerType()) { 13181 // C99 6.5.2.4p2, 6.5.6p2 13182 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13183 return QualType(); 13184 } else if (ResType->isObjCObjectPointerType()) { 13185 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13186 // Otherwise, we just need a complete type. 13187 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13188 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13189 return QualType(); 13190 } else if (ResType->isAnyComplexType()) { 13191 // C99 does not support ++/-- on complex types, we allow as an extension. 13192 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13193 << ResType << Op->getSourceRange(); 13194 } else if (ResType->isPlaceholderType()) { 13195 ExprResult PR = S.CheckPlaceholderExpr(Op); 13196 if (PR.isInvalid()) return QualType(); 13197 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13198 IsInc, IsPrefix); 13199 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13200 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13201 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13202 (ResType->castAs<VectorType>()->getVectorKind() != 13203 VectorType::AltiVecBool)) { 13204 // The z vector extensions allow ++ and -- for non-bool vectors. 13205 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13206 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13207 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13208 } else { 13209 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13210 << ResType << int(IsInc) << Op->getSourceRange(); 13211 return QualType(); 13212 } 13213 // At this point, we know we have a real, complex or pointer type. 13214 // Now make sure the operand is a modifiable lvalue. 13215 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13216 return QualType(); 13217 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13218 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13219 // An operand with volatile-qualified type is deprecated 13220 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13221 << IsInc << ResType; 13222 } 13223 // In C++, a prefix increment is the same type as the operand. Otherwise 13224 // (in C or with postfix), the increment is the unqualified type of the 13225 // operand. 13226 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13227 VK = VK_LValue; 13228 OK = Op->getObjectKind(); 13229 return ResType; 13230 } else { 13231 VK = VK_RValue; 13232 return ResType.getUnqualifiedType(); 13233 } 13234 } 13235 13236 13237 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13238 /// This routine allows us to typecheck complex/recursive expressions 13239 /// where the declaration is needed for type checking. We only need to 13240 /// handle cases when the expression references a function designator 13241 /// or is an lvalue. Here are some examples: 13242 /// - &(x) => x 13243 /// - &*****f => f for f a function designator. 13244 /// - &s.xx => s 13245 /// - &s.zz[1].yy -> s, if zz is an array 13246 /// - *(x + 1) -> x, if x is an array 13247 /// - &"123"[2] -> 0 13248 /// - & __real__ x -> x 13249 /// 13250 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13251 /// members. 13252 static ValueDecl *getPrimaryDecl(Expr *E) { 13253 switch (E->getStmtClass()) { 13254 case Stmt::DeclRefExprClass: 13255 return cast<DeclRefExpr>(E)->getDecl(); 13256 case Stmt::MemberExprClass: 13257 // If this is an arrow operator, the address is an offset from 13258 // the base's value, so the object the base refers to is 13259 // irrelevant. 13260 if (cast<MemberExpr>(E)->isArrow()) 13261 return nullptr; 13262 // Otherwise, the expression refers to a part of the base 13263 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13264 case Stmt::ArraySubscriptExprClass: { 13265 // FIXME: This code shouldn't be necessary! We should catch the implicit 13266 // promotion of register arrays earlier. 13267 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13268 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13269 if (ICE->getSubExpr()->getType()->isArrayType()) 13270 return getPrimaryDecl(ICE->getSubExpr()); 13271 } 13272 return nullptr; 13273 } 13274 case Stmt::UnaryOperatorClass: { 13275 UnaryOperator *UO = cast<UnaryOperator>(E); 13276 13277 switch(UO->getOpcode()) { 13278 case UO_Real: 13279 case UO_Imag: 13280 case UO_Extension: 13281 return getPrimaryDecl(UO->getSubExpr()); 13282 default: 13283 return nullptr; 13284 } 13285 } 13286 case Stmt::ParenExprClass: 13287 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13288 case Stmt::ImplicitCastExprClass: 13289 // If the result of an implicit cast is an l-value, we care about 13290 // the sub-expression; otherwise, the result here doesn't matter. 13291 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13292 case Stmt::CXXUuidofExprClass: 13293 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13294 default: 13295 return nullptr; 13296 } 13297 } 13298 13299 namespace { 13300 enum { 13301 AO_Bit_Field = 0, 13302 AO_Vector_Element = 1, 13303 AO_Property_Expansion = 2, 13304 AO_Register_Variable = 3, 13305 AO_Matrix_Element = 4, 13306 AO_No_Error = 5 13307 }; 13308 } 13309 /// Diagnose invalid operand for address of operations. 13310 /// 13311 /// \param Type The type of operand which cannot have its address taken. 13312 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13313 Expr *E, unsigned Type) { 13314 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13315 } 13316 13317 /// CheckAddressOfOperand - The operand of & must be either a function 13318 /// designator or an lvalue designating an object. If it is an lvalue, the 13319 /// object cannot be declared with storage class register or be a bit field. 13320 /// Note: The usual conversions are *not* applied to the operand of the & 13321 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13322 /// In C++, the operand might be an overloaded function name, in which case 13323 /// we allow the '&' but retain the overloaded-function type. 13324 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13325 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13326 if (PTy->getKind() == BuiltinType::Overload) { 13327 Expr *E = OrigOp.get()->IgnoreParens(); 13328 if (!isa<OverloadExpr>(E)) { 13329 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13330 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13331 << OrigOp.get()->getSourceRange(); 13332 return QualType(); 13333 } 13334 13335 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13336 if (isa<UnresolvedMemberExpr>(Ovl)) 13337 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13338 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13339 << OrigOp.get()->getSourceRange(); 13340 return QualType(); 13341 } 13342 13343 return Context.OverloadTy; 13344 } 13345 13346 if (PTy->getKind() == BuiltinType::UnknownAny) 13347 return Context.UnknownAnyTy; 13348 13349 if (PTy->getKind() == BuiltinType::BoundMember) { 13350 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13351 << OrigOp.get()->getSourceRange(); 13352 return QualType(); 13353 } 13354 13355 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13356 if (OrigOp.isInvalid()) return QualType(); 13357 } 13358 13359 if (OrigOp.get()->isTypeDependent()) 13360 return Context.DependentTy; 13361 13362 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13363 13364 // Make sure to ignore parentheses in subsequent checks 13365 Expr *op = OrigOp.get()->IgnoreParens(); 13366 13367 // In OpenCL captures for blocks called as lambda functions 13368 // are located in the private address space. Blocks used in 13369 // enqueue_kernel can be located in a different address space 13370 // depending on a vendor implementation. Thus preventing 13371 // taking an address of the capture to avoid invalid AS casts. 13372 if (LangOpts.OpenCL) { 13373 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13374 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13375 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13376 return QualType(); 13377 } 13378 } 13379 13380 if (getLangOpts().C99) { 13381 // Implement C99-only parts of addressof rules. 13382 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13383 if (uOp->getOpcode() == UO_Deref) 13384 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13385 // (assuming the deref expression is valid). 13386 return uOp->getSubExpr()->getType(); 13387 } 13388 // Technically, there should be a check for array subscript 13389 // expressions here, but the result of one is always an lvalue anyway. 13390 } 13391 ValueDecl *dcl = getPrimaryDecl(op); 13392 13393 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13394 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13395 op->getBeginLoc())) 13396 return QualType(); 13397 13398 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13399 unsigned AddressOfError = AO_No_Error; 13400 13401 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13402 bool sfinae = (bool)isSFINAEContext(); 13403 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13404 : diag::ext_typecheck_addrof_temporary) 13405 << op->getType() << op->getSourceRange(); 13406 if (sfinae) 13407 return QualType(); 13408 // Materialize the temporary as an lvalue so that we can take its address. 13409 OrigOp = op = 13410 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13411 } else if (isa<ObjCSelectorExpr>(op)) { 13412 return Context.getPointerType(op->getType()); 13413 } else if (lval == Expr::LV_MemberFunction) { 13414 // If it's an instance method, make a member pointer. 13415 // The expression must have exactly the form &A::foo. 13416 13417 // If the underlying expression isn't a decl ref, give up. 13418 if (!isa<DeclRefExpr>(op)) { 13419 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13420 << OrigOp.get()->getSourceRange(); 13421 return QualType(); 13422 } 13423 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13424 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13425 13426 // The id-expression was parenthesized. 13427 if (OrigOp.get() != DRE) { 13428 Diag(OpLoc, diag::err_parens_pointer_member_function) 13429 << OrigOp.get()->getSourceRange(); 13430 13431 // The method was named without a qualifier. 13432 } else if (!DRE->getQualifier()) { 13433 if (MD->getParent()->getName().empty()) 13434 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13435 << op->getSourceRange(); 13436 else { 13437 SmallString<32> Str; 13438 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13439 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13440 << op->getSourceRange() 13441 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13442 } 13443 } 13444 13445 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13446 if (isa<CXXDestructorDecl>(MD)) 13447 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13448 13449 QualType MPTy = Context.getMemberPointerType( 13450 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13451 // Under the MS ABI, lock down the inheritance model now. 13452 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13453 (void)isCompleteType(OpLoc, MPTy); 13454 return MPTy; 13455 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13456 // C99 6.5.3.2p1 13457 // The operand must be either an l-value or a function designator 13458 if (!op->getType()->isFunctionType()) { 13459 // Use a special diagnostic for loads from property references. 13460 if (isa<PseudoObjectExpr>(op)) { 13461 AddressOfError = AO_Property_Expansion; 13462 } else { 13463 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13464 << op->getType() << op->getSourceRange(); 13465 return QualType(); 13466 } 13467 } 13468 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13469 // The operand cannot be a bit-field 13470 AddressOfError = AO_Bit_Field; 13471 } else if (op->getObjectKind() == OK_VectorComponent) { 13472 // The operand cannot be an element of a vector 13473 AddressOfError = AO_Vector_Element; 13474 } else if (op->getObjectKind() == OK_MatrixComponent) { 13475 // The operand cannot be an element of a matrix. 13476 AddressOfError = AO_Matrix_Element; 13477 } else if (dcl) { // C99 6.5.3.2p1 13478 // We have an lvalue with a decl. Make sure the decl is not declared 13479 // with the register storage-class specifier. 13480 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13481 // in C++ it is not error to take address of a register 13482 // variable (c++03 7.1.1P3) 13483 if (vd->getStorageClass() == SC_Register && 13484 !getLangOpts().CPlusPlus) { 13485 AddressOfError = AO_Register_Variable; 13486 } 13487 } else if (isa<MSPropertyDecl>(dcl)) { 13488 AddressOfError = AO_Property_Expansion; 13489 } else if (isa<FunctionTemplateDecl>(dcl)) { 13490 return Context.OverloadTy; 13491 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13492 // Okay: we can take the address of a field. 13493 // Could be a pointer to member, though, if there is an explicit 13494 // scope qualifier for the class. 13495 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13496 DeclContext *Ctx = dcl->getDeclContext(); 13497 if (Ctx && Ctx->isRecord()) { 13498 if (dcl->getType()->isReferenceType()) { 13499 Diag(OpLoc, 13500 diag::err_cannot_form_pointer_to_member_of_reference_type) 13501 << dcl->getDeclName() << dcl->getType(); 13502 return QualType(); 13503 } 13504 13505 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13506 Ctx = Ctx->getParent(); 13507 13508 QualType MPTy = Context.getMemberPointerType( 13509 op->getType(), 13510 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13511 // Under the MS ABI, lock down the inheritance model now. 13512 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13513 (void)isCompleteType(OpLoc, MPTy); 13514 return MPTy; 13515 } 13516 } 13517 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13518 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13519 llvm_unreachable("Unknown/unexpected decl type"); 13520 } 13521 13522 if (AddressOfError != AO_No_Error) { 13523 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13524 return QualType(); 13525 } 13526 13527 if (lval == Expr::LV_IncompleteVoidType) { 13528 // Taking the address of a void variable is technically illegal, but we 13529 // allow it in cases which are otherwise valid. 13530 // Example: "extern void x; void* y = &x;". 13531 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13532 } 13533 13534 // If the operand has type "type", the result has type "pointer to type". 13535 if (op->getType()->isObjCObjectType()) 13536 return Context.getObjCObjectPointerType(op->getType()); 13537 13538 CheckAddressOfPackedMember(op); 13539 13540 return Context.getPointerType(op->getType()); 13541 } 13542 13543 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13544 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13545 if (!DRE) 13546 return; 13547 const Decl *D = DRE->getDecl(); 13548 if (!D) 13549 return; 13550 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13551 if (!Param) 13552 return; 13553 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13554 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13555 return; 13556 if (FunctionScopeInfo *FD = S.getCurFunction()) 13557 if (!FD->ModifiedNonNullParams.count(Param)) 13558 FD->ModifiedNonNullParams.insert(Param); 13559 } 13560 13561 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13562 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13563 SourceLocation OpLoc) { 13564 if (Op->isTypeDependent()) 13565 return S.Context.DependentTy; 13566 13567 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13568 if (ConvResult.isInvalid()) 13569 return QualType(); 13570 Op = ConvResult.get(); 13571 QualType OpTy = Op->getType(); 13572 QualType Result; 13573 13574 if (isa<CXXReinterpretCastExpr>(Op)) { 13575 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13576 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13577 Op->getSourceRange()); 13578 } 13579 13580 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13581 { 13582 Result = PT->getPointeeType(); 13583 } 13584 else if (const ObjCObjectPointerType *OPT = 13585 OpTy->getAs<ObjCObjectPointerType>()) 13586 Result = OPT->getPointeeType(); 13587 else { 13588 ExprResult PR = S.CheckPlaceholderExpr(Op); 13589 if (PR.isInvalid()) return QualType(); 13590 if (PR.get() != Op) 13591 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13592 } 13593 13594 if (Result.isNull()) { 13595 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13596 << OpTy << Op->getSourceRange(); 13597 return QualType(); 13598 } 13599 13600 // Note that per both C89 and C99, indirection is always legal, even if Result 13601 // is an incomplete type or void. It would be possible to warn about 13602 // dereferencing a void pointer, but it's completely well-defined, and such a 13603 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13604 // for pointers to 'void' but is fine for any other pointer type: 13605 // 13606 // C++ [expr.unary.op]p1: 13607 // [...] the expression to which [the unary * operator] is applied shall 13608 // be a pointer to an object type, or a pointer to a function type 13609 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13610 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13611 << OpTy << Op->getSourceRange(); 13612 13613 // Dereferences are usually l-values... 13614 VK = VK_LValue; 13615 13616 // ...except that certain expressions are never l-values in C. 13617 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13618 VK = VK_RValue; 13619 13620 return Result; 13621 } 13622 13623 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13624 BinaryOperatorKind Opc; 13625 switch (Kind) { 13626 default: llvm_unreachable("Unknown binop!"); 13627 case tok::periodstar: Opc = BO_PtrMemD; break; 13628 case tok::arrowstar: Opc = BO_PtrMemI; break; 13629 case tok::star: Opc = BO_Mul; break; 13630 case tok::slash: Opc = BO_Div; break; 13631 case tok::percent: Opc = BO_Rem; break; 13632 case tok::plus: Opc = BO_Add; break; 13633 case tok::minus: Opc = BO_Sub; break; 13634 case tok::lessless: Opc = BO_Shl; break; 13635 case tok::greatergreater: Opc = BO_Shr; break; 13636 case tok::lessequal: Opc = BO_LE; break; 13637 case tok::less: Opc = BO_LT; break; 13638 case tok::greaterequal: Opc = BO_GE; break; 13639 case tok::greater: Opc = BO_GT; break; 13640 case tok::exclaimequal: Opc = BO_NE; break; 13641 case tok::equalequal: Opc = BO_EQ; break; 13642 case tok::spaceship: Opc = BO_Cmp; break; 13643 case tok::amp: Opc = BO_And; break; 13644 case tok::caret: Opc = BO_Xor; break; 13645 case tok::pipe: Opc = BO_Or; break; 13646 case tok::ampamp: Opc = BO_LAnd; break; 13647 case tok::pipepipe: Opc = BO_LOr; break; 13648 case tok::equal: Opc = BO_Assign; break; 13649 case tok::starequal: Opc = BO_MulAssign; break; 13650 case tok::slashequal: Opc = BO_DivAssign; break; 13651 case tok::percentequal: Opc = BO_RemAssign; break; 13652 case tok::plusequal: Opc = BO_AddAssign; break; 13653 case tok::minusequal: Opc = BO_SubAssign; break; 13654 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13655 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13656 case tok::ampequal: Opc = BO_AndAssign; break; 13657 case tok::caretequal: Opc = BO_XorAssign; break; 13658 case tok::pipeequal: Opc = BO_OrAssign; break; 13659 case tok::comma: Opc = BO_Comma; break; 13660 } 13661 return Opc; 13662 } 13663 13664 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13665 tok::TokenKind Kind) { 13666 UnaryOperatorKind Opc; 13667 switch (Kind) { 13668 default: llvm_unreachable("Unknown unary op!"); 13669 case tok::plusplus: Opc = UO_PreInc; break; 13670 case tok::minusminus: Opc = UO_PreDec; break; 13671 case tok::amp: Opc = UO_AddrOf; break; 13672 case tok::star: Opc = UO_Deref; break; 13673 case tok::plus: Opc = UO_Plus; break; 13674 case tok::minus: Opc = UO_Minus; break; 13675 case tok::tilde: Opc = UO_Not; break; 13676 case tok::exclaim: Opc = UO_LNot; break; 13677 case tok::kw___real: Opc = UO_Real; break; 13678 case tok::kw___imag: Opc = UO_Imag; break; 13679 case tok::kw___extension__: Opc = UO_Extension; break; 13680 } 13681 return Opc; 13682 } 13683 13684 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13685 /// This warning suppressed in the event of macro expansions. 13686 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13687 SourceLocation OpLoc, bool IsBuiltin) { 13688 if (S.inTemplateInstantiation()) 13689 return; 13690 if (S.isUnevaluatedContext()) 13691 return; 13692 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13693 return; 13694 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13695 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13696 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13697 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13698 if (!LHSDeclRef || !RHSDeclRef || 13699 LHSDeclRef->getLocation().isMacroID() || 13700 RHSDeclRef->getLocation().isMacroID()) 13701 return; 13702 const ValueDecl *LHSDecl = 13703 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13704 const ValueDecl *RHSDecl = 13705 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13706 if (LHSDecl != RHSDecl) 13707 return; 13708 if (LHSDecl->getType().isVolatileQualified()) 13709 return; 13710 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13711 if (RefTy->getPointeeType().isVolatileQualified()) 13712 return; 13713 13714 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13715 : diag::warn_self_assignment_overloaded) 13716 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13717 << RHSExpr->getSourceRange(); 13718 } 13719 13720 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13721 /// is usually indicative of introspection within the Objective-C pointer. 13722 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13723 SourceLocation OpLoc) { 13724 if (!S.getLangOpts().ObjC) 13725 return; 13726 13727 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13728 const Expr *LHS = L.get(); 13729 const Expr *RHS = R.get(); 13730 13731 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13732 ObjCPointerExpr = LHS; 13733 OtherExpr = RHS; 13734 } 13735 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13736 ObjCPointerExpr = RHS; 13737 OtherExpr = LHS; 13738 } 13739 13740 // This warning is deliberately made very specific to reduce false 13741 // positives with logic that uses '&' for hashing. This logic mainly 13742 // looks for code trying to introspect into tagged pointers, which 13743 // code should generally never do. 13744 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13745 unsigned Diag = diag::warn_objc_pointer_masking; 13746 // Determine if we are introspecting the result of performSelectorXXX. 13747 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13748 // Special case messages to -performSelector and friends, which 13749 // can return non-pointer values boxed in a pointer value. 13750 // Some clients may wish to silence warnings in this subcase. 13751 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13752 Selector S = ME->getSelector(); 13753 StringRef SelArg0 = S.getNameForSlot(0); 13754 if (SelArg0.startswith("performSelector")) 13755 Diag = diag::warn_objc_pointer_masking_performSelector; 13756 } 13757 13758 S.Diag(OpLoc, Diag) 13759 << ObjCPointerExpr->getSourceRange(); 13760 } 13761 } 13762 13763 static NamedDecl *getDeclFromExpr(Expr *E) { 13764 if (!E) 13765 return nullptr; 13766 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13767 return DRE->getDecl(); 13768 if (auto *ME = dyn_cast<MemberExpr>(E)) 13769 return ME->getMemberDecl(); 13770 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13771 return IRE->getDecl(); 13772 return nullptr; 13773 } 13774 13775 // This helper function promotes a binary operator's operands (which are of a 13776 // half vector type) to a vector of floats and then truncates the result to 13777 // a vector of either half or short. 13778 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13779 BinaryOperatorKind Opc, QualType ResultTy, 13780 ExprValueKind VK, ExprObjectKind OK, 13781 bool IsCompAssign, SourceLocation OpLoc, 13782 FPOptionsOverride FPFeatures) { 13783 auto &Context = S.getASTContext(); 13784 assert((isVector(ResultTy, Context.HalfTy) || 13785 isVector(ResultTy, Context.ShortTy)) && 13786 "Result must be a vector of half or short"); 13787 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13788 isVector(RHS.get()->getType(), Context.HalfTy) && 13789 "both operands expected to be a half vector"); 13790 13791 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13792 QualType BinOpResTy = RHS.get()->getType(); 13793 13794 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13795 // change BinOpResTy to a vector of ints. 13796 if (isVector(ResultTy, Context.ShortTy)) 13797 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13798 13799 if (IsCompAssign) 13800 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13801 ResultTy, VK, OK, OpLoc, FPFeatures, 13802 BinOpResTy, BinOpResTy); 13803 13804 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13805 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13806 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13807 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13808 } 13809 13810 static std::pair<ExprResult, ExprResult> 13811 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13812 Expr *RHSExpr) { 13813 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13814 if (!S.Context.isDependenceAllowed()) { 13815 // C cannot handle TypoExpr nodes on either side of a binop because it 13816 // doesn't handle dependent types properly, so make sure any TypoExprs have 13817 // been dealt with before checking the operands. 13818 LHS = S.CorrectDelayedTyposInExpr(LHS); 13819 RHS = S.CorrectDelayedTyposInExpr( 13820 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13821 [Opc, LHS](Expr *E) { 13822 if (Opc != BO_Assign) 13823 return ExprResult(E); 13824 // Avoid correcting the RHS to the same Expr as the LHS. 13825 Decl *D = getDeclFromExpr(E); 13826 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13827 }); 13828 } 13829 return std::make_pair(LHS, RHS); 13830 } 13831 13832 /// Returns true if conversion between vectors of halfs and vectors of floats 13833 /// is needed. 13834 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13835 Expr *E0, Expr *E1 = nullptr) { 13836 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13837 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13838 return false; 13839 13840 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13841 QualType Ty = E->IgnoreImplicit()->getType(); 13842 13843 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13844 // to vectors of floats. Although the element type of the vectors is __fp16, 13845 // the vectors shouldn't be treated as storage-only types. See the 13846 // discussion here: https://reviews.llvm.org/rG825235c140e7 13847 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13848 if (VT->getVectorKind() == VectorType::NeonVector) 13849 return false; 13850 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13851 } 13852 return false; 13853 }; 13854 13855 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13856 } 13857 13858 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13859 /// operator @p Opc at location @c TokLoc. This routine only supports 13860 /// built-in operations; ActOnBinOp handles overloaded operators. 13861 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13862 BinaryOperatorKind Opc, 13863 Expr *LHSExpr, Expr *RHSExpr) { 13864 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13865 // The syntax only allows initializer lists on the RHS of assignment, 13866 // so we don't need to worry about accepting invalid code for 13867 // non-assignment operators. 13868 // C++11 5.17p9: 13869 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13870 // of x = {} is x = T(). 13871 InitializationKind Kind = InitializationKind::CreateDirectList( 13872 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13873 InitializedEntity Entity = 13874 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13875 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13876 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13877 if (Init.isInvalid()) 13878 return Init; 13879 RHSExpr = Init.get(); 13880 } 13881 13882 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13883 QualType ResultTy; // Result type of the binary operator. 13884 // The following two variables are used for compound assignment operators 13885 QualType CompLHSTy; // Type of LHS after promotions for computation 13886 QualType CompResultTy; // Type of computation result 13887 ExprValueKind VK = VK_RValue; 13888 ExprObjectKind OK = OK_Ordinary; 13889 bool ConvertHalfVec = false; 13890 13891 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13892 if (!LHS.isUsable() || !RHS.isUsable()) 13893 return ExprError(); 13894 13895 if (getLangOpts().OpenCL) { 13896 QualType LHSTy = LHSExpr->getType(); 13897 QualType RHSTy = RHSExpr->getType(); 13898 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13899 // the ATOMIC_VAR_INIT macro. 13900 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13901 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13902 if (BO_Assign == Opc) 13903 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13904 else 13905 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13906 return ExprError(); 13907 } 13908 13909 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13910 // only with a builtin functions and therefore should be disallowed here. 13911 if (LHSTy->isImageType() || RHSTy->isImageType() || 13912 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13913 LHSTy->isPipeType() || RHSTy->isPipeType() || 13914 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13915 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13916 return ExprError(); 13917 } 13918 } 13919 13920 switch (Opc) { 13921 case BO_Assign: 13922 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13923 if (getLangOpts().CPlusPlus && 13924 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13925 VK = LHS.get()->getValueKind(); 13926 OK = LHS.get()->getObjectKind(); 13927 } 13928 if (!ResultTy.isNull()) { 13929 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13930 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13931 13932 // Avoid copying a block to the heap if the block is assigned to a local 13933 // auto variable that is declared in the same scope as the block. This 13934 // optimization is unsafe if the local variable is declared in an outer 13935 // scope. For example: 13936 // 13937 // BlockTy b; 13938 // { 13939 // b = ^{...}; 13940 // } 13941 // // It is unsafe to invoke the block here if it wasn't copied to the 13942 // // heap. 13943 // b(); 13944 13945 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13946 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13947 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13948 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13949 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13950 13951 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13952 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13953 NTCUC_Assignment, NTCUK_Copy); 13954 } 13955 RecordModifiableNonNullParam(*this, LHS.get()); 13956 break; 13957 case BO_PtrMemD: 13958 case BO_PtrMemI: 13959 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13960 Opc == BO_PtrMemI); 13961 break; 13962 case BO_Mul: 13963 case BO_Div: 13964 ConvertHalfVec = true; 13965 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13966 Opc == BO_Div); 13967 break; 13968 case BO_Rem: 13969 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13970 break; 13971 case BO_Add: 13972 ConvertHalfVec = true; 13973 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13974 break; 13975 case BO_Sub: 13976 ConvertHalfVec = true; 13977 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13978 break; 13979 case BO_Shl: 13980 case BO_Shr: 13981 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13982 break; 13983 case BO_LE: 13984 case BO_LT: 13985 case BO_GE: 13986 case BO_GT: 13987 ConvertHalfVec = true; 13988 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13989 break; 13990 case BO_EQ: 13991 case BO_NE: 13992 ConvertHalfVec = true; 13993 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13994 break; 13995 case BO_Cmp: 13996 ConvertHalfVec = true; 13997 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13998 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13999 break; 14000 case BO_And: 14001 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14002 LLVM_FALLTHROUGH; 14003 case BO_Xor: 14004 case BO_Or: 14005 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14006 break; 14007 case BO_LAnd: 14008 case BO_LOr: 14009 ConvertHalfVec = true; 14010 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14011 break; 14012 case BO_MulAssign: 14013 case BO_DivAssign: 14014 ConvertHalfVec = true; 14015 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14016 Opc == BO_DivAssign); 14017 CompLHSTy = CompResultTy; 14018 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14019 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14020 break; 14021 case BO_RemAssign: 14022 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14023 CompLHSTy = CompResultTy; 14024 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14025 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14026 break; 14027 case BO_AddAssign: 14028 ConvertHalfVec = true; 14029 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14030 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14031 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14032 break; 14033 case BO_SubAssign: 14034 ConvertHalfVec = true; 14035 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14036 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14037 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14038 break; 14039 case BO_ShlAssign: 14040 case BO_ShrAssign: 14041 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14042 CompLHSTy = CompResultTy; 14043 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14044 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14045 break; 14046 case BO_AndAssign: 14047 case BO_OrAssign: // fallthrough 14048 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14049 LLVM_FALLTHROUGH; 14050 case BO_XorAssign: 14051 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14052 CompLHSTy = CompResultTy; 14053 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14054 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14055 break; 14056 case BO_Comma: 14057 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14058 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14059 VK = RHS.get()->getValueKind(); 14060 OK = RHS.get()->getObjectKind(); 14061 } 14062 break; 14063 } 14064 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14065 return ExprError(); 14066 14067 // Some of the binary operations require promoting operands of half vector to 14068 // float vectors and truncating the result back to half vector. For now, we do 14069 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14070 // arm64). 14071 assert( 14072 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14073 isVector(LHS.get()->getType(), Context.HalfTy)) && 14074 "both sides are half vectors or neither sides are"); 14075 ConvertHalfVec = 14076 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14077 14078 // Check for array bounds violations for both sides of the BinaryOperator 14079 CheckArrayAccess(LHS.get()); 14080 CheckArrayAccess(RHS.get()); 14081 14082 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14083 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14084 &Context.Idents.get("object_setClass"), 14085 SourceLocation(), LookupOrdinaryName); 14086 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14087 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14088 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14089 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14090 "object_setClass(") 14091 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14092 ",") 14093 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14094 } 14095 else 14096 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14097 } 14098 else if (const ObjCIvarRefExpr *OIRE = 14099 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14100 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14101 14102 // Opc is not a compound assignment if CompResultTy is null. 14103 if (CompResultTy.isNull()) { 14104 if (ConvertHalfVec) 14105 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14106 OpLoc, CurFPFeatureOverrides()); 14107 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14108 VK, OK, OpLoc, CurFPFeatureOverrides()); 14109 } 14110 14111 // Handle compound assignments. 14112 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14113 OK_ObjCProperty) { 14114 VK = VK_LValue; 14115 OK = LHS.get()->getObjectKind(); 14116 } 14117 14118 // The LHS is not converted to the result type for fixed-point compound 14119 // assignment as the common type is computed on demand. Reset the CompLHSTy 14120 // to the LHS type we would have gotten after unary conversions. 14121 if (CompResultTy->isFixedPointType()) 14122 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14123 14124 if (ConvertHalfVec) 14125 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14126 OpLoc, CurFPFeatureOverrides()); 14127 14128 return CompoundAssignOperator::Create( 14129 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14130 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14131 } 14132 14133 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14134 /// operators are mixed in a way that suggests that the programmer forgot that 14135 /// comparison operators have higher precedence. The most typical example of 14136 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14137 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14138 SourceLocation OpLoc, Expr *LHSExpr, 14139 Expr *RHSExpr) { 14140 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14141 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14142 14143 // Check that one of the sides is a comparison operator and the other isn't. 14144 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14145 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14146 if (isLeftComp == isRightComp) 14147 return; 14148 14149 // Bitwise operations are sometimes used as eager logical ops. 14150 // Don't diagnose this. 14151 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14152 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14153 if (isLeftBitwise || isRightBitwise) 14154 return; 14155 14156 SourceRange DiagRange = isLeftComp 14157 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14158 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14159 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14160 SourceRange ParensRange = 14161 isLeftComp 14162 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14163 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14164 14165 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14166 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14167 SuggestParentheses(Self, OpLoc, 14168 Self.PDiag(diag::note_precedence_silence) << OpStr, 14169 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14170 SuggestParentheses(Self, OpLoc, 14171 Self.PDiag(diag::note_precedence_bitwise_first) 14172 << BinaryOperator::getOpcodeStr(Opc), 14173 ParensRange); 14174 } 14175 14176 /// It accepts a '&&' expr that is inside a '||' one. 14177 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14178 /// in parentheses. 14179 static void 14180 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14181 BinaryOperator *Bop) { 14182 assert(Bop->getOpcode() == BO_LAnd); 14183 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14184 << Bop->getSourceRange() << OpLoc; 14185 SuggestParentheses(Self, Bop->getOperatorLoc(), 14186 Self.PDiag(diag::note_precedence_silence) 14187 << Bop->getOpcodeStr(), 14188 Bop->getSourceRange()); 14189 } 14190 14191 /// Returns true if the given expression can be evaluated as a constant 14192 /// 'true'. 14193 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14194 bool Res; 14195 return !E->isValueDependent() && 14196 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14197 } 14198 14199 /// Returns true if the given expression can be evaluated as a constant 14200 /// 'false'. 14201 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14202 bool Res; 14203 return !E->isValueDependent() && 14204 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14205 } 14206 14207 /// Look for '&&' in the left hand of a '||' expr. 14208 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14209 Expr *LHSExpr, Expr *RHSExpr) { 14210 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14211 if (Bop->getOpcode() == BO_LAnd) { 14212 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14213 if (EvaluatesAsFalse(S, RHSExpr)) 14214 return; 14215 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14216 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14217 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14218 } else if (Bop->getOpcode() == BO_LOr) { 14219 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14220 // If it's "a || b && 1 || c" we didn't warn earlier for 14221 // "a || b && 1", but warn now. 14222 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14223 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14224 } 14225 } 14226 } 14227 } 14228 14229 /// Look for '&&' in the right hand of a '||' expr. 14230 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14231 Expr *LHSExpr, Expr *RHSExpr) { 14232 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14233 if (Bop->getOpcode() == BO_LAnd) { 14234 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14235 if (EvaluatesAsFalse(S, LHSExpr)) 14236 return; 14237 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14238 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14239 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14240 } 14241 } 14242 } 14243 14244 /// Look for bitwise op in the left or right hand of a bitwise op with 14245 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14246 /// the '&' expression in parentheses. 14247 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14248 SourceLocation OpLoc, Expr *SubExpr) { 14249 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14250 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14251 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14252 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14253 << Bop->getSourceRange() << OpLoc; 14254 SuggestParentheses(S, Bop->getOperatorLoc(), 14255 S.PDiag(diag::note_precedence_silence) 14256 << Bop->getOpcodeStr(), 14257 Bop->getSourceRange()); 14258 } 14259 } 14260 } 14261 14262 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14263 Expr *SubExpr, StringRef Shift) { 14264 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14265 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14266 StringRef Op = Bop->getOpcodeStr(); 14267 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14268 << Bop->getSourceRange() << OpLoc << Shift << Op; 14269 SuggestParentheses(S, Bop->getOperatorLoc(), 14270 S.PDiag(diag::note_precedence_silence) << Op, 14271 Bop->getSourceRange()); 14272 } 14273 } 14274 } 14275 14276 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14277 Expr *LHSExpr, Expr *RHSExpr) { 14278 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14279 if (!OCE) 14280 return; 14281 14282 FunctionDecl *FD = OCE->getDirectCallee(); 14283 if (!FD || !FD->isOverloadedOperator()) 14284 return; 14285 14286 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14287 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14288 return; 14289 14290 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14291 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14292 << (Kind == OO_LessLess); 14293 SuggestParentheses(S, OCE->getOperatorLoc(), 14294 S.PDiag(diag::note_precedence_silence) 14295 << (Kind == OO_LessLess ? "<<" : ">>"), 14296 OCE->getSourceRange()); 14297 SuggestParentheses( 14298 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14299 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14300 } 14301 14302 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14303 /// precedence. 14304 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14305 SourceLocation OpLoc, Expr *LHSExpr, 14306 Expr *RHSExpr){ 14307 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14308 if (BinaryOperator::isBitwiseOp(Opc)) 14309 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14310 14311 // Diagnose "arg1 & arg2 | arg3" 14312 if ((Opc == BO_Or || Opc == BO_Xor) && 14313 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14314 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14315 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14316 } 14317 14318 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14319 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14320 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14321 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14322 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14323 } 14324 14325 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14326 || Opc == BO_Shr) { 14327 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14328 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14329 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14330 } 14331 14332 // Warn on overloaded shift operators and comparisons, such as: 14333 // cout << 5 == 4; 14334 if (BinaryOperator::isComparisonOp(Opc)) 14335 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14336 } 14337 14338 // Binary Operators. 'Tok' is the token for the operator. 14339 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14340 tok::TokenKind Kind, 14341 Expr *LHSExpr, Expr *RHSExpr) { 14342 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14343 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14344 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14345 14346 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14347 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14348 14349 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14350 } 14351 14352 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14353 UnresolvedSetImpl &Functions) { 14354 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14355 if (OverOp != OO_None && OverOp != OO_Equal) 14356 LookupOverloadedOperatorName(OverOp, S, Functions); 14357 14358 // In C++20 onwards, we may have a second operator to look up. 14359 if (getLangOpts().CPlusPlus20) { 14360 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14361 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14362 } 14363 } 14364 14365 /// Build an overloaded binary operator expression in the given scope. 14366 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14367 BinaryOperatorKind Opc, 14368 Expr *LHS, Expr *RHS) { 14369 switch (Opc) { 14370 case BO_Assign: 14371 case BO_DivAssign: 14372 case BO_RemAssign: 14373 case BO_SubAssign: 14374 case BO_AndAssign: 14375 case BO_OrAssign: 14376 case BO_XorAssign: 14377 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14378 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14379 break; 14380 default: 14381 break; 14382 } 14383 14384 // Find all of the overloaded operators visible from this point. 14385 UnresolvedSet<16> Functions; 14386 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14387 14388 // Build the (potentially-overloaded, potentially-dependent) 14389 // binary operation. 14390 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14391 } 14392 14393 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14394 BinaryOperatorKind Opc, 14395 Expr *LHSExpr, Expr *RHSExpr) { 14396 ExprResult LHS, RHS; 14397 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14398 if (!LHS.isUsable() || !RHS.isUsable()) 14399 return ExprError(); 14400 LHSExpr = LHS.get(); 14401 RHSExpr = RHS.get(); 14402 14403 // We want to end up calling one of checkPseudoObjectAssignment 14404 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14405 // both expressions are overloadable or either is type-dependent), 14406 // or CreateBuiltinBinOp (in any other case). We also want to get 14407 // any placeholder types out of the way. 14408 14409 // Handle pseudo-objects in the LHS. 14410 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14411 // Assignments with a pseudo-object l-value need special analysis. 14412 if (pty->getKind() == BuiltinType::PseudoObject && 14413 BinaryOperator::isAssignmentOp(Opc)) 14414 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14415 14416 // Don't resolve overloads if the other type is overloadable. 14417 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14418 // We can't actually test that if we still have a placeholder, 14419 // though. Fortunately, none of the exceptions we see in that 14420 // code below are valid when the LHS is an overload set. Note 14421 // that an overload set can be dependently-typed, but it never 14422 // instantiates to having an overloadable type. 14423 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14424 if (resolvedRHS.isInvalid()) return ExprError(); 14425 RHSExpr = resolvedRHS.get(); 14426 14427 if (RHSExpr->isTypeDependent() || 14428 RHSExpr->getType()->isOverloadableType()) 14429 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14430 } 14431 14432 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14433 // template, diagnose the missing 'template' keyword instead of diagnosing 14434 // an invalid use of a bound member function. 14435 // 14436 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14437 // to C++1z [over.over]/1.4, but we already checked for that case above. 14438 if (Opc == BO_LT && inTemplateInstantiation() && 14439 (pty->getKind() == BuiltinType::BoundMember || 14440 pty->getKind() == BuiltinType::Overload)) { 14441 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14442 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14443 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14444 return isa<FunctionTemplateDecl>(ND); 14445 })) { 14446 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14447 : OE->getNameLoc(), 14448 diag::err_template_kw_missing) 14449 << OE->getName().getAsString() << ""; 14450 return ExprError(); 14451 } 14452 } 14453 14454 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14455 if (LHS.isInvalid()) return ExprError(); 14456 LHSExpr = LHS.get(); 14457 } 14458 14459 // Handle pseudo-objects in the RHS. 14460 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14461 // An overload in the RHS can potentially be resolved by the type 14462 // being assigned to. 14463 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14464 if (getLangOpts().CPlusPlus && 14465 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14466 LHSExpr->getType()->isOverloadableType())) 14467 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14468 14469 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14470 } 14471 14472 // Don't resolve overloads if the other type is overloadable. 14473 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14474 LHSExpr->getType()->isOverloadableType()) 14475 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14476 14477 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14478 if (!resolvedRHS.isUsable()) return ExprError(); 14479 RHSExpr = resolvedRHS.get(); 14480 } 14481 14482 if (getLangOpts().CPlusPlus) { 14483 // If either expression is type-dependent, always build an 14484 // overloaded op. 14485 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14486 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14487 14488 // Otherwise, build an overloaded op if either expression has an 14489 // overloadable type. 14490 if (LHSExpr->getType()->isOverloadableType() || 14491 RHSExpr->getType()->isOverloadableType()) 14492 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14493 } 14494 14495 if (getLangOpts().RecoveryAST && 14496 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14497 assert(!getLangOpts().CPlusPlus); 14498 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14499 "Should only occur in error-recovery path."); 14500 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14501 // C [6.15.16] p3: 14502 // An assignment expression has the value of the left operand after the 14503 // assignment, but is not an lvalue. 14504 return CompoundAssignOperator::Create( 14505 Context, LHSExpr, RHSExpr, Opc, 14506 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14507 OpLoc, CurFPFeatureOverrides()); 14508 QualType ResultType; 14509 switch (Opc) { 14510 case BO_Assign: 14511 ResultType = LHSExpr->getType().getUnqualifiedType(); 14512 break; 14513 case BO_LT: 14514 case BO_GT: 14515 case BO_LE: 14516 case BO_GE: 14517 case BO_EQ: 14518 case BO_NE: 14519 case BO_LAnd: 14520 case BO_LOr: 14521 // These operators have a fixed result type regardless of operands. 14522 ResultType = Context.IntTy; 14523 break; 14524 case BO_Comma: 14525 ResultType = RHSExpr->getType(); 14526 break; 14527 default: 14528 ResultType = Context.DependentTy; 14529 break; 14530 } 14531 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14532 VK_RValue, OK_Ordinary, OpLoc, 14533 CurFPFeatureOverrides()); 14534 } 14535 14536 // Build a built-in binary operation. 14537 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14538 } 14539 14540 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14541 if (T.isNull() || T->isDependentType()) 14542 return false; 14543 14544 if (!T->isPromotableIntegerType()) 14545 return true; 14546 14547 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14548 } 14549 14550 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14551 UnaryOperatorKind Opc, 14552 Expr *InputExpr) { 14553 ExprResult Input = InputExpr; 14554 ExprValueKind VK = VK_RValue; 14555 ExprObjectKind OK = OK_Ordinary; 14556 QualType resultType; 14557 bool CanOverflow = false; 14558 14559 bool ConvertHalfVec = false; 14560 if (getLangOpts().OpenCL) { 14561 QualType Ty = InputExpr->getType(); 14562 // The only legal unary operation for atomics is '&'. 14563 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14564 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14565 // only with a builtin functions and therefore should be disallowed here. 14566 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14567 || Ty->isBlockPointerType())) { 14568 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14569 << InputExpr->getType() 14570 << Input.get()->getSourceRange()); 14571 } 14572 } 14573 14574 switch (Opc) { 14575 case UO_PreInc: 14576 case UO_PreDec: 14577 case UO_PostInc: 14578 case UO_PostDec: 14579 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14580 OpLoc, 14581 Opc == UO_PreInc || 14582 Opc == UO_PostInc, 14583 Opc == UO_PreInc || 14584 Opc == UO_PreDec); 14585 CanOverflow = isOverflowingIntegerType(Context, resultType); 14586 break; 14587 case UO_AddrOf: 14588 resultType = CheckAddressOfOperand(Input, OpLoc); 14589 CheckAddressOfNoDeref(InputExpr); 14590 RecordModifiableNonNullParam(*this, InputExpr); 14591 break; 14592 case UO_Deref: { 14593 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14594 if (Input.isInvalid()) return ExprError(); 14595 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14596 break; 14597 } 14598 case UO_Plus: 14599 case UO_Minus: 14600 CanOverflow = Opc == UO_Minus && 14601 isOverflowingIntegerType(Context, Input.get()->getType()); 14602 Input = UsualUnaryConversions(Input.get()); 14603 if (Input.isInvalid()) return ExprError(); 14604 // Unary plus and minus require promoting an operand of half vector to a 14605 // float vector and truncating the result back to a half vector. For now, we 14606 // do this only when HalfArgsAndReturns is set (that is, when the target is 14607 // arm or arm64). 14608 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14609 14610 // If the operand is a half vector, promote it to a float vector. 14611 if (ConvertHalfVec) 14612 Input = convertVector(Input.get(), Context.FloatTy, *this); 14613 resultType = Input.get()->getType(); 14614 if (resultType->isDependentType()) 14615 break; 14616 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14617 break; 14618 else if (resultType->isVectorType() && 14619 // The z vector extensions don't allow + or - with bool vectors. 14620 (!Context.getLangOpts().ZVector || 14621 resultType->castAs<VectorType>()->getVectorKind() != 14622 VectorType::AltiVecBool)) 14623 break; 14624 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14625 Opc == UO_Plus && 14626 resultType->isPointerType()) 14627 break; 14628 14629 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14630 << resultType << Input.get()->getSourceRange()); 14631 14632 case UO_Not: // bitwise complement 14633 Input = UsualUnaryConversions(Input.get()); 14634 if (Input.isInvalid()) 14635 return ExprError(); 14636 resultType = Input.get()->getType(); 14637 if (resultType->isDependentType()) 14638 break; 14639 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14640 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14641 // C99 does not support '~' for complex conjugation. 14642 Diag(OpLoc, diag::ext_integer_complement_complex) 14643 << resultType << Input.get()->getSourceRange(); 14644 else if (resultType->hasIntegerRepresentation()) 14645 break; 14646 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14647 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14648 // on vector float types. 14649 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14650 if (!T->isIntegerType()) 14651 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14652 << resultType << Input.get()->getSourceRange()); 14653 } else { 14654 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14655 << resultType << Input.get()->getSourceRange()); 14656 } 14657 break; 14658 14659 case UO_LNot: // logical negation 14660 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14661 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14662 if (Input.isInvalid()) return ExprError(); 14663 resultType = Input.get()->getType(); 14664 14665 // Though we still have to promote half FP to float... 14666 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14667 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14668 resultType = Context.FloatTy; 14669 } 14670 14671 if (resultType->isDependentType()) 14672 break; 14673 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14674 // C99 6.5.3.3p1: ok, fallthrough; 14675 if (Context.getLangOpts().CPlusPlus) { 14676 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14677 // operand contextually converted to bool. 14678 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14679 ScalarTypeToBooleanCastKind(resultType)); 14680 } else if (Context.getLangOpts().OpenCL && 14681 Context.getLangOpts().OpenCLVersion < 120) { 14682 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14683 // operate on scalar float types. 14684 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14685 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14686 << resultType << Input.get()->getSourceRange()); 14687 } 14688 } else if (resultType->isExtVectorType()) { 14689 if (Context.getLangOpts().OpenCL && 14690 Context.getLangOpts().OpenCLVersion < 120 && 14691 !Context.getLangOpts().OpenCLCPlusPlus) { 14692 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14693 // operate on vector float types. 14694 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14695 if (!T->isIntegerType()) 14696 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14697 << resultType << Input.get()->getSourceRange()); 14698 } 14699 // Vector logical not returns the signed variant of the operand type. 14700 resultType = GetSignedVectorType(resultType); 14701 break; 14702 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14703 const VectorType *VTy = resultType->castAs<VectorType>(); 14704 if (VTy->getVectorKind() != VectorType::GenericVector) 14705 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14706 << resultType << Input.get()->getSourceRange()); 14707 14708 // Vector logical not returns the signed variant of the operand type. 14709 resultType = GetSignedVectorType(resultType); 14710 break; 14711 } else { 14712 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14713 << resultType << Input.get()->getSourceRange()); 14714 } 14715 14716 // LNot always has type int. C99 6.5.3.3p5. 14717 // In C++, it's bool. C++ 5.3.1p8 14718 resultType = Context.getLogicalOperationType(); 14719 break; 14720 case UO_Real: 14721 case UO_Imag: 14722 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14723 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14724 // complex l-values to ordinary l-values and all other values to r-values. 14725 if (Input.isInvalid()) return ExprError(); 14726 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14727 if (Input.get()->getValueKind() != VK_RValue && 14728 Input.get()->getObjectKind() == OK_Ordinary) 14729 VK = Input.get()->getValueKind(); 14730 } else if (!getLangOpts().CPlusPlus) { 14731 // In C, a volatile scalar is read by __imag. In C++, it is not. 14732 Input = DefaultLvalueConversion(Input.get()); 14733 } 14734 break; 14735 case UO_Extension: 14736 resultType = Input.get()->getType(); 14737 VK = Input.get()->getValueKind(); 14738 OK = Input.get()->getObjectKind(); 14739 break; 14740 case UO_Coawait: 14741 // It's unnecessary to represent the pass-through operator co_await in the 14742 // AST; just return the input expression instead. 14743 assert(!Input.get()->getType()->isDependentType() && 14744 "the co_await expression must be non-dependant before " 14745 "building operator co_await"); 14746 return Input; 14747 } 14748 if (resultType.isNull() || Input.isInvalid()) 14749 return ExprError(); 14750 14751 // Check for array bounds violations in the operand of the UnaryOperator, 14752 // except for the '*' and '&' operators that have to be handled specially 14753 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14754 // that are explicitly defined as valid by the standard). 14755 if (Opc != UO_AddrOf && Opc != UO_Deref) 14756 CheckArrayAccess(Input.get()); 14757 14758 auto *UO = 14759 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14760 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14761 14762 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14763 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14764 !isUnevaluatedContext()) 14765 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14766 14767 // Convert the result back to a half vector. 14768 if (ConvertHalfVec) 14769 return convertVector(UO, Context.HalfTy, *this); 14770 return UO; 14771 } 14772 14773 /// Determine whether the given expression is a qualified member 14774 /// access expression, of a form that could be turned into a pointer to member 14775 /// with the address-of operator. 14776 bool Sema::isQualifiedMemberAccess(Expr *E) { 14777 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14778 if (!DRE->getQualifier()) 14779 return false; 14780 14781 ValueDecl *VD = DRE->getDecl(); 14782 if (!VD->isCXXClassMember()) 14783 return false; 14784 14785 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14786 return true; 14787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14788 return Method->isInstance(); 14789 14790 return false; 14791 } 14792 14793 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14794 if (!ULE->getQualifier()) 14795 return false; 14796 14797 for (NamedDecl *D : ULE->decls()) { 14798 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14799 if (Method->isInstance()) 14800 return true; 14801 } else { 14802 // Overload set does not contain methods. 14803 break; 14804 } 14805 } 14806 14807 return false; 14808 } 14809 14810 return false; 14811 } 14812 14813 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14814 UnaryOperatorKind Opc, Expr *Input) { 14815 // First things first: handle placeholders so that the 14816 // overloaded-operator check considers the right type. 14817 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14818 // Increment and decrement of pseudo-object references. 14819 if (pty->getKind() == BuiltinType::PseudoObject && 14820 UnaryOperator::isIncrementDecrementOp(Opc)) 14821 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14822 14823 // extension is always a builtin operator. 14824 if (Opc == UO_Extension) 14825 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14826 14827 // & gets special logic for several kinds of placeholder. 14828 // The builtin code knows what to do. 14829 if (Opc == UO_AddrOf && 14830 (pty->getKind() == BuiltinType::Overload || 14831 pty->getKind() == BuiltinType::UnknownAny || 14832 pty->getKind() == BuiltinType::BoundMember)) 14833 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14834 14835 // Anything else needs to be handled now. 14836 ExprResult Result = CheckPlaceholderExpr(Input); 14837 if (Result.isInvalid()) return ExprError(); 14838 Input = Result.get(); 14839 } 14840 14841 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14842 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14843 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14844 // Find all of the overloaded operators visible from this point. 14845 UnresolvedSet<16> Functions; 14846 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14847 if (S && OverOp != OO_None) 14848 LookupOverloadedOperatorName(OverOp, S, Functions); 14849 14850 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14851 } 14852 14853 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14854 } 14855 14856 // Unary Operators. 'Tok' is the token for the operator. 14857 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14858 tok::TokenKind Op, Expr *Input) { 14859 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14860 } 14861 14862 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14863 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14864 LabelDecl *TheDecl) { 14865 TheDecl->markUsed(Context); 14866 // Create the AST node. The address of a label always has type 'void*'. 14867 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14868 Context.getPointerType(Context.VoidTy)); 14869 } 14870 14871 void Sema::ActOnStartStmtExpr() { 14872 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14873 } 14874 14875 void Sema::ActOnStmtExprError() { 14876 // Note that function is also called by TreeTransform when leaving a 14877 // StmtExpr scope without rebuilding anything. 14878 14879 DiscardCleanupsInEvaluationContext(); 14880 PopExpressionEvaluationContext(); 14881 } 14882 14883 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14884 SourceLocation RPLoc) { 14885 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14886 } 14887 14888 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14889 SourceLocation RPLoc, unsigned TemplateDepth) { 14890 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14891 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14892 14893 if (hasAnyUnrecoverableErrorsInThisFunction()) 14894 DiscardCleanupsInEvaluationContext(); 14895 assert(!Cleanup.exprNeedsCleanups() && 14896 "cleanups within StmtExpr not correctly bound!"); 14897 PopExpressionEvaluationContext(); 14898 14899 // FIXME: there are a variety of strange constraints to enforce here, for 14900 // example, it is not possible to goto into a stmt expression apparently. 14901 // More semantic analysis is needed. 14902 14903 // If there are sub-stmts in the compound stmt, take the type of the last one 14904 // as the type of the stmtexpr. 14905 QualType Ty = Context.VoidTy; 14906 bool StmtExprMayBindToTemp = false; 14907 if (!Compound->body_empty()) { 14908 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14909 if (const auto *LastStmt = 14910 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14911 if (const Expr *Value = LastStmt->getExprStmt()) { 14912 StmtExprMayBindToTemp = true; 14913 Ty = Value->getType(); 14914 } 14915 } 14916 } 14917 14918 // FIXME: Check that expression type is complete/non-abstract; statement 14919 // expressions are not lvalues. 14920 Expr *ResStmtExpr = 14921 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14922 if (StmtExprMayBindToTemp) 14923 return MaybeBindToTemporary(ResStmtExpr); 14924 return ResStmtExpr; 14925 } 14926 14927 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14928 if (ER.isInvalid()) 14929 return ExprError(); 14930 14931 // Do function/array conversion on the last expression, but not 14932 // lvalue-to-rvalue. However, initialize an unqualified type. 14933 ER = DefaultFunctionArrayConversion(ER.get()); 14934 if (ER.isInvalid()) 14935 return ExprError(); 14936 Expr *E = ER.get(); 14937 14938 if (E->isTypeDependent()) 14939 return E; 14940 14941 // In ARC, if the final expression ends in a consume, splice 14942 // the consume out and bind it later. In the alternate case 14943 // (when dealing with a retainable type), the result 14944 // initialization will create a produce. In both cases the 14945 // result will be +1, and we'll need to balance that out with 14946 // a bind. 14947 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14948 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14949 return Cast->getSubExpr(); 14950 14951 // FIXME: Provide a better location for the initialization. 14952 return PerformCopyInitialization( 14953 InitializedEntity::InitializeStmtExprResult( 14954 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14955 SourceLocation(), E); 14956 } 14957 14958 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14959 TypeSourceInfo *TInfo, 14960 ArrayRef<OffsetOfComponent> Components, 14961 SourceLocation RParenLoc) { 14962 QualType ArgTy = TInfo->getType(); 14963 bool Dependent = ArgTy->isDependentType(); 14964 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14965 14966 // We must have at least one component that refers to the type, and the first 14967 // one is known to be a field designator. Verify that the ArgTy represents 14968 // a struct/union/class. 14969 if (!Dependent && !ArgTy->isRecordType()) 14970 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14971 << ArgTy << TypeRange); 14972 14973 // Type must be complete per C99 7.17p3 because a declaring a variable 14974 // with an incomplete type would be ill-formed. 14975 if (!Dependent 14976 && RequireCompleteType(BuiltinLoc, ArgTy, 14977 diag::err_offsetof_incomplete_type, TypeRange)) 14978 return ExprError(); 14979 14980 bool DidWarnAboutNonPOD = false; 14981 QualType CurrentType = ArgTy; 14982 SmallVector<OffsetOfNode, 4> Comps; 14983 SmallVector<Expr*, 4> Exprs; 14984 for (const OffsetOfComponent &OC : Components) { 14985 if (OC.isBrackets) { 14986 // Offset of an array sub-field. TODO: Should we allow vector elements? 14987 if (!CurrentType->isDependentType()) { 14988 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14989 if(!AT) 14990 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14991 << CurrentType); 14992 CurrentType = AT->getElementType(); 14993 } else 14994 CurrentType = Context.DependentTy; 14995 14996 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14997 if (IdxRval.isInvalid()) 14998 return ExprError(); 14999 Expr *Idx = IdxRval.get(); 15000 15001 // The expression must be an integral expression. 15002 // FIXME: An integral constant expression? 15003 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15004 !Idx->getType()->isIntegerType()) 15005 return ExprError( 15006 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15007 << Idx->getSourceRange()); 15008 15009 // Record this array index. 15010 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15011 Exprs.push_back(Idx); 15012 continue; 15013 } 15014 15015 // Offset of a field. 15016 if (CurrentType->isDependentType()) { 15017 // We have the offset of a field, but we can't look into the dependent 15018 // type. Just record the identifier of the field. 15019 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15020 CurrentType = Context.DependentTy; 15021 continue; 15022 } 15023 15024 // We need to have a complete type to look into. 15025 if (RequireCompleteType(OC.LocStart, CurrentType, 15026 diag::err_offsetof_incomplete_type)) 15027 return ExprError(); 15028 15029 // Look for the designated field. 15030 const RecordType *RC = CurrentType->getAs<RecordType>(); 15031 if (!RC) 15032 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15033 << CurrentType); 15034 RecordDecl *RD = RC->getDecl(); 15035 15036 // C++ [lib.support.types]p5: 15037 // The macro offsetof accepts a restricted set of type arguments in this 15038 // International Standard. type shall be a POD structure or a POD union 15039 // (clause 9). 15040 // C++11 [support.types]p4: 15041 // If type is not a standard-layout class (Clause 9), the results are 15042 // undefined. 15043 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15044 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15045 unsigned DiagID = 15046 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15047 : diag::ext_offsetof_non_pod_type; 15048 15049 if (!IsSafe && !DidWarnAboutNonPOD && 15050 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15051 PDiag(DiagID) 15052 << SourceRange(Components[0].LocStart, OC.LocEnd) 15053 << CurrentType)) 15054 DidWarnAboutNonPOD = true; 15055 } 15056 15057 // Look for the field. 15058 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15059 LookupQualifiedName(R, RD); 15060 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15061 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15062 if (!MemberDecl) { 15063 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15064 MemberDecl = IndirectMemberDecl->getAnonField(); 15065 } 15066 15067 if (!MemberDecl) 15068 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15069 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15070 OC.LocEnd)); 15071 15072 // C99 7.17p3: 15073 // (If the specified member is a bit-field, the behavior is undefined.) 15074 // 15075 // We diagnose this as an error. 15076 if (MemberDecl->isBitField()) { 15077 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15078 << MemberDecl->getDeclName() 15079 << SourceRange(BuiltinLoc, RParenLoc); 15080 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15081 return ExprError(); 15082 } 15083 15084 RecordDecl *Parent = MemberDecl->getParent(); 15085 if (IndirectMemberDecl) 15086 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15087 15088 // If the member was found in a base class, introduce OffsetOfNodes for 15089 // the base class indirections. 15090 CXXBasePaths Paths; 15091 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15092 Paths)) { 15093 if (Paths.getDetectedVirtual()) { 15094 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15095 << MemberDecl->getDeclName() 15096 << SourceRange(BuiltinLoc, RParenLoc); 15097 return ExprError(); 15098 } 15099 15100 CXXBasePath &Path = Paths.front(); 15101 for (const CXXBasePathElement &B : Path) 15102 Comps.push_back(OffsetOfNode(B.Base)); 15103 } 15104 15105 if (IndirectMemberDecl) { 15106 for (auto *FI : IndirectMemberDecl->chain()) { 15107 assert(isa<FieldDecl>(FI)); 15108 Comps.push_back(OffsetOfNode(OC.LocStart, 15109 cast<FieldDecl>(FI), OC.LocEnd)); 15110 } 15111 } else 15112 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15113 15114 CurrentType = MemberDecl->getType().getNonReferenceType(); 15115 } 15116 15117 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15118 Comps, Exprs, RParenLoc); 15119 } 15120 15121 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15122 SourceLocation BuiltinLoc, 15123 SourceLocation TypeLoc, 15124 ParsedType ParsedArgTy, 15125 ArrayRef<OffsetOfComponent> Components, 15126 SourceLocation RParenLoc) { 15127 15128 TypeSourceInfo *ArgTInfo; 15129 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15130 if (ArgTy.isNull()) 15131 return ExprError(); 15132 15133 if (!ArgTInfo) 15134 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15135 15136 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15137 } 15138 15139 15140 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15141 Expr *CondExpr, 15142 Expr *LHSExpr, Expr *RHSExpr, 15143 SourceLocation RPLoc) { 15144 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15145 15146 ExprValueKind VK = VK_RValue; 15147 ExprObjectKind OK = OK_Ordinary; 15148 QualType resType; 15149 bool CondIsTrue = false; 15150 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15151 resType = Context.DependentTy; 15152 } else { 15153 // The conditional expression is required to be a constant expression. 15154 llvm::APSInt condEval(32); 15155 ExprResult CondICE = VerifyIntegerConstantExpression( 15156 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15157 if (CondICE.isInvalid()) 15158 return ExprError(); 15159 CondExpr = CondICE.get(); 15160 CondIsTrue = condEval.getZExtValue(); 15161 15162 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15163 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15164 15165 resType = ActiveExpr->getType(); 15166 VK = ActiveExpr->getValueKind(); 15167 OK = ActiveExpr->getObjectKind(); 15168 } 15169 15170 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15171 resType, VK, OK, RPLoc, CondIsTrue); 15172 } 15173 15174 //===----------------------------------------------------------------------===// 15175 // Clang Extensions. 15176 //===----------------------------------------------------------------------===// 15177 15178 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15179 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15180 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15181 15182 if (LangOpts.CPlusPlus) { 15183 MangleNumberingContext *MCtx; 15184 Decl *ManglingContextDecl; 15185 std::tie(MCtx, ManglingContextDecl) = 15186 getCurrentMangleNumberContext(Block->getDeclContext()); 15187 if (MCtx) { 15188 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15189 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15190 } 15191 } 15192 15193 PushBlockScope(CurScope, Block); 15194 CurContext->addDecl(Block); 15195 if (CurScope) 15196 PushDeclContext(CurScope, Block); 15197 else 15198 CurContext = Block; 15199 15200 getCurBlock()->HasImplicitReturnType = true; 15201 15202 // Enter a new evaluation context to insulate the block from any 15203 // cleanups from the enclosing full-expression. 15204 PushExpressionEvaluationContext( 15205 ExpressionEvaluationContext::PotentiallyEvaluated); 15206 } 15207 15208 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15209 Scope *CurScope) { 15210 assert(ParamInfo.getIdentifier() == nullptr && 15211 "block-id should have no identifier!"); 15212 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15213 BlockScopeInfo *CurBlock = getCurBlock(); 15214 15215 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15216 QualType T = Sig->getType(); 15217 15218 // FIXME: We should allow unexpanded parameter packs here, but that would, 15219 // in turn, make the block expression contain unexpanded parameter packs. 15220 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15221 // Drop the parameters. 15222 FunctionProtoType::ExtProtoInfo EPI; 15223 EPI.HasTrailingReturn = false; 15224 EPI.TypeQuals.addConst(); 15225 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15226 Sig = Context.getTrivialTypeSourceInfo(T); 15227 } 15228 15229 // GetTypeForDeclarator always produces a function type for a block 15230 // literal signature. Furthermore, it is always a FunctionProtoType 15231 // unless the function was written with a typedef. 15232 assert(T->isFunctionType() && 15233 "GetTypeForDeclarator made a non-function block signature"); 15234 15235 // Look for an explicit signature in that function type. 15236 FunctionProtoTypeLoc ExplicitSignature; 15237 15238 if ((ExplicitSignature = Sig->getTypeLoc() 15239 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15240 15241 // Check whether that explicit signature was synthesized by 15242 // GetTypeForDeclarator. If so, don't save that as part of the 15243 // written signature. 15244 if (ExplicitSignature.getLocalRangeBegin() == 15245 ExplicitSignature.getLocalRangeEnd()) { 15246 // This would be much cheaper if we stored TypeLocs instead of 15247 // TypeSourceInfos. 15248 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15249 unsigned Size = Result.getFullDataSize(); 15250 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15251 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15252 15253 ExplicitSignature = FunctionProtoTypeLoc(); 15254 } 15255 } 15256 15257 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15258 CurBlock->FunctionType = T; 15259 15260 const auto *Fn = T->castAs<FunctionType>(); 15261 QualType RetTy = Fn->getReturnType(); 15262 bool isVariadic = 15263 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15264 15265 CurBlock->TheDecl->setIsVariadic(isVariadic); 15266 15267 // Context.DependentTy is used as a placeholder for a missing block 15268 // return type. TODO: what should we do with declarators like: 15269 // ^ * { ... } 15270 // If the answer is "apply template argument deduction".... 15271 if (RetTy != Context.DependentTy) { 15272 CurBlock->ReturnType = RetTy; 15273 CurBlock->TheDecl->setBlockMissingReturnType(false); 15274 CurBlock->HasImplicitReturnType = false; 15275 } 15276 15277 // Push block parameters from the declarator if we had them. 15278 SmallVector<ParmVarDecl*, 8> Params; 15279 if (ExplicitSignature) { 15280 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15281 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15282 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15283 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15284 // Diagnose this as an extension in C17 and earlier. 15285 if (!getLangOpts().C2x) 15286 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15287 } 15288 Params.push_back(Param); 15289 } 15290 15291 // Fake up parameter variables if we have a typedef, like 15292 // ^ fntype { ... } 15293 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15294 for (const auto &I : Fn->param_types()) { 15295 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15296 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15297 Params.push_back(Param); 15298 } 15299 } 15300 15301 // Set the parameters on the block decl. 15302 if (!Params.empty()) { 15303 CurBlock->TheDecl->setParams(Params); 15304 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15305 /*CheckParameterNames=*/false); 15306 } 15307 15308 // Finally we can process decl attributes. 15309 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15310 15311 // Put the parameter variables in scope. 15312 for (auto AI : CurBlock->TheDecl->parameters()) { 15313 AI->setOwningFunction(CurBlock->TheDecl); 15314 15315 // If this has an identifier, add it to the scope stack. 15316 if (AI->getIdentifier()) { 15317 CheckShadow(CurBlock->TheScope, AI); 15318 15319 PushOnScopeChains(AI, CurBlock->TheScope); 15320 } 15321 } 15322 } 15323 15324 /// ActOnBlockError - If there is an error parsing a block, this callback 15325 /// is invoked to pop the information about the block from the action impl. 15326 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15327 // Leave the expression-evaluation context. 15328 DiscardCleanupsInEvaluationContext(); 15329 PopExpressionEvaluationContext(); 15330 15331 // Pop off CurBlock, handle nested blocks. 15332 PopDeclContext(); 15333 PopFunctionScopeInfo(); 15334 } 15335 15336 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15337 /// literal was successfully completed. ^(int x){...} 15338 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15339 Stmt *Body, Scope *CurScope) { 15340 // If blocks are disabled, emit an error. 15341 if (!LangOpts.Blocks) 15342 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15343 15344 // Leave the expression-evaluation context. 15345 if (hasAnyUnrecoverableErrorsInThisFunction()) 15346 DiscardCleanupsInEvaluationContext(); 15347 assert(!Cleanup.exprNeedsCleanups() && 15348 "cleanups within block not correctly bound!"); 15349 PopExpressionEvaluationContext(); 15350 15351 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15352 BlockDecl *BD = BSI->TheDecl; 15353 15354 if (BSI->HasImplicitReturnType) 15355 deduceClosureReturnType(*BSI); 15356 15357 QualType RetTy = Context.VoidTy; 15358 if (!BSI->ReturnType.isNull()) 15359 RetTy = BSI->ReturnType; 15360 15361 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15362 QualType BlockTy; 15363 15364 // If the user wrote a function type in some form, try to use that. 15365 if (!BSI->FunctionType.isNull()) { 15366 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15367 15368 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15369 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15370 15371 // Turn protoless block types into nullary block types. 15372 if (isa<FunctionNoProtoType>(FTy)) { 15373 FunctionProtoType::ExtProtoInfo EPI; 15374 EPI.ExtInfo = Ext; 15375 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15376 15377 // Otherwise, if we don't need to change anything about the function type, 15378 // preserve its sugar structure. 15379 } else if (FTy->getReturnType() == RetTy && 15380 (!NoReturn || FTy->getNoReturnAttr())) { 15381 BlockTy = BSI->FunctionType; 15382 15383 // Otherwise, make the minimal modifications to the function type. 15384 } else { 15385 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15387 EPI.TypeQuals = Qualifiers(); 15388 EPI.ExtInfo = Ext; 15389 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15390 } 15391 15392 // If we don't have a function type, just build one from nothing. 15393 } else { 15394 FunctionProtoType::ExtProtoInfo EPI; 15395 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15396 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15397 } 15398 15399 DiagnoseUnusedParameters(BD->parameters()); 15400 BlockTy = Context.getBlockPointerType(BlockTy); 15401 15402 // If needed, diagnose invalid gotos and switches in the block. 15403 if (getCurFunction()->NeedsScopeChecking() && 15404 !PP.isCodeCompletionEnabled()) 15405 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15406 15407 BD->setBody(cast<CompoundStmt>(Body)); 15408 15409 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15410 DiagnoseUnguardedAvailabilityViolations(BD); 15411 15412 // Try to apply the named return value optimization. We have to check again 15413 // if we can do this, though, because blocks keep return statements around 15414 // to deduce an implicit return type. 15415 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15416 !BD->isDependentContext()) 15417 computeNRVO(Body, BSI); 15418 15419 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15420 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15421 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15422 NTCUK_Destruct|NTCUK_Copy); 15423 15424 PopDeclContext(); 15425 15426 // Set the captured variables on the block. 15427 SmallVector<BlockDecl::Capture, 4> Captures; 15428 for (Capture &Cap : BSI->Captures) { 15429 if (Cap.isInvalid() || Cap.isThisCapture()) 15430 continue; 15431 15432 VarDecl *Var = Cap.getVariable(); 15433 Expr *CopyExpr = nullptr; 15434 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15435 if (const RecordType *Record = 15436 Cap.getCaptureType()->getAs<RecordType>()) { 15437 // The capture logic needs the destructor, so make sure we mark it. 15438 // Usually this is unnecessary because most local variables have 15439 // their destructors marked at declaration time, but parameters are 15440 // an exception because it's technically only the call site that 15441 // actually requires the destructor. 15442 if (isa<ParmVarDecl>(Var)) 15443 FinalizeVarWithDestructor(Var, Record); 15444 15445 // Enter a separate potentially-evaluated context while building block 15446 // initializers to isolate their cleanups from those of the block 15447 // itself. 15448 // FIXME: Is this appropriate even when the block itself occurs in an 15449 // unevaluated operand? 15450 EnterExpressionEvaluationContext EvalContext( 15451 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15452 15453 SourceLocation Loc = Cap.getLocation(); 15454 15455 ExprResult Result = BuildDeclarationNameExpr( 15456 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15457 15458 // According to the blocks spec, the capture of a variable from 15459 // the stack requires a const copy constructor. This is not true 15460 // of the copy/move done to move a __block variable to the heap. 15461 if (!Result.isInvalid() && 15462 !Result.get()->getType().isConstQualified()) { 15463 Result = ImpCastExprToType(Result.get(), 15464 Result.get()->getType().withConst(), 15465 CK_NoOp, VK_LValue); 15466 } 15467 15468 if (!Result.isInvalid()) { 15469 Result = PerformCopyInitialization( 15470 InitializedEntity::InitializeBlock(Var->getLocation(), 15471 Cap.getCaptureType(), false), 15472 Loc, Result.get()); 15473 } 15474 15475 // Build a full-expression copy expression if initialization 15476 // succeeded and used a non-trivial constructor. Recover from 15477 // errors by pretending that the copy isn't necessary. 15478 if (!Result.isInvalid() && 15479 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15480 ->isTrivial()) { 15481 Result = MaybeCreateExprWithCleanups(Result); 15482 CopyExpr = Result.get(); 15483 } 15484 } 15485 } 15486 15487 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15488 CopyExpr); 15489 Captures.push_back(NewCap); 15490 } 15491 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15492 15493 // Pop the block scope now but keep it alive to the end of this function. 15494 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15495 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15496 15497 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15498 15499 // If the block isn't obviously global, i.e. it captures anything at 15500 // all, then we need to do a few things in the surrounding context: 15501 if (Result->getBlockDecl()->hasCaptures()) { 15502 // First, this expression has a new cleanup object. 15503 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15504 Cleanup.setExprNeedsCleanups(true); 15505 15506 // It also gets a branch-protected scope if any of the captured 15507 // variables needs destruction. 15508 for (const auto &CI : Result->getBlockDecl()->captures()) { 15509 const VarDecl *var = CI.getVariable(); 15510 if (var->getType().isDestructedType() != QualType::DK_none) { 15511 setFunctionHasBranchProtectedScope(); 15512 break; 15513 } 15514 } 15515 } 15516 15517 if (getCurFunction()) 15518 getCurFunction()->addBlock(BD); 15519 15520 return Result; 15521 } 15522 15523 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15524 SourceLocation RPLoc) { 15525 TypeSourceInfo *TInfo; 15526 GetTypeFromParser(Ty, &TInfo); 15527 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15528 } 15529 15530 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15531 Expr *E, TypeSourceInfo *TInfo, 15532 SourceLocation RPLoc) { 15533 Expr *OrigExpr = E; 15534 bool IsMS = false; 15535 15536 // CUDA device code does not support varargs. 15537 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15538 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15539 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15540 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15541 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15542 } 15543 } 15544 15545 // NVPTX does not support va_arg expression. 15546 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15547 Context.getTargetInfo().getTriple().isNVPTX()) 15548 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15549 15550 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15551 // as Microsoft ABI on an actual Microsoft platform, where 15552 // __builtin_ms_va_list and __builtin_va_list are the same.) 15553 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15554 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15555 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15556 if (Context.hasSameType(MSVaListType, E->getType())) { 15557 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15558 return ExprError(); 15559 IsMS = true; 15560 } 15561 } 15562 15563 // Get the va_list type 15564 QualType VaListType = Context.getBuiltinVaListType(); 15565 if (!IsMS) { 15566 if (VaListType->isArrayType()) { 15567 // Deal with implicit array decay; for example, on x86-64, 15568 // va_list is an array, but it's supposed to decay to 15569 // a pointer for va_arg. 15570 VaListType = Context.getArrayDecayedType(VaListType); 15571 // Make sure the input expression also decays appropriately. 15572 ExprResult Result = UsualUnaryConversions(E); 15573 if (Result.isInvalid()) 15574 return ExprError(); 15575 E = Result.get(); 15576 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15577 // If va_list is a record type and we are compiling in C++ mode, 15578 // check the argument using reference binding. 15579 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15580 Context, Context.getLValueReferenceType(VaListType), false); 15581 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15582 if (Init.isInvalid()) 15583 return ExprError(); 15584 E = Init.getAs<Expr>(); 15585 } else { 15586 // Otherwise, the va_list argument must be an l-value because 15587 // it is modified by va_arg. 15588 if (!E->isTypeDependent() && 15589 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15590 return ExprError(); 15591 } 15592 } 15593 15594 if (!IsMS && !E->isTypeDependent() && 15595 !Context.hasSameType(VaListType, E->getType())) 15596 return ExprError( 15597 Diag(E->getBeginLoc(), 15598 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15599 << OrigExpr->getType() << E->getSourceRange()); 15600 15601 if (!TInfo->getType()->isDependentType()) { 15602 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15603 diag::err_second_parameter_to_va_arg_incomplete, 15604 TInfo->getTypeLoc())) 15605 return ExprError(); 15606 15607 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15608 TInfo->getType(), 15609 diag::err_second_parameter_to_va_arg_abstract, 15610 TInfo->getTypeLoc())) 15611 return ExprError(); 15612 15613 if (!TInfo->getType().isPODType(Context)) { 15614 Diag(TInfo->getTypeLoc().getBeginLoc(), 15615 TInfo->getType()->isObjCLifetimeType() 15616 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15617 : diag::warn_second_parameter_to_va_arg_not_pod) 15618 << TInfo->getType() 15619 << TInfo->getTypeLoc().getSourceRange(); 15620 } 15621 15622 // Check for va_arg where arguments of the given type will be promoted 15623 // (i.e. this va_arg is guaranteed to have undefined behavior). 15624 QualType PromoteType; 15625 if (TInfo->getType()->isPromotableIntegerType()) { 15626 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15627 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15628 PromoteType = QualType(); 15629 } 15630 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15631 PromoteType = Context.DoubleTy; 15632 if (!PromoteType.isNull()) 15633 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15634 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15635 << TInfo->getType() 15636 << PromoteType 15637 << TInfo->getTypeLoc().getSourceRange()); 15638 } 15639 15640 QualType T = TInfo->getType().getNonLValueExprType(Context); 15641 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15642 } 15643 15644 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15645 // The type of __null will be int or long, depending on the size of 15646 // pointers on the target. 15647 QualType Ty; 15648 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15649 if (pw == Context.getTargetInfo().getIntWidth()) 15650 Ty = Context.IntTy; 15651 else if (pw == Context.getTargetInfo().getLongWidth()) 15652 Ty = Context.LongTy; 15653 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15654 Ty = Context.LongLongTy; 15655 else { 15656 llvm_unreachable("I don't know size of pointer!"); 15657 } 15658 15659 return new (Context) GNUNullExpr(Ty, TokenLoc); 15660 } 15661 15662 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15663 SourceLocation BuiltinLoc, 15664 SourceLocation RPLoc) { 15665 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15666 } 15667 15668 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15669 SourceLocation BuiltinLoc, 15670 SourceLocation RPLoc, 15671 DeclContext *ParentContext) { 15672 return new (Context) 15673 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15674 } 15675 15676 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15677 bool Diagnose) { 15678 if (!getLangOpts().ObjC) 15679 return false; 15680 15681 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15682 if (!PT) 15683 return false; 15684 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15685 15686 // Ignore any parens, implicit casts (should only be 15687 // array-to-pointer decays), and not-so-opaque values. The last is 15688 // important for making this trigger for property assignments. 15689 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15690 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15691 if (OV->getSourceExpr()) 15692 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15693 15694 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15695 if (!PT->isObjCIdType() && 15696 !(ID && ID->getIdentifier()->isStr("NSString"))) 15697 return false; 15698 if (!SL->isAscii()) 15699 return false; 15700 15701 if (Diagnose) { 15702 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15703 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15704 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15705 } 15706 return true; 15707 } 15708 15709 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15710 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15711 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15712 !SrcExpr->isNullPointerConstant( 15713 getASTContext(), Expr::NPC_NeverValueDependent)) { 15714 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15715 return false; 15716 if (Diagnose) { 15717 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15718 << /*number*/1 15719 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15720 Expr *NumLit = 15721 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15722 if (NumLit) 15723 Exp = NumLit; 15724 } 15725 return true; 15726 } 15727 15728 return false; 15729 } 15730 15731 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15732 const Expr *SrcExpr) { 15733 if (!DstType->isFunctionPointerType() || 15734 !SrcExpr->getType()->isFunctionType()) 15735 return false; 15736 15737 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15738 if (!DRE) 15739 return false; 15740 15741 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15742 if (!FD) 15743 return false; 15744 15745 return !S.checkAddressOfFunctionIsAvailable(FD, 15746 /*Complain=*/true, 15747 SrcExpr->getBeginLoc()); 15748 } 15749 15750 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15751 SourceLocation Loc, 15752 QualType DstType, QualType SrcType, 15753 Expr *SrcExpr, AssignmentAction Action, 15754 bool *Complained) { 15755 if (Complained) 15756 *Complained = false; 15757 15758 // Decode the result (notice that AST's are still created for extensions). 15759 bool CheckInferredResultType = false; 15760 bool isInvalid = false; 15761 unsigned DiagKind = 0; 15762 ConversionFixItGenerator ConvHints; 15763 bool MayHaveConvFixit = false; 15764 bool MayHaveFunctionDiff = false; 15765 const ObjCInterfaceDecl *IFace = nullptr; 15766 const ObjCProtocolDecl *PDecl = nullptr; 15767 15768 switch (ConvTy) { 15769 case Compatible: 15770 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15771 return false; 15772 15773 case PointerToInt: 15774 if (getLangOpts().CPlusPlus) { 15775 DiagKind = diag::err_typecheck_convert_pointer_int; 15776 isInvalid = true; 15777 } else { 15778 DiagKind = diag::ext_typecheck_convert_pointer_int; 15779 } 15780 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15781 MayHaveConvFixit = true; 15782 break; 15783 case IntToPointer: 15784 if (getLangOpts().CPlusPlus) { 15785 DiagKind = diag::err_typecheck_convert_int_pointer; 15786 isInvalid = true; 15787 } else { 15788 DiagKind = diag::ext_typecheck_convert_int_pointer; 15789 } 15790 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15791 MayHaveConvFixit = true; 15792 break; 15793 case IncompatibleFunctionPointer: 15794 if (getLangOpts().CPlusPlus) { 15795 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15796 isInvalid = true; 15797 } else { 15798 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15799 } 15800 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15801 MayHaveConvFixit = true; 15802 break; 15803 case IncompatiblePointer: 15804 if (Action == AA_Passing_CFAudited) { 15805 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15806 } else if (getLangOpts().CPlusPlus) { 15807 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15808 isInvalid = true; 15809 } else { 15810 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15811 } 15812 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15813 SrcType->isObjCObjectPointerType(); 15814 if (!CheckInferredResultType) { 15815 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15816 } else if (CheckInferredResultType) { 15817 SrcType = SrcType.getUnqualifiedType(); 15818 DstType = DstType.getUnqualifiedType(); 15819 } 15820 MayHaveConvFixit = true; 15821 break; 15822 case IncompatiblePointerSign: 15823 if (getLangOpts().CPlusPlus) { 15824 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15825 isInvalid = true; 15826 } else { 15827 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15828 } 15829 break; 15830 case FunctionVoidPointer: 15831 if (getLangOpts().CPlusPlus) { 15832 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15833 isInvalid = true; 15834 } else { 15835 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15836 } 15837 break; 15838 case IncompatiblePointerDiscardsQualifiers: { 15839 // Perform array-to-pointer decay if necessary. 15840 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15841 15842 isInvalid = true; 15843 15844 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15845 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15846 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15847 DiagKind = diag::err_typecheck_incompatible_address_space; 15848 break; 15849 15850 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15851 DiagKind = diag::err_typecheck_incompatible_ownership; 15852 break; 15853 } 15854 15855 llvm_unreachable("unknown error case for discarding qualifiers!"); 15856 // fallthrough 15857 } 15858 case CompatiblePointerDiscardsQualifiers: 15859 // If the qualifiers lost were because we were applying the 15860 // (deprecated) C++ conversion from a string literal to a char* 15861 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15862 // Ideally, this check would be performed in 15863 // checkPointerTypesForAssignment. However, that would require a 15864 // bit of refactoring (so that the second argument is an 15865 // expression, rather than a type), which should be done as part 15866 // of a larger effort to fix checkPointerTypesForAssignment for 15867 // C++ semantics. 15868 if (getLangOpts().CPlusPlus && 15869 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15870 return false; 15871 if (getLangOpts().CPlusPlus) { 15872 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15873 isInvalid = true; 15874 } else { 15875 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15876 } 15877 15878 break; 15879 case IncompatibleNestedPointerQualifiers: 15880 if (getLangOpts().CPlusPlus) { 15881 isInvalid = true; 15882 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15883 } else { 15884 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15885 } 15886 break; 15887 case IncompatibleNestedPointerAddressSpaceMismatch: 15888 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15889 isInvalid = true; 15890 break; 15891 case IntToBlockPointer: 15892 DiagKind = diag::err_int_to_block_pointer; 15893 isInvalid = true; 15894 break; 15895 case IncompatibleBlockPointer: 15896 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15897 isInvalid = true; 15898 break; 15899 case IncompatibleObjCQualifiedId: { 15900 if (SrcType->isObjCQualifiedIdType()) { 15901 const ObjCObjectPointerType *srcOPT = 15902 SrcType->castAs<ObjCObjectPointerType>(); 15903 for (auto *srcProto : srcOPT->quals()) { 15904 PDecl = srcProto; 15905 break; 15906 } 15907 if (const ObjCInterfaceType *IFaceT = 15908 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15909 IFace = IFaceT->getDecl(); 15910 } 15911 else if (DstType->isObjCQualifiedIdType()) { 15912 const ObjCObjectPointerType *dstOPT = 15913 DstType->castAs<ObjCObjectPointerType>(); 15914 for (auto *dstProto : dstOPT->quals()) { 15915 PDecl = dstProto; 15916 break; 15917 } 15918 if (const ObjCInterfaceType *IFaceT = 15919 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15920 IFace = IFaceT->getDecl(); 15921 } 15922 if (getLangOpts().CPlusPlus) { 15923 DiagKind = diag::err_incompatible_qualified_id; 15924 isInvalid = true; 15925 } else { 15926 DiagKind = diag::warn_incompatible_qualified_id; 15927 } 15928 break; 15929 } 15930 case IncompatibleVectors: 15931 if (getLangOpts().CPlusPlus) { 15932 DiagKind = diag::err_incompatible_vectors; 15933 isInvalid = true; 15934 } else { 15935 DiagKind = diag::warn_incompatible_vectors; 15936 } 15937 break; 15938 case IncompatibleObjCWeakRef: 15939 DiagKind = diag::err_arc_weak_unavailable_assign; 15940 isInvalid = true; 15941 break; 15942 case Incompatible: 15943 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15944 if (Complained) 15945 *Complained = true; 15946 return true; 15947 } 15948 15949 DiagKind = diag::err_typecheck_convert_incompatible; 15950 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15951 MayHaveConvFixit = true; 15952 isInvalid = true; 15953 MayHaveFunctionDiff = true; 15954 break; 15955 } 15956 15957 QualType FirstType, SecondType; 15958 switch (Action) { 15959 case AA_Assigning: 15960 case AA_Initializing: 15961 // The destination type comes first. 15962 FirstType = DstType; 15963 SecondType = SrcType; 15964 break; 15965 15966 case AA_Returning: 15967 case AA_Passing: 15968 case AA_Passing_CFAudited: 15969 case AA_Converting: 15970 case AA_Sending: 15971 case AA_Casting: 15972 // The source type comes first. 15973 FirstType = SrcType; 15974 SecondType = DstType; 15975 break; 15976 } 15977 15978 PartialDiagnostic FDiag = PDiag(DiagKind); 15979 if (Action == AA_Passing_CFAudited) 15980 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15981 else 15982 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15983 15984 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 15985 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 15986 auto isPlainChar = [](const clang::Type *Type) { 15987 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 15988 Type->isSpecificBuiltinType(BuiltinType::Char_U); 15989 }; 15990 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 15991 isPlainChar(SecondType->getPointeeOrArrayElementType())); 15992 } 15993 15994 // If we can fix the conversion, suggest the FixIts. 15995 if (!ConvHints.isNull()) { 15996 for (FixItHint &H : ConvHints.Hints) 15997 FDiag << H; 15998 } 15999 16000 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16001 16002 if (MayHaveFunctionDiff) 16003 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16004 16005 Diag(Loc, FDiag); 16006 if ((DiagKind == diag::warn_incompatible_qualified_id || 16007 DiagKind == diag::err_incompatible_qualified_id) && 16008 PDecl && IFace && !IFace->hasDefinition()) 16009 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16010 << IFace << PDecl; 16011 16012 if (SecondType == Context.OverloadTy) 16013 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16014 FirstType, /*TakingAddress=*/true); 16015 16016 if (CheckInferredResultType) 16017 EmitRelatedResultTypeNote(SrcExpr); 16018 16019 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16020 EmitRelatedResultTypeNoteForReturn(DstType); 16021 16022 if (Complained) 16023 *Complained = true; 16024 return isInvalid; 16025 } 16026 16027 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16028 llvm::APSInt *Result, 16029 AllowFoldKind CanFold) { 16030 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16031 public: 16032 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16033 QualType T) override { 16034 return S.Diag(Loc, diag::err_ice_not_integral) 16035 << T << S.LangOpts.CPlusPlus; 16036 } 16037 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16038 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16039 } 16040 } Diagnoser; 16041 16042 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16043 } 16044 16045 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16046 llvm::APSInt *Result, 16047 unsigned DiagID, 16048 AllowFoldKind CanFold) { 16049 class IDDiagnoser : public VerifyICEDiagnoser { 16050 unsigned DiagID; 16051 16052 public: 16053 IDDiagnoser(unsigned DiagID) 16054 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16055 16056 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16057 return S.Diag(Loc, DiagID); 16058 } 16059 } Diagnoser(DiagID); 16060 16061 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16062 } 16063 16064 Sema::SemaDiagnosticBuilder 16065 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16066 QualType T) { 16067 return diagnoseNotICE(S, Loc); 16068 } 16069 16070 Sema::SemaDiagnosticBuilder 16071 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16072 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16073 } 16074 16075 ExprResult 16076 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16077 VerifyICEDiagnoser &Diagnoser, 16078 AllowFoldKind CanFold) { 16079 SourceLocation DiagLoc = E->getBeginLoc(); 16080 16081 if (getLangOpts().CPlusPlus11) { 16082 // C++11 [expr.const]p5: 16083 // If an expression of literal class type is used in a context where an 16084 // integral constant expression is required, then that class type shall 16085 // have a single non-explicit conversion function to an integral or 16086 // unscoped enumeration type 16087 ExprResult Converted; 16088 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16089 VerifyICEDiagnoser &BaseDiagnoser; 16090 public: 16091 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16092 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16093 BaseDiagnoser.Suppress, true), 16094 BaseDiagnoser(BaseDiagnoser) {} 16095 16096 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16097 QualType T) override { 16098 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16099 } 16100 16101 SemaDiagnosticBuilder diagnoseIncomplete( 16102 Sema &S, SourceLocation Loc, QualType T) override { 16103 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16104 } 16105 16106 SemaDiagnosticBuilder diagnoseExplicitConv( 16107 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16108 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16109 } 16110 16111 SemaDiagnosticBuilder noteExplicitConv( 16112 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16113 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16114 << ConvTy->isEnumeralType() << ConvTy; 16115 } 16116 16117 SemaDiagnosticBuilder diagnoseAmbiguous( 16118 Sema &S, SourceLocation Loc, QualType T) override { 16119 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16120 } 16121 16122 SemaDiagnosticBuilder noteAmbiguous( 16123 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16124 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16125 << ConvTy->isEnumeralType() << ConvTy; 16126 } 16127 16128 SemaDiagnosticBuilder diagnoseConversion( 16129 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16130 llvm_unreachable("conversion functions are permitted"); 16131 } 16132 } ConvertDiagnoser(Diagnoser); 16133 16134 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16135 ConvertDiagnoser); 16136 if (Converted.isInvalid()) 16137 return Converted; 16138 E = Converted.get(); 16139 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16140 return ExprError(); 16141 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16142 // An ICE must be of integral or unscoped enumeration type. 16143 if (!Diagnoser.Suppress) 16144 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16145 << E->getSourceRange(); 16146 return ExprError(); 16147 } 16148 16149 ExprResult RValueExpr = DefaultLvalueConversion(E); 16150 if (RValueExpr.isInvalid()) 16151 return ExprError(); 16152 16153 E = RValueExpr.get(); 16154 16155 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16156 // in the non-ICE case. 16157 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16158 if (Result) 16159 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16160 if (!isa<ConstantExpr>(E)) 16161 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16162 : ConstantExpr::Create(Context, E); 16163 return E; 16164 } 16165 16166 Expr::EvalResult EvalResult; 16167 SmallVector<PartialDiagnosticAt, 8> Notes; 16168 EvalResult.Diag = &Notes; 16169 16170 // Try to evaluate the expression, and produce diagnostics explaining why it's 16171 // not a constant expression as a side-effect. 16172 bool Folded = 16173 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16174 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16175 16176 if (!isa<ConstantExpr>(E)) 16177 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16178 16179 // In C++11, we can rely on diagnostics being produced for any expression 16180 // which is not a constant expression. If no diagnostics were produced, then 16181 // this is a constant expression. 16182 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16183 if (Result) 16184 *Result = EvalResult.Val.getInt(); 16185 return E; 16186 } 16187 16188 // If our only note is the usual "invalid subexpression" note, just point 16189 // the caret at its location rather than producing an essentially 16190 // redundant note. 16191 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16192 diag::note_invalid_subexpr_in_const_expr) { 16193 DiagLoc = Notes[0].first; 16194 Notes.clear(); 16195 } 16196 16197 if (!Folded || !CanFold) { 16198 if (!Diagnoser.Suppress) { 16199 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16200 for (const PartialDiagnosticAt &Note : Notes) 16201 Diag(Note.first, Note.second); 16202 } 16203 16204 return ExprError(); 16205 } 16206 16207 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16208 for (const PartialDiagnosticAt &Note : Notes) 16209 Diag(Note.first, Note.second); 16210 16211 if (Result) 16212 *Result = EvalResult.Val.getInt(); 16213 return E; 16214 } 16215 16216 namespace { 16217 // Handle the case where we conclude a expression which we speculatively 16218 // considered to be unevaluated is actually evaluated. 16219 class TransformToPE : public TreeTransform<TransformToPE> { 16220 typedef TreeTransform<TransformToPE> BaseTransform; 16221 16222 public: 16223 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16224 16225 // Make sure we redo semantic analysis 16226 bool AlwaysRebuild() { return true; } 16227 bool ReplacingOriginal() { return true; } 16228 16229 // We need to special-case DeclRefExprs referring to FieldDecls which 16230 // are not part of a member pointer formation; normal TreeTransforming 16231 // doesn't catch this case because of the way we represent them in the AST. 16232 // FIXME: This is a bit ugly; is it really the best way to handle this 16233 // case? 16234 // 16235 // Error on DeclRefExprs referring to FieldDecls. 16236 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16237 if (isa<FieldDecl>(E->getDecl()) && 16238 !SemaRef.isUnevaluatedContext()) 16239 return SemaRef.Diag(E->getLocation(), 16240 diag::err_invalid_non_static_member_use) 16241 << E->getDecl() << E->getSourceRange(); 16242 16243 return BaseTransform::TransformDeclRefExpr(E); 16244 } 16245 16246 // Exception: filter out member pointer formation 16247 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16248 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16249 return E; 16250 16251 return BaseTransform::TransformUnaryOperator(E); 16252 } 16253 16254 // The body of a lambda-expression is in a separate expression evaluation 16255 // context so never needs to be transformed. 16256 // FIXME: Ideally we wouldn't transform the closure type either, and would 16257 // just recreate the capture expressions and lambda expression. 16258 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16259 return SkipLambdaBody(E, Body); 16260 } 16261 }; 16262 } 16263 16264 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16265 assert(isUnevaluatedContext() && 16266 "Should only transform unevaluated expressions"); 16267 ExprEvalContexts.back().Context = 16268 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16269 if (isUnevaluatedContext()) 16270 return E; 16271 return TransformToPE(*this).TransformExpr(E); 16272 } 16273 16274 void 16275 Sema::PushExpressionEvaluationContext( 16276 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16277 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16278 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16279 LambdaContextDecl, ExprContext); 16280 Cleanup.reset(); 16281 if (!MaybeODRUseExprs.empty()) 16282 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16283 } 16284 16285 void 16286 Sema::PushExpressionEvaluationContext( 16287 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16288 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16289 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16290 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16291 } 16292 16293 namespace { 16294 16295 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16296 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16297 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16298 if (E->getOpcode() == UO_Deref) 16299 return CheckPossibleDeref(S, E->getSubExpr()); 16300 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16301 return CheckPossibleDeref(S, E->getBase()); 16302 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16303 return CheckPossibleDeref(S, E->getBase()); 16304 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16305 QualType Inner; 16306 QualType Ty = E->getType(); 16307 if (const auto *Ptr = Ty->getAs<PointerType>()) 16308 Inner = Ptr->getPointeeType(); 16309 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16310 Inner = Arr->getElementType(); 16311 else 16312 return nullptr; 16313 16314 if (Inner->hasAttr(attr::NoDeref)) 16315 return E; 16316 } 16317 return nullptr; 16318 } 16319 16320 } // namespace 16321 16322 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16323 for (const Expr *E : Rec.PossibleDerefs) { 16324 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16325 if (DeclRef) { 16326 const ValueDecl *Decl = DeclRef->getDecl(); 16327 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16328 << Decl->getName() << E->getSourceRange(); 16329 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16330 } else { 16331 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16332 << E->getSourceRange(); 16333 } 16334 } 16335 Rec.PossibleDerefs.clear(); 16336 } 16337 16338 /// Check whether E, which is either a discarded-value expression or an 16339 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16340 /// and if so, remove it from the list of volatile-qualified assignments that 16341 /// we are going to warn are deprecated. 16342 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16343 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16344 return; 16345 16346 // Note: ignoring parens here is not justified by the standard rules, but 16347 // ignoring parentheses seems like a more reasonable approach, and this only 16348 // drives a deprecation warning so doesn't affect conformance. 16349 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16350 if (BO->getOpcode() == BO_Assign) { 16351 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16352 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16353 LHSs.end()); 16354 } 16355 } 16356 } 16357 16358 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16359 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16360 RebuildingImmediateInvocation) 16361 return E; 16362 16363 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16364 /// It's OK if this fails; we'll also remove this in 16365 /// HandleImmediateInvocations, but catching it here allows us to avoid 16366 /// walking the AST looking for it in simple cases. 16367 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16368 if (auto *DeclRef = 16369 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16370 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16371 16372 E = MaybeCreateExprWithCleanups(E); 16373 16374 ConstantExpr *Res = ConstantExpr::Create( 16375 getASTContext(), E.get(), 16376 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16377 getASTContext()), 16378 /*IsImmediateInvocation*/ true); 16379 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16380 return Res; 16381 } 16382 16383 static void EvaluateAndDiagnoseImmediateInvocation( 16384 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16385 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16386 Expr::EvalResult Eval; 16387 Eval.Diag = &Notes; 16388 ConstantExpr *CE = Candidate.getPointer(); 16389 bool Result = CE->EvaluateAsConstantExpr( 16390 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16391 if (!Result || !Notes.empty()) { 16392 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16393 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16394 InnerExpr = FunctionalCast->getSubExpr(); 16395 FunctionDecl *FD = nullptr; 16396 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16397 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16398 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16399 FD = Call->getConstructor(); 16400 else 16401 llvm_unreachable("unhandled decl kind"); 16402 assert(FD->isConsteval()); 16403 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16404 for (auto &Note : Notes) 16405 SemaRef.Diag(Note.first, Note.second); 16406 return; 16407 } 16408 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16409 } 16410 16411 static void RemoveNestedImmediateInvocation( 16412 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16413 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16414 struct ComplexRemove : TreeTransform<ComplexRemove> { 16415 using Base = TreeTransform<ComplexRemove>; 16416 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16417 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16418 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16419 CurrentII; 16420 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16421 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16422 SmallVector<Sema::ImmediateInvocationCandidate, 16423 4>::reverse_iterator Current) 16424 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16425 void RemoveImmediateInvocation(ConstantExpr* E) { 16426 auto It = std::find_if(CurrentII, IISet.rend(), 16427 [E](Sema::ImmediateInvocationCandidate Elem) { 16428 return Elem.getPointer() == E; 16429 }); 16430 assert(It != IISet.rend() && 16431 "ConstantExpr marked IsImmediateInvocation should " 16432 "be present"); 16433 It->setInt(1); // Mark as deleted 16434 } 16435 ExprResult TransformConstantExpr(ConstantExpr *E) { 16436 if (!E->isImmediateInvocation()) 16437 return Base::TransformConstantExpr(E); 16438 RemoveImmediateInvocation(E); 16439 return Base::TransformExpr(E->getSubExpr()); 16440 } 16441 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16442 /// we need to remove its DeclRefExpr from the DRSet. 16443 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16444 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16445 return Base::TransformCXXOperatorCallExpr(E); 16446 } 16447 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16448 /// here. 16449 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16450 if (!Init) 16451 return Init; 16452 /// ConstantExpr are the first layer of implicit node to be removed so if 16453 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16454 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16455 if (CE->isImmediateInvocation()) 16456 RemoveImmediateInvocation(CE); 16457 return Base::TransformInitializer(Init, NotCopyInit); 16458 } 16459 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16460 DRSet.erase(E); 16461 return E; 16462 } 16463 bool AlwaysRebuild() { return false; } 16464 bool ReplacingOriginal() { return true; } 16465 bool AllowSkippingCXXConstructExpr() { 16466 bool Res = AllowSkippingFirstCXXConstructExpr; 16467 AllowSkippingFirstCXXConstructExpr = true; 16468 return Res; 16469 } 16470 bool AllowSkippingFirstCXXConstructExpr = true; 16471 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16472 Rec.ImmediateInvocationCandidates, It); 16473 16474 /// CXXConstructExpr with a single argument are getting skipped by 16475 /// TreeTransform in some situtation because they could be implicit. This 16476 /// can only occur for the top-level CXXConstructExpr because it is used 16477 /// nowhere in the expression being transformed therefore will not be rebuilt. 16478 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16479 /// skipping the first CXXConstructExpr. 16480 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16481 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16482 16483 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16484 assert(Res.isUsable()); 16485 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16486 It->getPointer()->setSubExpr(Res.get()); 16487 } 16488 16489 static void 16490 HandleImmediateInvocations(Sema &SemaRef, 16491 Sema::ExpressionEvaluationContextRecord &Rec) { 16492 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16493 Rec.ReferenceToConsteval.size() == 0) || 16494 SemaRef.RebuildingImmediateInvocation) 16495 return; 16496 16497 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16498 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16499 /// need to remove ReferenceToConsteval in the immediate invocation. 16500 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16501 16502 /// Prevent sema calls during the tree transform from adding pointers that 16503 /// are already in the sets. 16504 llvm::SaveAndRestore<bool> DisableIITracking( 16505 SemaRef.RebuildingImmediateInvocation, true); 16506 16507 /// Prevent diagnostic during tree transfrom as they are duplicates 16508 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16509 16510 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16511 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16512 if (!It->getInt()) 16513 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16514 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16515 Rec.ReferenceToConsteval.size()) { 16516 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16517 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16518 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16519 bool VisitDeclRefExpr(DeclRefExpr *E) { 16520 DRSet.erase(E); 16521 return DRSet.size(); 16522 } 16523 } Visitor(Rec.ReferenceToConsteval); 16524 Visitor.TraverseStmt( 16525 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16526 } 16527 for (auto CE : Rec.ImmediateInvocationCandidates) 16528 if (!CE.getInt()) 16529 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16530 for (auto DR : Rec.ReferenceToConsteval) { 16531 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16532 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16533 << FD; 16534 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16535 } 16536 } 16537 16538 void Sema::PopExpressionEvaluationContext() { 16539 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16540 unsigned NumTypos = Rec.NumTypos; 16541 16542 if (!Rec.Lambdas.empty()) { 16543 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16544 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16545 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16546 unsigned D; 16547 if (Rec.isUnevaluated()) { 16548 // C++11 [expr.prim.lambda]p2: 16549 // A lambda-expression shall not appear in an unevaluated operand 16550 // (Clause 5). 16551 D = diag::err_lambda_unevaluated_operand; 16552 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16553 // C++1y [expr.const]p2: 16554 // A conditional-expression e is a core constant expression unless the 16555 // evaluation of e, following the rules of the abstract machine, would 16556 // evaluate [...] a lambda-expression. 16557 D = diag::err_lambda_in_constant_expression; 16558 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16559 // C++17 [expr.prim.lamda]p2: 16560 // A lambda-expression shall not appear [...] in a template-argument. 16561 D = diag::err_lambda_in_invalid_context; 16562 } else 16563 llvm_unreachable("Couldn't infer lambda error message."); 16564 16565 for (const auto *L : Rec.Lambdas) 16566 Diag(L->getBeginLoc(), D); 16567 } 16568 } 16569 16570 WarnOnPendingNoDerefs(Rec); 16571 HandleImmediateInvocations(*this, Rec); 16572 16573 // Warn on any volatile-qualified simple-assignments that are not discarded- 16574 // value expressions nor unevaluated operands (those cases get removed from 16575 // this list by CheckUnusedVolatileAssignment). 16576 for (auto *BO : Rec.VolatileAssignmentLHSs) 16577 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16578 << BO->getType(); 16579 16580 // When are coming out of an unevaluated context, clear out any 16581 // temporaries that we may have created as part of the evaluation of 16582 // the expression in that context: they aren't relevant because they 16583 // will never be constructed. 16584 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16585 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16586 ExprCleanupObjects.end()); 16587 Cleanup = Rec.ParentCleanup; 16588 CleanupVarDeclMarking(); 16589 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16590 // Otherwise, merge the contexts together. 16591 } else { 16592 Cleanup.mergeFrom(Rec.ParentCleanup); 16593 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16594 Rec.SavedMaybeODRUseExprs.end()); 16595 } 16596 16597 // Pop the current expression evaluation context off the stack. 16598 ExprEvalContexts.pop_back(); 16599 16600 // The global expression evaluation context record is never popped. 16601 ExprEvalContexts.back().NumTypos += NumTypos; 16602 } 16603 16604 void Sema::DiscardCleanupsInEvaluationContext() { 16605 ExprCleanupObjects.erase( 16606 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16607 ExprCleanupObjects.end()); 16608 Cleanup.reset(); 16609 MaybeODRUseExprs.clear(); 16610 } 16611 16612 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16613 ExprResult Result = CheckPlaceholderExpr(E); 16614 if (Result.isInvalid()) 16615 return ExprError(); 16616 E = Result.get(); 16617 if (!E->getType()->isVariablyModifiedType()) 16618 return E; 16619 return TransformToPotentiallyEvaluated(E); 16620 } 16621 16622 /// Are we in a context that is potentially constant evaluated per C++20 16623 /// [expr.const]p12? 16624 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16625 /// C++2a [expr.const]p12: 16626 // An expression or conversion is potentially constant evaluated if it is 16627 switch (SemaRef.ExprEvalContexts.back().Context) { 16628 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16629 // -- a manifestly constant-evaluated expression, 16630 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16631 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16632 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16633 // -- a potentially-evaluated expression, 16634 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16635 // -- an immediate subexpression of a braced-init-list, 16636 16637 // -- [FIXME] an expression of the form & cast-expression that occurs 16638 // within a templated entity 16639 // -- a subexpression of one of the above that is not a subexpression of 16640 // a nested unevaluated operand. 16641 return true; 16642 16643 case Sema::ExpressionEvaluationContext::Unevaluated: 16644 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16645 // Expressions in this context are never evaluated. 16646 return false; 16647 } 16648 llvm_unreachable("Invalid context"); 16649 } 16650 16651 /// Return true if this function has a calling convention that requires mangling 16652 /// in the size of the parameter pack. 16653 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16654 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16655 // we don't need parameter type sizes. 16656 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16657 if (!TT.isOSWindows() || !TT.isX86()) 16658 return false; 16659 16660 // If this is C++ and this isn't an extern "C" function, parameters do not 16661 // need to be complete. In this case, C++ mangling will apply, which doesn't 16662 // use the size of the parameters. 16663 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16664 return false; 16665 16666 // Stdcall, fastcall, and vectorcall need this special treatment. 16667 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16668 switch (CC) { 16669 case CC_X86StdCall: 16670 case CC_X86FastCall: 16671 case CC_X86VectorCall: 16672 return true; 16673 default: 16674 break; 16675 } 16676 return false; 16677 } 16678 16679 /// Require that all of the parameter types of function be complete. Normally, 16680 /// parameter types are only required to be complete when a function is called 16681 /// or defined, but to mangle functions with certain calling conventions, the 16682 /// mangler needs to know the size of the parameter list. In this situation, 16683 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16684 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16685 /// result in a linker error. Clang doesn't implement this behavior, and instead 16686 /// attempts to error at compile time. 16687 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16688 SourceLocation Loc) { 16689 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16690 FunctionDecl *FD; 16691 ParmVarDecl *Param; 16692 16693 public: 16694 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16695 : FD(FD), Param(Param) {} 16696 16697 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16698 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16699 StringRef CCName; 16700 switch (CC) { 16701 case CC_X86StdCall: 16702 CCName = "stdcall"; 16703 break; 16704 case CC_X86FastCall: 16705 CCName = "fastcall"; 16706 break; 16707 case CC_X86VectorCall: 16708 CCName = "vectorcall"; 16709 break; 16710 default: 16711 llvm_unreachable("CC does not need mangling"); 16712 } 16713 16714 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16715 << Param->getDeclName() << FD->getDeclName() << CCName; 16716 } 16717 }; 16718 16719 for (ParmVarDecl *Param : FD->parameters()) { 16720 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16721 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16722 } 16723 } 16724 16725 namespace { 16726 enum class OdrUseContext { 16727 /// Declarations in this context are not odr-used. 16728 None, 16729 /// Declarations in this context are formally odr-used, but this is a 16730 /// dependent context. 16731 Dependent, 16732 /// Declarations in this context are odr-used but not actually used (yet). 16733 FormallyOdrUsed, 16734 /// Declarations in this context are used. 16735 Used 16736 }; 16737 } 16738 16739 /// Are we within a context in which references to resolved functions or to 16740 /// variables result in odr-use? 16741 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16742 OdrUseContext Result; 16743 16744 switch (SemaRef.ExprEvalContexts.back().Context) { 16745 case Sema::ExpressionEvaluationContext::Unevaluated: 16746 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16747 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16748 return OdrUseContext::None; 16749 16750 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16751 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16752 Result = OdrUseContext::Used; 16753 break; 16754 16755 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16756 Result = OdrUseContext::FormallyOdrUsed; 16757 break; 16758 16759 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16760 // A default argument formally results in odr-use, but doesn't actually 16761 // result in a use in any real sense until it itself is used. 16762 Result = OdrUseContext::FormallyOdrUsed; 16763 break; 16764 } 16765 16766 if (SemaRef.CurContext->isDependentContext()) 16767 return OdrUseContext::Dependent; 16768 16769 return Result; 16770 } 16771 16772 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16773 if (!Func->isConstexpr()) 16774 return false; 16775 16776 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16777 return true; 16778 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16779 return CCD && CCD->getInheritedConstructor(); 16780 } 16781 16782 /// Mark a function referenced, and check whether it is odr-used 16783 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16784 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16785 bool MightBeOdrUse) { 16786 assert(Func && "No function?"); 16787 16788 Func->setReferenced(); 16789 16790 // Recursive functions aren't really used until they're used from some other 16791 // context. 16792 bool IsRecursiveCall = CurContext == Func; 16793 16794 // C++11 [basic.def.odr]p3: 16795 // A function whose name appears as a potentially-evaluated expression is 16796 // odr-used if it is the unique lookup result or the selected member of a 16797 // set of overloaded functions [...]. 16798 // 16799 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16800 // can just check that here. 16801 OdrUseContext OdrUse = 16802 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16803 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16804 OdrUse = OdrUseContext::FormallyOdrUsed; 16805 16806 // Trivial default constructors and destructors are never actually used. 16807 // FIXME: What about other special members? 16808 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16809 OdrUse == OdrUseContext::Used) { 16810 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16811 if (Constructor->isDefaultConstructor()) 16812 OdrUse = OdrUseContext::FormallyOdrUsed; 16813 if (isa<CXXDestructorDecl>(Func)) 16814 OdrUse = OdrUseContext::FormallyOdrUsed; 16815 } 16816 16817 // C++20 [expr.const]p12: 16818 // A function [...] is needed for constant evaluation if it is [...] a 16819 // constexpr function that is named by an expression that is potentially 16820 // constant evaluated 16821 bool NeededForConstantEvaluation = 16822 isPotentiallyConstantEvaluatedContext(*this) && 16823 isImplicitlyDefinableConstexprFunction(Func); 16824 16825 // Determine whether we require a function definition to exist, per 16826 // C++11 [temp.inst]p3: 16827 // Unless a function template specialization has been explicitly 16828 // instantiated or explicitly specialized, the function template 16829 // specialization is implicitly instantiated when the specialization is 16830 // referenced in a context that requires a function definition to exist. 16831 // C++20 [temp.inst]p7: 16832 // The existence of a definition of a [...] function is considered to 16833 // affect the semantics of the program if the [...] function is needed for 16834 // constant evaluation by an expression 16835 // C++20 [basic.def.odr]p10: 16836 // Every program shall contain exactly one definition of every non-inline 16837 // function or variable that is odr-used in that program outside of a 16838 // discarded statement 16839 // C++20 [special]p1: 16840 // The implementation will implicitly define [defaulted special members] 16841 // if they are odr-used or needed for constant evaluation. 16842 // 16843 // Note that we skip the implicit instantiation of templates that are only 16844 // used in unused default arguments or by recursive calls to themselves. 16845 // This is formally non-conforming, but seems reasonable in practice. 16846 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16847 NeededForConstantEvaluation); 16848 16849 // C++14 [temp.expl.spec]p6: 16850 // If a template [...] is explicitly specialized then that specialization 16851 // shall be declared before the first use of that specialization that would 16852 // cause an implicit instantiation to take place, in every translation unit 16853 // in which such a use occurs 16854 if (NeedDefinition && 16855 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16856 Func->getMemberSpecializationInfo())) 16857 checkSpecializationVisibility(Loc, Func); 16858 16859 if (getLangOpts().CUDA) 16860 CheckCUDACall(Loc, Func); 16861 16862 if (getLangOpts().SYCLIsDevice) 16863 checkSYCLDeviceFunction(Loc, Func); 16864 16865 // If we need a definition, try to create one. 16866 if (NeedDefinition && !Func->getBody()) { 16867 runWithSufficientStackSpace(Loc, [&] { 16868 if (CXXConstructorDecl *Constructor = 16869 dyn_cast<CXXConstructorDecl>(Func)) { 16870 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16871 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16872 if (Constructor->isDefaultConstructor()) { 16873 if (Constructor->isTrivial() && 16874 !Constructor->hasAttr<DLLExportAttr>()) 16875 return; 16876 DefineImplicitDefaultConstructor(Loc, Constructor); 16877 } else if (Constructor->isCopyConstructor()) { 16878 DefineImplicitCopyConstructor(Loc, Constructor); 16879 } else if (Constructor->isMoveConstructor()) { 16880 DefineImplicitMoveConstructor(Loc, Constructor); 16881 } 16882 } else if (Constructor->getInheritedConstructor()) { 16883 DefineInheritingConstructor(Loc, Constructor); 16884 } 16885 } else if (CXXDestructorDecl *Destructor = 16886 dyn_cast<CXXDestructorDecl>(Func)) { 16887 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16888 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16889 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16890 return; 16891 DefineImplicitDestructor(Loc, Destructor); 16892 } 16893 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16894 MarkVTableUsed(Loc, Destructor->getParent()); 16895 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16896 if (MethodDecl->isOverloadedOperator() && 16897 MethodDecl->getOverloadedOperator() == OO_Equal) { 16898 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16899 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16900 if (MethodDecl->isCopyAssignmentOperator()) 16901 DefineImplicitCopyAssignment(Loc, MethodDecl); 16902 else if (MethodDecl->isMoveAssignmentOperator()) 16903 DefineImplicitMoveAssignment(Loc, MethodDecl); 16904 } 16905 } else if (isa<CXXConversionDecl>(MethodDecl) && 16906 MethodDecl->getParent()->isLambda()) { 16907 CXXConversionDecl *Conversion = 16908 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16909 if (Conversion->isLambdaToBlockPointerConversion()) 16910 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16911 else 16912 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16913 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16914 MarkVTableUsed(Loc, MethodDecl->getParent()); 16915 } 16916 16917 if (Func->isDefaulted() && !Func->isDeleted()) { 16918 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16919 if (DCK != DefaultedComparisonKind::None) 16920 DefineDefaultedComparison(Loc, Func, DCK); 16921 } 16922 16923 // Implicit instantiation of function templates and member functions of 16924 // class templates. 16925 if (Func->isImplicitlyInstantiable()) { 16926 TemplateSpecializationKind TSK = 16927 Func->getTemplateSpecializationKindForInstantiation(); 16928 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16929 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16930 if (FirstInstantiation) { 16931 PointOfInstantiation = Loc; 16932 if (auto *MSI = Func->getMemberSpecializationInfo()) 16933 MSI->setPointOfInstantiation(Loc); 16934 // FIXME: Notify listener. 16935 else 16936 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16937 } else if (TSK != TSK_ImplicitInstantiation) { 16938 // Use the point of use as the point of instantiation, instead of the 16939 // point of explicit instantiation (which we track as the actual point 16940 // of instantiation). This gives better backtraces in diagnostics. 16941 PointOfInstantiation = Loc; 16942 } 16943 16944 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16945 Func->isConstexpr()) { 16946 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16947 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16948 CodeSynthesisContexts.size()) 16949 PendingLocalImplicitInstantiations.push_back( 16950 std::make_pair(Func, PointOfInstantiation)); 16951 else if (Func->isConstexpr()) 16952 // Do not defer instantiations of constexpr functions, to avoid the 16953 // expression evaluator needing to call back into Sema if it sees a 16954 // call to such a function. 16955 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16956 else { 16957 Func->setInstantiationIsPending(true); 16958 PendingInstantiations.push_back( 16959 std::make_pair(Func, PointOfInstantiation)); 16960 // Notify the consumer that a function was implicitly instantiated. 16961 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16962 } 16963 } 16964 } else { 16965 // Walk redefinitions, as some of them may be instantiable. 16966 for (auto i : Func->redecls()) { 16967 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16968 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16969 } 16970 } 16971 }); 16972 } 16973 16974 // C++14 [except.spec]p17: 16975 // An exception-specification is considered to be needed when: 16976 // - the function is odr-used or, if it appears in an unevaluated operand, 16977 // would be odr-used if the expression were potentially-evaluated; 16978 // 16979 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16980 // function is a pure virtual function we're calling, and in that case the 16981 // function was selected by overload resolution and we need to resolve its 16982 // exception specification for a different reason. 16983 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16984 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16985 ResolveExceptionSpec(Loc, FPT); 16986 16987 // If this is the first "real" use, act on that. 16988 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16989 // Keep track of used but undefined functions. 16990 if (!Func->isDefined()) { 16991 if (mightHaveNonExternalLinkage(Func)) 16992 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16993 else if (Func->getMostRecentDecl()->isInlined() && 16994 !LangOpts.GNUInline && 16995 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16996 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16997 else if (isExternalWithNoLinkageType(Func)) 16998 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16999 } 17000 17001 // Some x86 Windows calling conventions mangle the size of the parameter 17002 // pack into the name. Computing the size of the parameters requires the 17003 // parameter types to be complete. Check that now. 17004 if (funcHasParameterSizeMangling(*this, Func)) 17005 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17006 17007 // In the MS C++ ABI, the compiler emits destructor variants where they are 17008 // used. If the destructor is used here but defined elsewhere, mark the 17009 // virtual base destructors referenced. If those virtual base destructors 17010 // are inline, this will ensure they are defined when emitting the complete 17011 // destructor variant. This checking may be redundant if the destructor is 17012 // provided later in this TU. 17013 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17014 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17015 CXXRecordDecl *Parent = Dtor->getParent(); 17016 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17017 CheckCompleteDestructorVariant(Loc, Dtor); 17018 } 17019 } 17020 17021 Func->markUsed(Context); 17022 } 17023 } 17024 17025 /// Directly mark a variable odr-used. Given a choice, prefer to use 17026 /// MarkVariableReferenced since it does additional checks and then 17027 /// calls MarkVarDeclODRUsed. 17028 /// If the variable must be captured: 17029 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17030 /// - else capture it in the DeclContext that maps to the 17031 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17032 static void 17033 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17034 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17035 // Keep track of used but undefined variables. 17036 // FIXME: We shouldn't suppress this warning for static data members. 17037 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17038 (!Var->isExternallyVisible() || Var->isInline() || 17039 SemaRef.isExternalWithNoLinkageType(Var)) && 17040 !(Var->isStaticDataMember() && Var->hasInit())) { 17041 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17042 if (old.isInvalid()) 17043 old = Loc; 17044 } 17045 QualType CaptureType, DeclRefType; 17046 if (SemaRef.LangOpts.OpenMP) 17047 SemaRef.tryCaptureOpenMPLambdas(Var); 17048 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17049 /*EllipsisLoc*/ SourceLocation(), 17050 /*BuildAndDiagnose*/ true, 17051 CaptureType, DeclRefType, 17052 FunctionScopeIndexToStopAt); 17053 17054 Var->markUsed(SemaRef.Context); 17055 } 17056 17057 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17058 SourceLocation Loc, 17059 unsigned CapturingScopeIndex) { 17060 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17061 } 17062 17063 static void 17064 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17065 ValueDecl *var, DeclContext *DC) { 17066 DeclContext *VarDC = var->getDeclContext(); 17067 17068 // If the parameter still belongs to the translation unit, then 17069 // we're actually just using one parameter in the declaration of 17070 // the next. 17071 if (isa<ParmVarDecl>(var) && 17072 isa<TranslationUnitDecl>(VarDC)) 17073 return; 17074 17075 // For C code, don't diagnose about capture if we're not actually in code 17076 // right now; it's impossible to write a non-constant expression outside of 17077 // function context, so we'll get other (more useful) diagnostics later. 17078 // 17079 // For C++, things get a bit more nasty... it would be nice to suppress this 17080 // diagnostic for certain cases like using a local variable in an array bound 17081 // for a member of a local class, but the correct predicate is not obvious. 17082 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17083 return; 17084 17085 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17086 unsigned ContextKind = 3; // unknown 17087 if (isa<CXXMethodDecl>(VarDC) && 17088 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17089 ContextKind = 2; 17090 } else if (isa<FunctionDecl>(VarDC)) { 17091 ContextKind = 0; 17092 } else if (isa<BlockDecl>(VarDC)) { 17093 ContextKind = 1; 17094 } 17095 17096 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17097 << var << ValueKind << ContextKind << VarDC; 17098 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17099 << var; 17100 17101 // FIXME: Add additional diagnostic info about class etc. which prevents 17102 // capture. 17103 } 17104 17105 17106 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17107 bool &SubCapturesAreNested, 17108 QualType &CaptureType, 17109 QualType &DeclRefType) { 17110 // Check whether we've already captured it. 17111 if (CSI->CaptureMap.count(Var)) { 17112 // If we found a capture, any subcaptures are nested. 17113 SubCapturesAreNested = true; 17114 17115 // Retrieve the capture type for this variable. 17116 CaptureType = CSI->getCapture(Var).getCaptureType(); 17117 17118 // Compute the type of an expression that refers to this variable. 17119 DeclRefType = CaptureType.getNonReferenceType(); 17120 17121 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17122 // are mutable in the sense that user can change their value - they are 17123 // private instances of the captured declarations. 17124 const Capture &Cap = CSI->getCapture(Var); 17125 if (Cap.isCopyCapture() && 17126 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17127 !(isa<CapturedRegionScopeInfo>(CSI) && 17128 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17129 DeclRefType.addConst(); 17130 return true; 17131 } 17132 return false; 17133 } 17134 17135 // Only block literals, captured statements, and lambda expressions can 17136 // capture; other scopes don't work. 17137 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17138 SourceLocation Loc, 17139 const bool Diagnose, Sema &S) { 17140 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17141 return getLambdaAwareParentOfDeclContext(DC); 17142 else if (Var->hasLocalStorage()) { 17143 if (Diagnose) 17144 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17145 } 17146 return nullptr; 17147 } 17148 17149 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17150 // certain types of variables (unnamed, variably modified types etc.) 17151 // so check for eligibility. 17152 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17153 SourceLocation Loc, 17154 const bool Diagnose, Sema &S) { 17155 17156 bool IsBlock = isa<BlockScopeInfo>(CSI); 17157 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17158 17159 // Lambdas are not allowed to capture unnamed variables 17160 // (e.g. anonymous unions). 17161 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17162 // assuming that's the intent. 17163 if (IsLambda && !Var->getDeclName()) { 17164 if (Diagnose) { 17165 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17166 S.Diag(Var->getLocation(), diag::note_declared_at); 17167 } 17168 return false; 17169 } 17170 17171 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17172 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17173 if (Diagnose) { 17174 S.Diag(Loc, diag::err_ref_vm_type); 17175 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17176 } 17177 return false; 17178 } 17179 // Prohibit structs with flexible array members too. 17180 // We cannot capture what is in the tail end of the struct. 17181 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17182 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17183 if (Diagnose) { 17184 if (IsBlock) 17185 S.Diag(Loc, diag::err_ref_flexarray_type); 17186 else 17187 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17188 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17189 } 17190 return false; 17191 } 17192 } 17193 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17194 // Lambdas and captured statements are not allowed to capture __block 17195 // variables; they don't support the expected semantics. 17196 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17197 if (Diagnose) { 17198 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17199 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17200 } 17201 return false; 17202 } 17203 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17204 if (S.getLangOpts().OpenCL && IsBlock && 17205 Var->getType()->isBlockPointerType()) { 17206 if (Diagnose) 17207 S.Diag(Loc, diag::err_opencl_block_ref_block); 17208 return false; 17209 } 17210 17211 return true; 17212 } 17213 17214 // Returns true if the capture by block was successful. 17215 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17216 SourceLocation Loc, 17217 const bool BuildAndDiagnose, 17218 QualType &CaptureType, 17219 QualType &DeclRefType, 17220 const bool Nested, 17221 Sema &S, bool Invalid) { 17222 bool ByRef = false; 17223 17224 // Blocks are not allowed to capture arrays, excepting OpenCL. 17225 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17226 // (decayed to pointers). 17227 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17228 if (BuildAndDiagnose) { 17229 S.Diag(Loc, diag::err_ref_array_type); 17230 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17231 Invalid = true; 17232 } else { 17233 return false; 17234 } 17235 } 17236 17237 // Forbid the block-capture of autoreleasing variables. 17238 if (!Invalid && 17239 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17240 if (BuildAndDiagnose) { 17241 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17242 << /*block*/ 0; 17243 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17244 Invalid = true; 17245 } else { 17246 return false; 17247 } 17248 } 17249 17250 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17251 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17252 QualType PointeeTy = PT->getPointeeType(); 17253 17254 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17255 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17256 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17257 if (BuildAndDiagnose) { 17258 SourceLocation VarLoc = Var->getLocation(); 17259 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17260 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17261 } 17262 } 17263 } 17264 17265 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17266 if (HasBlocksAttr || CaptureType->isReferenceType() || 17267 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17268 // Block capture by reference does not change the capture or 17269 // declaration reference types. 17270 ByRef = true; 17271 } else { 17272 // Block capture by copy introduces 'const'. 17273 CaptureType = CaptureType.getNonReferenceType().withConst(); 17274 DeclRefType = CaptureType; 17275 } 17276 17277 // Actually capture the variable. 17278 if (BuildAndDiagnose) 17279 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17280 CaptureType, Invalid); 17281 17282 return !Invalid; 17283 } 17284 17285 17286 /// Capture the given variable in the captured region. 17287 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 17288 VarDecl *Var, 17289 SourceLocation Loc, 17290 const bool BuildAndDiagnose, 17291 QualType &CaptureType, 17292 QualType &DeclRefType, 17293 const bool RefersToCapturedVariable, 17294 Sema &S, bool Invalid) { 17295 // By default, capture variables by reference. 17296 bool ByRef = true; 17297 // Using an LValue reference type is consistent with Lambdas (see below). 17298 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17299 if (S.isOpenMPCapturedDecl(Var)) { 17300 bool HasConst = DeclRefType.isConstQualified(); 17301 DeclRefType = DeclRefType.getUnqualifiedType(); 17302 // Don't lose diagnostics about assignments to const. 17303 if (HasConst) 17304 DeclRefType.addConst(); 17305 } 17306 // Do not capture firstprivates in tasks. 17307 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17308 OMPC_unknown) 17309 return true; 17310 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17311 RSI->OpenMPCaptureLevel); 17312 } 17313 17314 if (ByRef) 17315 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17316 else 17317 CaptureType = DeclRefType; 17318 17319 // Actually capture the variable. 17320 if (BuildAndDiagnose) 17321 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17322 Loc, SourceLocation(), CaptureType, Invalid); 17323 17324 return !Invalid; 17325 } 17326 17327 /// Capture the given variable in the lambda. 17328 static bool captureInLambda(LambdaScopeInfo *LSI, 17329 VarDecl *Var, 17330 SourceLocation Loc, 17331 const bool BuildAndDiagnose, 17332 QualType &CaptureType, 17333 QualType &DeclRefType, 17334 const bool RefersToCapturedVariable, 17335 const Sema::TryCaptureKind Kind, 17336 SourceLocation EllipsisLoc, 17337 const bool IsTopScope, 17338 Sema &S, bool Invalid) { 17339 // Determine whether we are capturing by reference or by value. 17340 bool ByRef = false; 17341 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17342 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17343 } else { 17344 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17345 } 17346 17347 // Compute the type of the field that will capture this variable. 17348 if (ByRef) { 17349 // C++11 [expr.prim.lambda]p15: 17350 // An entity is captured by reference if it is implicitly or 17351 // explicitly captured but not captured by copy. It is 17352 // unspecified whether additional unnamed non-static data 17353 // members are declared in the closure type for entities 17354 // captured by reference. 17355 // 17356 // FIXME: It is not clear whether we want to build an lvalue reference 17357 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17358 // to do the former, while EDG does the latter. Core issue 1249 will 17359 // clarify, but for now we follow GCC because it's a more permissive and 17360 // easily defensible position. 17361 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17362 } else { 17363 // C++11 [expr.prim.lambda]p14: 17364 // For each entity captured by copy, an unnamed non-static 17365 // data member is declared in the closure type. The 17366 // declaration order of these members is unspecified. The type 17367 // of such a data member is the type of the corresponding 17368 // captured entity if the entity is not a reference to an 17369 // object, or the referenced type otherwise. [Note: If the 17370 // captured entity is a reference to a function, the 17371 // corresponding data member is also a reference to a 17372 // function. - end note ] 17373 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17374 if (!RefType->getPointeeType()->isFunctionType()) 17375 CaptureType = RefType->getPointeeType(); 17376 } 17377 17378 // Forbid the lambda copy-capture of autoreleasing variables. 17379 if (!Invalid && 17380 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17381 if (BuildAndDiagnose) { 17382 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17383 S.Diag(Var->getLocation(), diag::note_previous_decl) 17384 << Var->getDeclName(); 17385 Invalid = true; 17386 } else { 17387 return false; 17388 } 17389 } 17390 17391 // Make sure that by-copy captures are of a complete and non-abstract type. 17392 if (!Invalid && BuildAndDiagnose) { 17393 if (!CaptureType->isDependentType() && 17394 S.RequireCompleteSizedType( 17395 Loc, CaptureType, 17396 diag::err_capture_of_incomplete_or_sizeless_type, 17397 Var->getDeclName())) 17398 Invalid = true; 17399 else if (S.RequireNonAbstractType(Loc, CaptureType, 17400 diag::err_capture_of_abstract_type)) 17401 Invalid = true; 17402 } 17403 } 17404 17405 // Compute the type of a reference to this captured variable. 17406 if (ByRef) 17407 DeclRefType = CaptureType.getNonReferenceType(); 17408 else { 17409 // C++ [expr.prim.lambda]p5: 17410 // The closure type for a lambda-expression has a public inline 17411 // function call operator [...]. This function call operator is 17412 // declared const (9.3.1) if and only if the lambda-expression's 17413 // parameter-declaration-clause is not followed by mutable. 17414 DeclRefType = CaptureType.getNonReferenceType(); 17415 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17416 DeclRefType.addConst(); 17417 } 17418 17419 // Add the capture. 17420 if (BuildAndDiagnose) 17421 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17422 Loc, EllipsisLoc, CaptureType, Invalid); 17423 17424 return !Invalid; 17425 } 17426 17427 bool Sema::tryCaptureVariable( 17428 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17429 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17430 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17431 // An init-capture is notionally from the context surrounding its 17432 // declaration, but its parent DC is the lambda class. 17433 DeclContext *VarDC = Var->getDeclContext(); 17434 if (Var->isInitCapture()) 17435 VarDC = VarDC->getParent(); 17436 17437 DeclContext *DC = CurContext; 17438 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17439 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17440 // We need to sync up the Declaration Context with the 17441 // FunctionScopeIndexToStopAt 17442 if (FunctionScopeIndexToStopAt) { 17443 unsigned FSIndex = FunctionScopes.size() - 1; 17444 while (FSIndex != MaxFunctionScopesIndex) { 17445 DC = getLambdaAwareParentOfDeclContext(DC); 17446 --FSIndex; 17447 } 17448 } 17449 17450 17451 // If the variable is declared in the current context, there is no need to 17452 // capture it. 17453 if (VarDC == DC) return true; 17454 17455 // Capture global variables if it is required to use private copy of this 17456 // variable. 17457 bool IsGlobal = !Var->hasLocalStorage(); 17458 if (IsGlobal && 17459 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17460 MaxFunctionScopesIndex))) 17461 return true; 17462 Var = Var->getCanonicalDecl(); 17463 17464 // Walk up the stack to determine whether we can capture the variable, 17465 // performing the "simple" checks that don't depend on type. We stop when 17466 // we've either hit the declared scope of the variable or find an existing 17467 // capture of that variable. We start from the innermost capturing-entity 17468 // (the DC) and ensure that all intervening capturing-entities 17469 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17470 // declcontext can either capture the variable or have already captured 17471 // the variable. 17472 CaptureType = Var->getType(); 17473 DeclRefType = CaptureType.getNonReferenceType(); 17474 bool Nested = false; 17475 bool Explicit = (Kind != TryCapture_Implicit); 17476 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17477 do { 17478 // Only block literals, captured statements, and lambda expressions can 17479 // capture; other scopes don't work. 17480 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17481 ExprLoc, 17482 BuildAndDiagnose, 17483 *this); 17484 // We need to check for the parent *first* because, if we *have* 17485 // private-captured a global variable, we need to recursively capture it in 17486 // intermediate blocks, lambdas, etc. 17487 if (!ParentDC) { 17488 if (IsGlobal) { 17489 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17490 break; 17491 } 17492 return true; 17493 } 17494 17495 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17496 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17497 17498 17499 // Check whether we've already captured it. 17500 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17501 DeclRefType)) { 17502 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17503 break; 17504 } 17505 // If we are instantiating a generic lambda call operator body, 17506 // we do not want to capture new variables. What was captured 17507 // during either a lambdas transformation or initial parsing 17508 // should be used. 17509 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17510 if (BuildAndDiagnose) { 17511 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17512 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17513 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17514 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17515 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17516 } else 17517 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17518 } 17519 return true; 17520 } 17521 17522 // Try to capture variable-length arrays types. 17523 if (Var->getType()->isVariablyModifiedType()) { 17524 // We're going to walk down into the type and look for VLA 17525 // expressions. 17526 QualType QTy = Var->getType(); 17527 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17528 QTy = PVD->getOriginalType(); 17529 captureVariablyModifiedType(Context, QTy, CSI); 17530 } 17531 17532 if (getLangOpts().OpenMP) { 17533 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17534 // OpenMP private variables should not be captured in outer scope, so 17535 // just break here. Similarly, global variables that are captured in a 17536 // target region should not be captured outside the scope of the region. 17537 if (RSI->CapRegionKind == CR_OpenMP) { 17538 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17539 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17540 // If the variable is private (i.e. not captured) and has variably 17541 // modified type, we still need to capture the type for correct 17542 // codegen in all regions, associated with the construct. Currently, 17543 // it is captured in the innermost captured region only. 17544 if (IsOpenMPPrivateDecl != OMPC_unknown && 17545 Var->getType()->isVariablyModifiedType()) { 17546 QualType QTy = Var->getType(); 17547 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17548 QTy = PVD->getOriginalType(); 17549 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17550 I < E; ++I) { 17551 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17552 FunctionScopes[FunctionScopesIndex - I]); 17553 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17554 "Wrong number of captured regions associated with the " 17555 "OpenMP construct."); 17556 captureVariablyModifiedType(Context, QTy, OuterRSI); 17557 } 17558 } 17559 bool IsTargetCap = 17560 IsOpenMPPrivateDecl != OMPC_private && 17561 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17562 RSI->OpenMPCaptureLevel); 17563 // Do not capture global if it is not privatized in outer regions. 17564 bool IsGlobalCap = 17565 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17566 RSI->OpenMPCaptureLevel); 17567 17568 // When we detect target captures we are looking from inside the 17569 // target region, therefore we need to propagate the capture from the 17570 // enclosing region. Therefore, the capture is not initially nested. 17571 if (IsTargetCap) 17572 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17573 17574 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17575 (IsGlobal && !IsGlobalCap)) { 17576 Nested = !IsTargetCap; 17577 bool HasConst = DeclRefType.isConstQualified(); 17578 DeclRefType = DeclRefType.getUnqualifiedType(); 17579 // Don't lose diagnostics about assignments to const. 17580 if (HasConst) 17581 DeclRefType.addConst(); 17582 CaptureType = Context.getLValueReferenceType(DeclRefType); 17583 break; 17584 } 17585 } 17586 } 17587 } 17588 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17589 // No capture-default, and this is not an explicit capture 17590 // so cannot capture this variable. 17591 if (BuildAndDiagnose) { 17592 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17593 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17594 if (cast<LambdaScopeInfo>(CSI)->Lambda) 17595 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 17596 diag::note_lambda_decl); 17597 // FIXME: If we error out because an outer lambda can not implicitly 17598 // capture a variable that an inner lambda explicitly captures, we 17599 // should have the inner lambda do the explicit capture - because 17600 // it makes for cleaner diagnostics later. This would purely be done 17601 // so that the diagnostic does not misleadingly claim that a variable 17602 // can not be captured by a lambda implicitly even though it is captured 17603 // explicitly. Suggestion: 17604 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17605 // at the function head 17606 // - cache the StartingDeclContext - this must be a lambda 17607 // - captureInLambda in the innermost lambda the variable. 17608 } 17609 return true; 17610 } 17611 17612 FunctionScopesIndex--; 17613 DC = ParentDC; 17614 Explicit = false; 17615 } while (!VarDC->Equals(DC)); 17616 17617 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17618 // computing the type of the capture at each step, checking type-specific 17619 // requirements, and adding captures if requested. 17620 // If the variable had already been captured previously, we start capturing 17621 // at the lambda nested within that one. 17622 bool Invalid = false; 17623 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17624 ++I) { 17625 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17626 17627 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17628 // certain types of variables (unnamed, variably modified types etc.) 17629 // so check for eligibility. 17630 if (!Invalid) 17631 Invalid = 17632 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17633 17634 // After encountering an error, if we're actually supposed to capture, keep 17635 // capturing in nested contexts to suppress any follow-on diagnostics. 17636 if (Invalid && !BuildAndDiagnose) 17637 return true; 17638 17639 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17640 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17641 DeclRefType, Nested, *this, Invalid); 17642 Nested = true; 17643 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17644 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 17645 CaptureType, DeclRefType, Nested, 17646 *this, Invalid); 17647 Nested = true; 17648 } else { 17649 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17650 Invalid = 17651 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17652 DeclRefType, Nested, Kind, EllipsisLoc, 17653 /*IsTopScope*/ I == N - 1, *this, Invalid); 17654 Nested = true; 17655 } 17656 17657 if (Invalid && !BuildAndDiagnose) 17658 return true; 17659 } 17660 return Invalid; 17661 } 17662 17663 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17664 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17665 QualType CaptureType; 17666 QualType DeclRefType; 17667 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17668 /*BuildAndDiagnose=*/true, CaptureType, 17669 DeclRefType, nullptr); 17670 } 17671 17672 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17673 QualType CaptureType; 17674 QualType DeclRefType; 17675 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17676 /*BuildAndDiagnose=*/false, CaptureType, 17677 DeclRefType, nullptr); 17678 } 17679 17680 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17681 QualType CaptureType; 17682 QualType DeclRefType; 17683 17684 // Determine whether we can capture this variable. 17685 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17686 /*BuildAndDiagnose=*/false, CaptureType, 17687 DeclRefType, nullptr)) 17688 return QualType(); 17689 17690 return DeclRefType; 17691 } 17692 17693 namespace { 17694 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17695 // The produced TemplateArgumentListInfo* points to data stored within this 17696 // object, so should only be used in contexts where the pointer will not be 17697 // used after the CopiedTemplateArgs object is destroyed. 17698 class CopiedTemplateArgs { 17699 bool HasArgs; 17700 TemplateArgumentListInfo TemplateArgStorage; 17701 public: 17702 template<typename RefExpr> 17703 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17704 if (HasArgs) 17705 E->copyTemplateArgumentsInto(TemplateArgStorage); 17706 } 17707 operator TemplateArgumentListInfo*() 17708 #ifdef __has_cpp_attribute 17709 #if __has_cpp_attribute(clang::lifetimebound) 17710 [[clang::lifetimebound]] 17711 #endif 17712 #endif 17713 { 17714 return HasArgs ? &TemplateArgStorage : nullptr; 17715 } 17716 }; 17717 } 17718 17719 /// Walk the set of potential results of an expression and mark them all as 17720 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17721 /// 17722 /// \return A new expression if we found any potential results, ExprEmpty() if 17723 /// not, and ExprError() if we diagnosed an error. 17724 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17725 NonOdrUseReason NOUR) { 17726 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17727 // an object that satisfies the requirements for appearing in a 17728 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17729 // is immediately applied." This function handles the lvalue-to-rvalue 17730 // conversion part. 17731 // 17732 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17733 // transform it into the relevant kind of non-odr-use node and rebuild the 17734 // tree of nodes leading to it. 17735 // 17736 // This is a mini-TreeTransform that only transforms a restricted subset of 17737 // nodes (and only certain operands of them). 17738 17739 // Rebuild a subexpression. 17740 auto Rebuild = [&](Expr *Sub) { 17741 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17742 }; 17743 17744 // Check whether a potential result satisfies the requirements of NOUR. 17745 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17746 // Any entity other than a VarDecl is always odr-used whenever it's named 17747 // in a potentially-evaluated expression. 17748 auto *VD = dyn_cast<VarDecl>(D); 17749 if (!VD) 17750 return true; 17751 17752 // C++2a [basic.def.odr]p4: 17753 // A variable x whose name appears as a potentially-evalauted expression 17754 // e is odr-used by e unless 17755 // -- x is a reference that is usable in constant expressions, or 17756 // -- x is a variable of non-reference type that is usable in constant 17757 // expressions and has no mutable subobjects, and e is an element of 17758 // the set of potential results of an expression of 17759 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17760 // conversion is applied, or 17761 // -- x is a variable of non-reference type, and e is an element of the 17762 // set of potential results of a discarded-value expression to which 17763 // the lvalue-to-rvalue conversion is not applied 17764 // 17765 // We check the first bullet and the "potentially-evaluated" condition in 17766 // BuildDeclRefExpr. We check the type requirements in the second bullet 17767 // in CheckLValueToRValueConversionOperand below. 17768 switch (NOUR) { 17769 case NOUR_None: 17770 case NOUR_Unevaluated: 17771 llvm_unreachable("unexpected non-odr-use-reason"); 17772 17773 case NOUR_Constant: 17774 // Constant references were handled when they were built. 17775 if (VD->getType()->isReferenceType()) 17776 return true; 17777 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17778 if (RD->hasMutableFields()) 17779 return true; 17780 if (!VD->isUsableInConstantExpressions(S.Context)) 17781 return true; 17782 break; 17783 17784 case NOUR_Discarded: 17785 if (VD->getType()->isReferenceType()) 17786 return true; 17787 break; 17788 } 17789 return false; 17790 }; 17791 17792 // Mark that this expression does not constitute an odr-use. 17793 auto MarkNotOdrUsed = [&] { 17794 S.MaybeODRUseExprs.remove(E); 17795 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17796 LSI->markVariableExprAsNonODRUsed(E); 17797 }; 17798 17799 // C++2a [basic.def.odr]p2: 17800 // The set of potential results of an expression e is defined as follows: 17801 switch (E->getStmtClass()) { 17802 // -- If e is an id-expression, ... 17803 case Expr::DeclRefExprClass: { 17804 auto *DRE = cast<DeclRefExpr>(E); 17805 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17806 break; 17807 17808 // Rebuild as a non-odr-use DeclRefExpr. 17809 MarkNotOdrUsed(); 17810 return DeclRefExpr::Create( 17811 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17812 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17813 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17814 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17815 } 17816 17817 case Expr::FunctionParmPackExprClass: { 17818 auto *FPPE = cast<FunctionParmPackExpr>(E); 17819 // If any of the declarations in the pack is odr-used, then the expression 17820 // as a whole constitutes an odr-use. 17821 for (VarDecl *D : *FPPE) 17822 if (IsPotentialResultOdrUsed(D)) 17823 return ExprEmpty(); 17824 17825 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17826 // nothing cares about whether we marked this as an odr-use, but it might 17827 // be useful for non-compiler tools. 17828 MarkNotOdrUsed(); 17829 break; 17830 } 17831 17832 // -- If e is a subscripting operation with an array operand... 17833 case Expr::ArraySubscriptExprClass: { 17834 auto *ASE = cast<ArraySubscriptExpr>(E); 17835 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17836 if (!OldBase->getType()->isArrayType()) 17837 break; 17838 ExprResult Base = Rebuild(OldBase); 17839 if (!Base.isUsable()) 17840 return Base; 17841 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17842 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17843 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17844 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17845 ASE->getRBracketLoc()); 17846 } 17847 17848 case Expr::MemberExprClass: { 17849 auto *ME = cast<MemberExpr>(E); 17850 // -- If e is a class member access expression [...] naming a non-static 17851 // data member... 17852 if (isa<FieldDecl>(ME->getMemberDecl())) { 17853 ExprResult Base = Rebuild(ME->getBase()); 17854 if (!Base.isUsable()) 17855 return Base; 17856 return MemberExpr::Create( 17857 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17858 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17859 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17860 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17861 ME->getObjectKind(), ME->isNonOdrUse()); 17862 } 17863 17864 if (ME->getMemberDecl()->isCXXInstanceMember()) 17865 break; 17866 17867 // -- If e is a class member access expression naming a static data member, 17868 // ... 17869 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17870 break; 17871 17872 // Rebuild as a non-odr-use MemberExpr. 17873 MarkNotOdrUsed(); 17874 return MemberExpr::Create( 17875 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 17876 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 17877 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 17878 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 17879 return ExprEmpty(); 17880 } 17881 17882 case Expr::BinaryOperatorClass: { 17883 auto *BO = cast<BinaryOperator>(E); 17884 Expr *LHS = BO->getLHS(); 17885 Expr *RHS = BO->getRHS(); 17886 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 17887 if (BO->getOpcode() == BO_PtrMemD) { 17888 ExprResult Sub = Rebuild(LHS); 17889 if (!Sub.isUsable()) 17890 return Sub; 17891 LHS = Sub.get(); 17892 // -- If e is a comma expression, ... 17893 } else if (BO->getOpcode() == BO_Comma) { 17894 ExprResult Sub = Rebuild(RHS); 17895 if (!Sub.isUsable()) 17896 return Sub; 17897 RHS = Sub.get(); 17898 } else { 17899 break; 17900 } 17901 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17902 LHS, RHS); 17903 } 17904 17905 // -- If e has the form (e1)... 17906 case Expr::ParenExprClass: { 17907 auto *PE = cast<ParenExpr>(E); 17908 ExprResult Sub = Rebuild(PE->getSubExpr()); 17909 if (!Sub.isUsable()) 17910 return Sub; 17911 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17912 } 17913 17914 // -- If e is a glvalue conditional expression, ... 17915 // We don't apply this to a binary conditional operator. FIXME: Should we? 17916 case Expr::ConditionalOperatorClass: { 17917 auto *CO = cast<ConditionalOperator>(E); 17918 ExprResult LHS = Rebuild(CO->getLHS()); 17919 if (LHS.isInvalid()) 17920 return ExprError(); 17921 ExprResult RHS = Rebuild(CO->getRHS()); 17922 if (RHS.isInvalid()) 17923 return ExprError(); 17924 if (!LHS.isUsable() && !RHS.isUsable()) 17925 return ExprEmpty(); 17926 if (!LHS.isUsable()) 17927 LHS = CO->getLHS(); 17928 if (!RHS.isUsable()) 17929 RHS = CO->getRHS(); 17930 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17931 CO->getCond(), LHS.get(), RHS.get()); 17932 } 17933 17934 // [Clang extension] 17935 // -- If e has the form __extension__ e1... 17936 case Expr::UnaryOperatorClass: { 17937 auto *UO = cast<UnaryOperator>(E); 17938 if (UO->getOpcode() != UO_Extension) 17939 break; 17940 ExprResult Sub = Rebuild(UO->getSubExpr()); 17941 if (!Sub.isUsable()) 17942 return Sub; 17943 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17944 Sub.get()); 17945 } 17946 17947 // [Clang extension] 17948 // -- If e has the form _Generic(...), the set of potential results is the 17949 // union of the sets of potential results of the associated expressions. 17950 case Expr::GenericSelectionExprClass: { 17951 auto *GSE = cast<GenericSelectionExpr>(E); 17952 17953 SmallVector<Expr *, 4> AssocExprs; 17954 bool AnyChanged = false; 17955 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17956 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17957 if (AssocExpr.isInvalid()) 17958 return ExprError(); 17959 if (AssocExpr.isUsable()) { 17960 AssocExprs.push_back(AssocExpr.get()); 17961 AnyChanged = true; 17962 } else { 17963 AssocExprs.push_back(OrigAssocExpr); 17964 } 17965 } 17966 17967 return AnyChanged ? S.CreateGenericSelectionExpr( 17968 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17969 GSE->getRParenLoc(), GSE->getControllingExpr(), 17970 GSE->getAssocTypeSourceInfos(), AssocExprs) 17971 : ExprEmpty(); 17972 } 17973 17974 // [Clang extension] 17975 // -- If e has the form __builtin_choose_expr(...), the set of potential 17976 // results is the union of the sets of potential results of the 17977 // second and third subexpressions. 17978 case Expr::ChooseExprClass: { 17979 auto *CE = cast<ChooseExpr>(E); 17980 17981 ExprResult LHS = Rebuild(CE->getLHS()); 17982 if (LHS.isInvalid()) 17983 return ExprError(); 17984 17985 ExprResult RHS = Rebuild(CE->getLHS()); 17986 if (RHS.isInvalid()) 17987 return ExprError(); 17988 17989 if (!LHS.get() && !RHS.get()) 17990 return ExprEmpty(); 17991 if (!LHS.isUsable()) 17992 LHS = CE->getLHS(); 17993 if (!RHS.isUsable()) 17994 RHS = CE->getRHS(); 17995 17996 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17997 RHS.get(), CE->getRParenLoc()); 17998 } 17999 18000 // Step through non-syntactic nodes. 18001 case Expr::ConstantExprClass: { 18002 auto *CE = cast<ConstantExpr>(E); 18003 ExprResult Sub = Rebuild(CE->getSubExpr()); 18004 if (!Sub.isUsable()) 18005 return Sub; 18006 return ConstantExpr::Create(S.Context, Sub.get()); 18007 } 18008 18009 // We could mostly rely on the recursive rebuilding to rebuild implicit 18010 // casts, but not at the top level, so rebuild them here. 18011 case Expr::ImplicitCastExprClass: { 18012 auto *ICE = cast<ImplicitCastExpr>(E); 18013 // Only step through the narrow set of cast kinds we expect to encounter. 18014 // Anything else suggests we've left the region in which potential results 18015 // can be found. 18016 switch (ICE->getCastKind()) { 18017 case CK_NoOp: 18018 case CK_DerivedToBase: 18019 case CK_UncheckedDerivedToBase: { 18020 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18021 if (!Sub.isUsable()) 18022 return Sub; 18023 CXXCastPath Path(ICE->path()); 18024 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18025 ICE->getValueKind(), &Path); 18026 } 18027 18028 default: 18029 break; 18030 } 18031 break; 18032 } 18033 18034 default: 18035 break; 18036 } 18037 18038 // Can't traverse through this node. Nothing to do. 18039 return ExprEmpty(); 18040 } 18041 18042 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18043 // Check whether the operand is or contains an object of non-trivial C union 18044 // type. 18045 if (E->getType().isVolatileQualified() && 18046 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18047 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18048 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18049 Sema::NTCUC_LValueToRValueVolatile, 18050 NTCUK_Destruct|NTCUK_Copy); 18051 18052 // C++2a [basic.def.odr]p4: 18053 // [...] an expression of non-volatile-qualified non-class type to which 18054 // the lvalue-to-rvalue conversion is applied [...] 18055 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18056 return E; 18057 18058 ExprResult Result = 18059 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18060 if (Result.isInvalid()) 18061 return ExprError(); 18062 return Result.get() ? Result : E; 18063 } 18064 18065 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18066 Res = CorrectDelayedTyposInExpr(Res); 18067 18068 if (!Res.isUsable()) 18069 return Res; 18070 18071 // If a constant-expression is a reference to a variable where we delay 18072 // deciding whether it is an odr-use, just assume we will apply the 18073 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18074 // (a non-type template argument), we have special handling anyway. 18075 return CheckLValueToRValueConversionOperand(Res.get()); 18076 } 18077 18078 void Sema::CleanupVarDeclMarking() { 18079 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18080 // call. 18081 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18082 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18083 18084 for (Expr *E : LocalMaybeODRUseExprs) { 18085 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18086 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18087 DRE->getLocation(), *this); 18088 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18089 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18090 *this); 18091 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18092 for (VarDecl *VD : *FP) 18093 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18094 } else { 18095 llvm_unreachable("Unexpected expression"); 18096 } 18097 } 18098 18099 assert(MaybeODRUseExprs.empty() && 18100 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18101 } 18102 18103 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18104 VarDecl *Var, Expr *E) { 18105 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18106 isa<FunctionParmPackExpr>(E)) && 18107 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18108 Var->setReferenced(); 18109 18110 if (Var->isInvalidDecl()) 18111 return; 18112 18113 // Record a CUDA/HIP static device/constant variable if it is referenced 18114 // by host code. This is done conservatively, when the variable is referenced 18115 // in any of the following contexts: 18116 // - a non-function context 18117 // - a host function 18118 // - a host device function 18119 // This also requires the reference of the static device/constant variable by 18120 // host code to be visible in the device compilation for the compiler to be 18121 // able to externalize the static device/constant variable. 18122 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18123 auto *CurContext = SemaRef.CurContext; 18124 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18125 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18126 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18127 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18128 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18129 } 18130 18131 auto *MSI = Var->getMemberSpecializationInfo(); 18132 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18133 : Var->getTemplateSpecializationKind(); 18134 18135 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18136 bool UsableInConstantExpr = 18137 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18138 18139 // C++20 [expr.const]p12: 18140 // A variable [...] is needed for constant evaluation if it is [...] a 18141 // variable whose name appears as a potentially constant evaluated 18142 // expression that is either a contexpr variable or is of non-volatile 18143 // const-qualified integral type or of reference type 18144 bool NeededForConstantEvaluation = 18145 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18146 18147 bool NeedDefinition = 18148 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18149 18150 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18151 "Can't instantiate a partial template specialization."); 18152 18153 // If this might be a member specialization of a static data member, check 18154 // the specialization is visible. We already did the checks for variable 18155 // template specializations when we created them. 18156 if (NeedDefinition && TSK != TSK_Undeclared && 18157 !isa<VarTemplateSpecializationDecl>(Var)) 18158 SemaRef.checkSpecializationVisibility(Loc, Var); 18159 18160 // Perform implicit instantiation of static data members, static data member 18161 // templates of class templates, and variable template specializations. Delay 18162 // instantiations of variable templates, except for those that could be used 18163 // in a constant expression. 18164 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18165 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18166 // instantiation declaration if a variable is usable in a constant 18167 // expression (among other cases). 18168 bool TryInstantiating = 18169 TSK == TSK_ImplicitInstantiation || 18170 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18171 18172 if (TryInstantiating) { 18173 SourceLocation PointOfInstantiation = 18174 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18175 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18176 if (FirstInstantiation) { 18177 PointOfInstantiation = Loc; 18178 if (MSI) 18179 MSI->setPointOfInstantiation(PointOfInstantiation); 18180 // FIXME: Notify listener. 18181 else 18182 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18183 } 18184 18185 if (UsableInConstantExpr) { 18186 // Do not defer instantiations of variables that could be used in a 18187 // constant expression. 18188 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18189 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18190 }); 18191 18192 // Re-set the member to trigger a recomputation of the dependence bits 18193 // for the expression. 18194 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18195 DRE->setDecl(DRE->getDecl()); 18196 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18197 ME->setMemberDecl(ME->getMemberDecl()); 18198 } else if (FirstInstantiation || 18199 isa<VarTemplateSpecializationDecl>(Var)) { 18200 // FIXME: For a specialization of a variable template, we don't 18201 // distinguish between "declaration and type implicitly instantiated" 18202 // and "implicit instantiation of definition requested", so we have 18203 // no direct way to avoid enqueueing the pending instantiation 18204 // multiple times. 18205 SemaRef.PendingInstantiations 18206 .push_back(std::make_pair(Var, PointOfInstantiation)); 18207 } 18208 } 18209 } 18210 18211 // C++2a [basic.def.odr]p4: 18212 // A variable x whose name appears as a potentially-evaluated expression e 18213 // is odr-used by e unless 18214 // -- x is a reference that is usable in constant expressions 18215 // -- x is a variable of non-reference type that is usable in constant 18216 // expressions and has no mutable subobjects [FIXME], and e is an 18217 // element of the set of potential results of an expression of 18218 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18219 // conversion is applied 18220 // -- x is a variable of non-reference type, and e is an element of the set 18221 // of potential results of a discarded-value expression to which the 18222 // lvalue-to-rvalue conversion is not applied [FIXME] 18223 // 18224 // We check the first part of the second bullet here, and 18225 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18226 // FIXME: To get the third bullet right, we need to delay this even for 18227 // variables that are not usable in constant expressions. 18228 18229 // If we already know this isn't an odr-use, there's nothing more to do. 18230 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18231 if (DRE->isNonOdrUse()) 18232 return; 18233 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18234 if (ME->isNonOdrUse()) 18235 return; 18236 18237 switch (OdrUse) { 18238 case OdrUseContext::None: 18239 assert((!E || isa<FunctionParmPackExpr>(E)) && 18240 "missing non-odr-use marking for unevaluated decl ref"); 18241 break; 18242 18243 case OdrUseContext::FormallyOdrUsed: 18244 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18245 // behavior. 18246 break; 18247 18248 case OdrUseContext::Used: 18249 // If we might later find that this expression isn't actually an odr-use, 18250 // delay the marking. 18251 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18252 SemaRef.MaybeODRUseExprs.insert(E); 18253 else 18254 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18255 break; 18256 18257 case OdrUseContext::Dependent: 18258 // If this is a dependent context, we don't need to mark variables as 18259 // odr-used, but we may still need to track them for lambda capture. 18260 // FIXME: Do we also need to do this inside dependent typeid expressions 18261 // (which are modeled as unevaluated at this point)? 18262 const bool RefersToEnclosingScope = 18263 (SemaRef.CurContext != Var->getDeclContext() && 18264 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18265 if (RefersToEnclosingScope) { 18266 LambdaScopeInfo *const LSI = 18267 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18268 if (LSI && (!LSI->CallOperator || 18269 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18270 // If a variable could potentially be odr-used, defer marking it so 18271 // until we finish analyzing the full expression for any 18272 // lvalue-to-rvalue 18273 // or discarded value conversions that would obviate odr-use. 18274 // Add it to the list of potential captures that will be analyzed 18275 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18276 // unless the variable is a reference that was initialized by a constant 18277 // expression (this will never need to be captured or odr-used). 18278 // 18279 // FIXME: We can simplify this a lot after implementing P0588R1. 18280 assert(E && "Capture variable should be used in an expression."); 18281 if (!Var->getType()->isReferenceType() || 18282 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18283 LSI->addPotentialCapture(E->IgnoreParens()); 18284 } 18285 } 18286 break; 18287 } 18288 } 18289 18290 /// Mark a variable referenced, and check whether it is odr-used 18291 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18292 /// used directly for normal expressions referring to VarDecl. 18293 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18294 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18295 } 18296 18297 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18298 Decl *D, Expr *E, bool MightBeOdrUse) { 18299 if (SemaRef.isInOpenMPDeclareTargetContext()) 18300 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18301 18302 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18303 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18304 return; 18305 } 18306 18307 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18308 18309 // If this is a call to a method via a cast, also mark the method in the 18310 // derived class used in case codegen can devirtualize the call. 18311 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18312 if (!ME) 18313 return; 18314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18315 if (!MD) 18316 return; 18317 // Only attempt to devirtualize if this is truly a virtual call. 18318 bool IsVirtualCall = MD->isVirtual() && 18319 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18320 if (!IsVirtualCall) 18321 return; 18322 18323 // If it's possible to devirtualize the call, mark the called function 18324 // referenced. 18325 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18326 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18327 if (DM) 18328 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18329 } 18330 18331 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18332 /// 18333 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18334 /// handled with care if the DeclRefExpr is not newly-created. 18335 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18336 // TODO: update this with DR# once a defect report is filed. 18337 // C++11 defect. The address of a pure member should not be an ODR use, even 18338 // if it's a qualified reference. 18339 bool OdrUse = true; 18340 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18341 if (Method->isVirtual() && 18342 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18343 OdrUse = false; 18344 18345 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18346 if (!isConstantEvaluated() && FD->isConsteval() && 18347 !RebuildingImmediateInvocation) 18348 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18349 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18350 } 18351 18352 /// Perform reference-marking and odr-use handling for a MemberExpr. 18353 void Sema::MarkMemberReferenced(MemberExpr *E) { 18354 // C++11 [basic.def.odr]p2: 18355 // A non-overloaded function whose name appears as a potentially-evaluated 18356 // expression or a member of a set of candidate functions, if selected by 18357 // overload resolution when referred to from a potentially-evaluated 18358 // expression, is odr-used, unless it is a pure virtual function and its 18359 // name is not explicitly qualified. 18360 bool MightBeOdrUse = true; 18361 if (E->performsVirtualDispatch(getLangOpts())) { 18362 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18363 if (Method->isPure()) 18364 MightBeOdrUse = false; 18365 } 18366 SourceLocation Loc = 18367 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18368 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18369 } 18370 18371 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18372 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18373 for (VarDecl *VD : *E) 18374 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18375 } 18376 18377 /// Perform marking for a reference to an arbitrary declaration. It 18378 /// marks the declaration referenced, and performs odr-use checking for 18379 /// functions and variables. This method should not be used when building a 18380 /// normal expression which refers to a variable. 18381 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18382 bool MightBeOdrUse) { 18383 if (MightBeOdrUse) { 18384 if (auto *VD = dyn_cast<VarDecl>(D)) { 18385 MarkVariableReferenced(Loc, VD); 18386 return; 18387 } 18388 } 18389 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18390 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18391 return; 18392 } 18393 D->setReferenced(); 18394 } 18395 18396 namespace { 18397 // Mark all of the declarations used by a type as referenced. 18398 // FIXME: Not fully implemented yet! We need to have a better understanding 18399 // of when we're entering a context we should not recurse into. 18400 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18401 // TreeTransforms rebuilding the type in a new context. Rather than 18402 // duplicating the TreeTransform logic, we should consider reusing it here. 18403 // Currently that causes problems when rebuilding LambdaExprs. 18404 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18405 Sema &S; 18406 SourceLocation Loc; 18407 18408 public: 18409 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18410 18411 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18412 18413 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18414 }; 18415 } 18416 18417 bool MarkReferencedDecls::TraverseTemplateArgument( 18418 const TemplateArgument &Arg) { 18419 { 18420 // A non-type template argument is a constant-evaluated context. 18421 EnterExpressionEvaluationContext Evaluated( 18422 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18423 if (Arg.getKind() == TemplateArgument::Declaration) { 18424 if (Decl *D = Arg.getAsDecl()) 18425 S.MarkAnyDeclReferenced(Loc, D, true); 18426 } else if (Arg.getKind() == TemplateArgument::Expression) { 18427 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18428 } 18429 } 18430 18431 return Inherited::TraverseTemplateArgument(Arg); 18432 } 18433 18434 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18435 MarkReferencedDecls Marker(*this, Loc); 18436 Marker.TraverseType(T); 18437 } 18438 18439 namespace { 18440 /// Helper class that marks all of the declarations referenced by 18441 /// potentially-evaluated subexpressions as "referenced". 18442 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18443 public: 18444 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18445 bool SkipLocalVariables; 18446 18447 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18448 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18449 18450 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18451 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18452 } 18453 18454 void VisitDeclRefExpr(DeclRefExpr *E) { 18455 // If we were asked not to visit local variables, don't. 18456 if (SkipLocalVariables) { 18457 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18458 if (VD->hasLocalStorage()) 18459 return; 18460 } 18461 18462 // FIXME: This can trigger the instantiation of the initializer of a 18463 // variable, which can cause the expression to become value-dependent 18464 // or error-dependent. Do we need to propagate the new dependence bits? 18465 S.MarkDeclRefReferenced(E); 18466 } 18467 18468 void VisitMemberExpr(MemberExpr *E) { 18469 S.MarkMemberReferenced(E); 18470 Visit(E->getBase()); 18471 } 18472 }; 18473 } // namespace 18474 18475 /// Mark any declarations that appear within this expression or any 18476 /// potentially-evaluated subexpressions as "referenced". 18477 /// 18478 /// \param SkipLocalVariables If true, don't mark local variables as 18479 /// 'referenced'. 18480 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18481 bool SkipLocalVariables) { 18482 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18483 } 18484 18485 /// Emit a diagnostic that describes an effect on the run-time behavior 18486 /// of the program being compiled. 18487 /// 18488 /// This routine emits the given diagnostic when the code currently being 18489 /// type-checked is "potentially evaluated", meaning that there is a 18490 /// possibility that the code will actually be executable. Code in sizeof() 18491 /// expressions, code used only during overload resolution, etc., are not 18492 /// potentially evaluated. This routine will suppress such diagnostics or, 18493 /// in the absolutely nutty case of potentially potentially evaluated 18494 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18495 /// later. 18496 /// 18497 /// This routine should be used for all diagnostics that describe the run-time 18498 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18499 /// Failure to do so will likely result in spurious diagnostics or failures 18500 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18501 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18502 const PartialDiagnostic &PD) { 18503 switch (ExprEvalContexts.back().Context) { 18504 case ExpressionEvaluationContext::Unevaluated: 18505 case ExpressionEvaluationContext::UnevaluatedList: 18506 case ExpressionEvaluationContext::UnevaluatedAbstract: 18507 case ExpressionEvaluationContext::DiscardedStatement: 18508 // The argument will never be evaluated, so don't complain. 18509 break; 18510 18511 case ExpressionEvaluationContext::ConstantEvaluated: 18512 // Relevant diagnostics should be produced by constant evaluation. 18513 break; 18514 18515 case ExpressionEvaluationContext::PotentiallyEvaluated: 18516 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18517 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18518 FunctionScopes.back()->PossiblyUnreachableDiags. 18519 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18520 return true; 18521 } 18522 18523 // The initializer of a constexpr variable or of the first declaration of a 18524 // static data member is not syntactically a constant evaluated constant, 18525 // but nonetheless is always required to be a constant expression, so we 18526 // can skip diagnosing. 18527 // FIXME: Using the mangling context here is a hack. 18528 if (auto *VD = dyn_cast_or_null<VarDecl>( 18529 ExprEvalContexts.back().ManglingContextDecl)) { 18530 if (VD->isConstexpr() || 18531 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18532 break; 18533 // FIXME: For any other kind of variable, we should build a CFG for its 18534 // initializer and check whether the context in question is reachable. 18535 } 18536 18537 Diag(Loc, PD); 18538 return true; 18539 } 18540 18541 return false; 18542 } 18543 18544 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18545 const PartialDiagnostic &PD) { 18546 return DiagRuntimeBehavior( 18547 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18548 } 18549 18550 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18551 CallExpr *CE, FunctionDecl *FD) { 18552 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18553 return false; 18554 18555 // If we're inside a decltype's expression, don't check for a valid return 18556 // type or construct temporaries until we know whether this is the last call. 18557 if (ExprEvalContexts.back().ExprContext == 18558 ExpressionEvaluationContextRecord::EK_Decltype) { 18559 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18560 return false; 18561 } 18562 18563 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18564 FunctionDecl *FD; 18565 CallExpr *CE; 18566 18567 public: 18568 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18569 : FD(FD), CE(CE) { } 18570 18571 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18572 if (!FD) { 18573 S.Diag(Loc, diag::err_call_incomplete_return) 18574 << T << CE->getSourceRange(); 18575 return; 18576 } 18577 18578 S.Diag(Loc, diag::err_call_function_incomplete_return) 18579 << CE->getSourceRange() << FD << T; 18580 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18581 << FD->getDeclName(); 18582 } 18583 } Diagnoser(FD, CE); 18584 18585 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18586 return true; 18587 18588 return false; 18589 } 18590 18591 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18592 // will prevent this condition from triggering, which is what we want. 18593 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18594 SourceLocation Loc; 18595 18596 unsigned diagnostic = diag::warn_condition_is_assignment; 18597 bool IsOrAssign = false; 18598 18599 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18600 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18601 return; 18602 18603 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18604 18605 // Greylist some idioms by putting them into a warning subcategory. 18606 if (ObjCMessageExpr *ME 18607 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18608 Selector Sel = ME->getSelector(); 18609 18610 // self = [<foo> init...] 18611 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18612 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18613 18614 // <foo> = [<bar> nextObject] 18615 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18616 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18617 } 18618 18619 Loc = Op->getOperatorLoc(); 18620 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18621 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18622 return; 18623 18624 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18625 Loc = Op->getOperatorLoc(); 18626 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18627 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18628 else { 18629 // Not an assignment. 18630 return; 18631 } 18632 18633 Diag(Loc, diagnostic) << E->getSourceRange(); 18634 18635 SourceLocation Open = E->getBeginLoc(); 18636 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18637 Diag(Loc, diag::note_condition_assign_silence) 18638 << FixItHint::CreateInsertion(Open, "(") 18639 << FixItHint::CreateInsertion(Close, ")"); 18640 18641 if (IsOrAssign) 18642 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18643 << FixItHint::CreateReplacement(Loc, "!="); 18644 else 18645 Diag(Loc, diag::note_condition_assign_to_comparison) 18646 << FixItHint::CreateReplacement(Loc, "=="); 18647 } 18648 18649 /// Redundant parentheses over an equality comparison can indicate 18650 /// that the user intended an assignment used as condition. 18651 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18652 // Don't warn if the parens came from a macro. 18653 SourceLocation parenLoc = ParenE->getBeginLoc(); 18654 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18655 return; 18656 // Don't warn for dependent expressions. 18657 if (ParenE->isTypeDependent()) 18658 return; 18659 18660 Expr *E = ParenE->IgnoreParens(); 18661 18662 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18663 if (opE->getOpcode() == BO_EQ && 18664 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18665 == Expr::MLV_Valid) { 18666 SourceLocation Loc = opE->getOperatorLoc(); 18667 18668 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18669 SourceRange ParenERange = ParenE->getSourceRange(); 18670 Diag(Loc, diag::note_equality_comparison_silence) 18671 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18672 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18673 Diag(Loc, diag::note_equality_comparison_to_assign) 18674 << FixItHint::CreateReplacement(Loc, "="); 18675 } 18676 } 18677 18678 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18679 bool IsConstexpr) { 18680 DiagnoseAssignmentAsCondition(E); 18681 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18682 DiagnoseEqualityWithExtraParens(parenE); 18683 18684 ExprResult result = CheckPlaceholderExpr(E); 18685 if (result.isInvalid()) return ExprError(); 18686 E = result.get(); 18687 18688 if (!E->isTypeDependent()) { 18689 if (getLangOpts().CPlusPlus) 18690 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18691 18692 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18693 if (ERes.isInvalid()) 18694 return ExprError(); 18695 E = ERes.get(); 18696 18697 QualType T = E->getType(); 18698 if (!T->isScalarType()) { // C99 6.8.4.1p1 18699 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18700 << T << E->getSourceRange(); 18701 return ExprError(); 18702 } 18703 CheckBoolLikeConversion(E, Loc); 18704 } 18705 18706 return E; 18707 } 18708 18709 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18710 Expr *SubExpr, ConditionKind CK) { 18711 // Empty conditions are valid in for-statements. 18712 if (!SubExpr) 18713 return ConditionResult(); 18714 18715 ExprResult Cond; 18716 switch (CK) { 18717 case ConditionKind::Boolean: 18718 Cond = CheckBooleanCondition(Loc, SubExpr); 18719 break; 18720 18721 case ConditionKind::ConstexprIf: 18722 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18723 break; 18724 18725 case ConditionKind::Switch: 18726 Cond = CheckSwitchCondition(Loc, SubExpr); 18727 break; 18728 } 18729 if (Cond.isInvalid()) { 18730 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18731 {SubExpr}); 18732 if (!Cond.get()) 18733 return ConditionError(); 18734 } 18735 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18736 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18737 if (!FullExpr.get()) 18738 return ConditionError(); 18739 18740 return ConditionResult(*this, nullptr, FullExpr, 18741 CK == ConditionKind::ConstexprIf); 18742 } 18743 18744 namespace { 18745 /// A visitor for rebuilding a call to an __unknown_any expression 18746 /// to have an appropriate type. 18747 struct RebuildUnknownAnyFunction 18748 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18749 18750 Sema &S; 18751 18752 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18753 18754 ExprResult VisitStmt(Stmt *S) { 18755 llvm_unreachable("unexpected statement!"); 18756 } 18757 18758 ExprResult VisitExpr(Expr *E) { 18759 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18760 << E->getSourceRange(); 18761 return ExprError(); 18762 } 18763 18764 /// Rebuild an expression which simply semantically wraps another 18765 /// expression which it shares the type and value kind of. 18766 template <class T> ExprResult rebuildSugarExpr(T *E) { 18767 ExprResult SubResult = Visit(E->getSubExpr()); 18768 if (SubResult.isInvalid()) return ExprError(); 18769 18770 Expr *SubExpr = SubResult.get(); 18771 E->setSubExpr(SubExpr); 18772 E->setType(SubExpr->getType()); 18773 E->setValueKind(SubExpr->getValueKind()); 18774 assert(E->getObjectKind() == OK_Ordinary); 18775 return E; 18776 } 18777 18778 ExprResult VisitParenExpr(ParenExpr *E) { 18779 return rebuildSugarExpr(E); 18780 } 18781 18782 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18783 return rebuildSugarExpr(E); 18784 } 18785 18786 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18787 ExprResult SubResult = Visit(E->getSubExpr()); 18788 if (SubResult.isInvalid()) return ExprError(); 18789 18790 Expr *SubExpr = SubResult.get(); 18791 E->setSubExpr(SubExpr); 18792 E->setType(S.Context.getPointerType(SubExpr->getType())); 18793 assert(E->getValueKind() == VK_RValue); 18794 assert(E->getObjectKind() == OK_Ordinary); 18795 return E; 18796 } 18797 18798 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18799 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18800 18801 E->setType(VD->getType()); 18802 18803 assert(E->getValueKind() == VK_RValue); 18804 if (S.getLangOpts().CPlusPlus && 18805 !(isa<CXXMethodDecl>(VD) && 18806 cast<CXXMethodDecl>(VD)->isInstance())) 18807 E->setValueKind(VK_LValue); 18808 18809 return E; 18810 } 18811 18812 ExprResult VisitMemberExpr(MemberExpr *E) { 18813 return resolveDecl(E, E->getMemberDecl()); 18814 } 18815 18816 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18817 return resolveDecl(E, E->getDecl()); 18818 } 18819 }; 18820 } 18821 18822 /// Given a function expression of unknown-any type, try to rebuild it 18823 /// to have a function type. 18824 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18825 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18826 if (Result.isInvalid()) return ExprError(); 18827 return S.DefaultFunctionArrayConversion(Result.get()); 18828 } 18829 18830 namespace { 18831 /// A visitor for rebuilding an expression of type __unknown_anytype 18832 /// into one which resolves the type directly on the referring 18833 /// expression. Strict preservation of the original source 18834 /// structure is not a goal. 18835 struct RebuildUnknownAnyExpr 18836 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18837 18838 Sema &S; 18839 18840 /// The current destination type. 18841 QualType DestType; 18842 18843 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18844 : S(S), DestType(CastType) {} 18845 18846 ExprResult VisitStmt(Stmt *S) { 18847 llvm_unreachable("unexpected statement!"); 18848 } 18849 18850 ExprResult VisitExpr(Expr *E) { 18851 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18852 << E->getSourceRange(); 18853 return ExprError(); 18854 } 18855 18856 ExprResult VisitCallExpr(CallExpr *E); 18857 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18858 18859 /// Rebuild an expression which simply semantically wraps another 18860 /// expression which it shares the type and value kind of. 18861 template <class T> ExprResult rebuildSugarExpr(T *E) { 18862 ExprResult SubResult = Visit(E->getSubExpr()); 18863 if (SubResult.isInvalid()) return ExprError(); 18864 Expr *SubExpr = SubResult.get(); 18865 E->setSubExpr(SubExpr); 18866 E->setType(SubExpr->getType()); 18867 E->setValueKind(SubExpr->getValueKind()); 18868 assert(E->getObjectKind() == OK_Ordinary); 18869 return E; 18870 } 18871 18872 ExprResult VisitParenExpr(ParenExpr *E) { 18873 return rebuildSugarExpr(E); 18874 } 18875 18876 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18877 return rebuildSugarExpr(E); 18878 } 18879 18880 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18881 const PointerType *Ptr = DestType->getAs<PointerType>(); 18882 if (!Ptr) { 18883 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 18884 << E->getSourceRange(); 18885 return ExprError(); 18886 } 18887 18888 if (isa<CallExpr>(E->getSubExpr())) { 18889 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 18890 << E->getSourceRange(); 18891 return ExprError(); 18892 } 18893 18894 assert(E->getValueKind() == VK_RValue); 18895 assert(E->getObjectKind() == OK_Ordinary); 18896 E->setType(DestType); 18897 18898 // Build the sub-expression as if it were an object of the pointee type. 18899 DestType = Ptr->getPointeeType(); 18900 ExprResult SubResult = Visit(E->getSubExpr()); 18901 if (SubResult.isInvalid()) return ExprError(); 18902 E->setSubExpr(SubResult.get()); 18903 return E; 18904 } 18905 18906 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 18907 18908 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 18909 18910 ExprResult VisitMemberExpr(MemberExpr *E) { 18911 return resolveDecl(E, E->getMemberDecl()); 18912 } 18913 18914 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18915 return resolveDecl(E, E->getDecl()); 18916 } 18917 }; 18918 } 18919 18920 /// Rebuilds a call expression which yielded __unknown_anytype. 18921 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 18922 Expr *CalleeExpr = E->getCallee(); 18923 18924 enum FnKind { 18925 FK_MemberFunction, 18926 FK_FunctionPointer, 18927 FK_BlockPointer 18928 }; 18929 18930 FnKind Kind; 18931 QualType CalleeType = CalleeExpr->getType(); 18932 if (CalleeType == S.Context.BoundMemberTy) { 18933 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18934 Kind = FK_MemberFunction; 18935 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18936 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18937 CalleeType = Ptr->getPointeeType(); 18938 Kind = FK_FunctionPointer; 18939 } else { 18940 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18941 Kind = FK_BlockPointer; 18942 } 18943 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18944 18945 // Verify that this is a legal result type of a function. 18946 if (DestType->isArrayType() || DestType->isFunctionType()) { 18947 unsigned diagID = diag::err_func_returning_array_function; 18948 if (Kind == FK_BlockPointer) 18949 diagID = diag::err_block_returning_array_function; 18950 18951 S.Diag(E->getExprLoc(), diagID) 18952 << DestType->isFunctionType() << DestType; 18953 return ExprError(); 18954 } 18955 18956 // Otherwise, go ahead and set DestType as the call's result. 18957 E->setType(DestType.getNonLValueExprType(S.Context)); 18958 E->setValueKind(Expr::getValueKindForType(DestType)); 18959 assert(E->getObjectKind() == OK_Ordinary); 18960 18961 // Rebuild the function type, replacing the result type with DestType. 18962 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18963 if (Proto) { 18964 // __unknown_anytype(...) is a special case used by the debugger when 18965 // it has no idea what a function's signature is. 18966 // 18967 // We want to build this call essentially under the K&R 18968 // unprototyped rules, but making a FunctionNoProtoType in C++ 18969 // would foul up all sorts of assumptions. However, we cannot 18970 // simply pass all arguments as variadic arguments, nor can we 18971 // portably just call the function under a non-variadic type; see 18972 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18973 // However, it turns out that in practice it is generally safe to 18974 // call a function declared as "A foo(B,C,D);" under the prototype 18975 // "A foo(B,C,D,...);". The only known exception is with the 18976 // Windows ABI, where any variadic function is implicitly cdecl 18977 // regardless of its normal CC. Therefore we change the parameter 18978 // types to match the types of the arguments. 18979 // 18980 // This is a hack, but it is far superior to moving the 18981 // corresponding target-specific code from IR-gen to Sema/AST. 18982 18983 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18984 SmallVector<QualType, 8> ArgTypes; 18985 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18986 ArgTypes.reserve(E->getNumArgs()); 18987 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18988 Expr *Arg = E->getArg(i); 18989 QualType ArgType = Arg->getType(); 18990 if (E->isLValue()) { 18991 ArgType = S.Context.getLValueReferenceType(ArgType); 18992 } else if (E->isXValue()) { 18993 ArgType = S.Context.getRValueReferenceType(ArgType); 18994 } 18995 ArgTypes.push_back(ArgType); 18996 } 18997 ParamTypes = ArgTypes; 18998 } 18999 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19000 Proto->getExtProtoInfo()); 19001 } else { 19002 DestType = S.Context.getFunctionNoProtoType(DestType, 19003 FnType->getExtInfo()); 19004 } 19005 19006 // Rebuild the appropriate pointer-to-function type. 19007 switch (Kind) { 19008 case FK_MemberFunction: 19009 // Nothing to do. 19010 break; 19011 19012 case FK_FunctionPointer: 19013 DestType = S.Context.getPointerType(DestType); 19014 break; 19015 19016 case FK_BlockPointer: 19017 DestType = S.Context.getBlockPointerType(DestType); 19018 break; 19019 } 19020 19021 // Finally, we can recurse. 19022 ExprResult CalleeResult = Visit(CalleeExpr); 19023 if (!CalleeResult.isUsable()) return ExprError(); 19024 E->setCallee(CalleeResult.get()); 19025 19026 // Bind a temporary if necessary. 19027 return S.MaybeBindToTemporary(E); 19028 } 19029 19030 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19031 // Verify that this is a legal result type of a call. 19032 if (DestType->isArrayType() || DestType->isFunctionType()) { 19033 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19034 << DestType->isFunctionType() << DestType; 19035 return ExprError(); 19036 } 19037 19038 // Rewrite the method result type if available. 19039 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19040 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19041 Method->setReturnType(DestType); 19042 } 19043 19044 // Change the type of the message. 19045 E->setType(DestType.getNonReferenceType()); 19046 E->setValueKind(Expr::getValueKindForType(DestType)); 19047 19048 return S.MaybeBindToTemporary(E); 19049 } 19050 19051 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19052 // The only case we should ever see here is a function-to-pointer decay. 19053 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19054 assert(E->getValueKind() == VK_RValue); 19055 assert(E->getObjectKind() == OK_Ordinary); 19056 19057 E->setType(DestType); 19058 19059 // Rebuild the sub-expression as the pointee (function) type. 19060 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19061 19062 ExprResult Result = Visit(E->getSubExpr()); 19063 if (!Result.isUsable()) return ExprError(); 19064 19065 E->setSubExpr(Result.get()); 19066 return E; 19067 } else if (E->getCastKind() == CK_LValueToRValue) { 19068 assert(E->getValueKind() == VK_RValue); 19069 assert(E->getObjectKind() == OK_Ordinary); 19070 19071 assert(isa<BlockPointerType>(E->getType())); 19072 19073 E->setType(DestType); 19074 19075 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19076 DestType = S.Context.getLValueReferenceType(DestType); 19077 19078 ExprResult Result = Visit(E->getSubExpr()); 19079 if (!Result.isUsable()) return ExprError(); 19080 19081 E->setSubExpr(Result.get()); 19082 return E; 19083 } else { 19084 llvm_unreachable("Unhandled cast type!"); 19085 } 19086 } 19087 19088 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19089 ExprValueKind ValueKind = VK_LValue; 19090 QualType Type = DestType; 19091 19092 // We know how to make this work for certain kinds of decls: 19093 19094 // - functions 19095 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19096 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19097 DestType = Ptr->getPointeeType(); 19098 ExprResult Result = resolveDecl(E, VD); 19099 if (Result.isInvalid()) return ExprError(); 19100 return S.ImpCastExprToType(Result.get(), Type, 19101 CK_FunctionToPointerDecay, VK_RValue); 19102 } 19103 19104 if (!Type->isFunctionType()) { 19105 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19106 << VD << E->getSourceRange(); 19107 return ExprError(); 19108 } 19109 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19110 // We must match the FunctionDecl's type to the hack introduced in 19111 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19112 // type. See the lengthy commentary in that routine. 19113 QualType FDT = FD->getType(); 19114 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19115 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19116 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19117 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19118 SourceLocation Loc = FD->getLocation(); 19119 FunctionDecl *NewFD = FunctionDecl::Create( 19120 S.Context, FD->getDeclContext(), Loc, Loc, 19121 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19122 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19123 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19124 19125 if (FD->getQualifier()) 19126 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19127 19128 SmallVector<ParmVarDecl*, 16> Params; 19129 for (const auto &AI : FT->param_types()) { 19130 ParmVarDecl *Param = 19131 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19132 Param->setScopeInfo(0, Params.size()); 19133 Params.push_back(Param); 19134 } 19135 NewFD->setParams(Params); 19136 DRE->setDecl(NewFD); 19137 VD = DRE->getDecl(); 19138 } 19139 } 19140 19141 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19142 if (MD->isInstance()) { 19143 ValueKind = VK_RValue; 19144 Type = S.Context.BoundMemberTy; 19145 } 19146 19147 // Function references aren't l-values in C. 19148 if (!S.getLangOpts().CPlusPlus) 19149 ValueKind = VK_RValue; 19150 19151 // - variables 19152 } else if (isa<VarDecl>(VD)) { 19153 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19154 Type = RefTy->getPointeeType(); 19155 } else if (Type->isFunctionType()) { 19156 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19157 << VD << E->getSourceRange(); 19158 return ExprError(); 19159 } 19160 19161 // - nothing else 19162 } else { 19163 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19164 << VD << E->getSourceRange(); 19165 return ExprError(); 19166 } 19167 19168 // Modifying the declaration like this is friendly to IR-gen but 19169 // also really dangerous. 19170 VD->setType(DestType); 19171 E->setType(Type); 19172 E->setValueKind(ValueKind); 19173 return E; 19174 } 19175 19176 /// Check a cast of an unknown-any type. We intentionally only 19177 /// trigger this for C-style casts. 19178 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19179 Expr *CastExpr, CastKind &CastKind, 19180 ExprValueKind &VK, CXXCastPath &Path) { 19181 // The type we're casting to must be either void or complete. 19182 if (!CastType->isVoidType() && 19183 RequireCompleteType(TypeRange.getBegin(), CastType, 19184 diag::err_typecheck_cast_to_incomplete)) 19185 return ExprError(); 19186 19187 // Rewrite the casted expression from scratch. 19188 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19189 if (!result.isUsable()) return ExprError(); 19190 19191 CastExpr = result.get(); 19192 VK = CastExpr->getValueKind(); 19193 CastKind = CK_NoOp; 19194 19195 return CastExpr; 19196 } 19197 19198 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19199 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19200 } 19201 19202 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19203 Expr *arg, QualType ¶mType) { 19204 // If the syntactic form of the argument is not an explicit cast of 19205 // any sort, just do default argument promotion. 19206 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19207 if (!castArg) { 19208 ExprResult result = DefaultArgumentPromotion(arg); 19209 if (result.isInvalid()) return ExprError(); 19210 paramType = result.get()->getType(); 19211 return result; 19212 } 19213 19214 // Otherwise, use the type that was written in the explicit cast. 19215 assert(!arg->hasPlaceholderType()); 19216 paramType = castArg->getTypeAsWritten(); 19217 19218 // Copy-initialize a parameter of that type. 19219 InitializedEntity entity = 19220 InitializedEntity::InitializeParameter(Context, paramType, 19221 /*consumed*/ false); 19222 return PerformCopyInitialization(entity, callLoc, arg); 19223 } 19224 19225 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19226 Expr *orig = E; 19227 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19228 while (true) { 19229 E = E->IgnoreParenImpCasts(); 19230 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19231 E = call->getCallee(); 19232 diagID = diag::err_uncasted_call_of_unknown_any; 19233 } else { 19234 break; 19235 } 19236 } 19237 19238 SourceLocation loc; 19239 NamedDecl *d; 19240 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19241 loc = ref->getLocation(); 19242 d = ref->getDecl(); 19243 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19244 loc = mem->getMemberLoc(); 19245 d = mem->getMemberDecl(); 19246 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19247 diagID = diag::err_uncasted_call_of_unknown_any; 19248 loc = msg->getSelectorStartLoc(); 19249 d = msg->getMethodDecl(); 19250 if (!d) { 19251 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19252 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19253 << orig->getSourceRange(); 19254 return ExprError(); 19255 } 19256 } else { 19257 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19258 << E->getSourceRange(); 19259 return ExprError(); 19260 } 19261 19262 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19263 19264 // Never recoverable. 19265 return ExprError(); 19266 } 19267 19268 /// Check for operands with placeholder types and complain if found. 19269 /// Returns ExprError() if there was an error and no recovery was possible. 19270 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19271 if (!Context.isDependenceAllowed()) { 19272 // C cannot handle TypoExpr nodes on either side of a binop because it 19273 // doesn't handle dependent types properly, so make sure any TypoExprs have 19274 // been dealt with before checking the operands. 19275 ExprResult Result = CorrectDelayedTyposInExpr(E); 19276 if (!Result.isUsable()) return ExprError(); 19277 E = Result.get(); 19278 } 19279 19280 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19281 if (!placeholderType) return E; 19282 19283 switch (placeholderType->getKind()) { 19284 19285 // Overloaded expressions. 19286 case BuiltinType::Overload: { 19287 // Try to resolve a single function template specialization. 19288 // This is obligatory. 19289 ExprResult Result = E; 19290 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19291 return Result; 19292 19293 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19294 // leaves Result unchanged on failure. 19295 Result = E; 19296 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19297 return Result; 19298 19299 // If that failed, try to recover with a call. 19300 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19301 /*complain*/ true); 19302 return Result; 19303 } 19304 19305 // Bound member functions. 19306 case BuiltinType::BoundMember: { 19307 ExprResult result = E; 19308 const Expr *BME = E->IgnoreParens(); 19309 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19310 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19311 if (isa<CXXPseudoDestructorExpr>(BME)) { 19312 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19313 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19314 if (ME->getMemberNameInfo().getName().getNameKind() == 19315 DeclarationName::CXXDestructorName) 19316 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19317 } 19318 tryToRecoverWithCall(result, PD, 19319 /*complain*/ true); 19320 return result; 19321 } 19322 19323 // ARC unbridged casts. 19324 case BuiltinType::ARCUnbridgedCast: { 19325 Expr *realCast = stripARCUnbridgedCast(E); 19326 diagnoseARCUnbridgedCast(realCast); 19327 return realCast; 19328 } 19329 19330 // Expressions of unknown type. 19331 case BuiltinType::UnknownAny: 19332 return diagnoseUnknownAnyExpr(*this, E); 19333 19334 // Pseudo-objects. 19335 case BuiltinType::PseudoObject: 19336 return checkPseudoObjectRValue(E); 19337 19338 case BuiltinType::BuiltinFn: { 19339 // Accept __noop without parens by implicitly converting it to a call expr. 19340 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19341 if (DRE) { 19342 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19343 if (FD->getBuiltinID() == Builtin::BI__noop) { 19344 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19345 CK_BuiltinFnToFnPtr) 19346 .get(); 19347 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19348 VK_RValue, SourceLocation(), 19349 FPOptionsOverride()); 19350 } 19351 } 19352 19353 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19354 return ExprError(); 19355 } 19356 19357 case BuiltinType::IncompleteMatrixIdx: 19358 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19359 ->getRowIdx() 19360 ->getBeginLoc(), 19361 diag::err_matrix_incomplete_index); 19362 return ExprError(); 19363 19364 // Expressions of unknown type. 19365 case BuiltinType::OMPArraySection: 19366 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19367 return ExprError(); 19368 19369 // Expressions of unknown type. 19370 case BuiltinType::OMPArrayShaping: 19371 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19372 19373 case BuiltinType::OMPIterator: 19374 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19375 19376 // Everything else should be impossible. 19377 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19378 case BuiltinType::Id: 19379 #include "clang/Basic/OpenCLImageTypes.def" 19380 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19381 case BuiltinType::Id: 19382 #include "clang/Basic/OpenCLExtensionTypes.def" 19383 #define SVE_TYPE(Name, Id, SingletonId) \ 19384 case BuiltinType::Id: 19385 #include "clang/Basic/AArch64SVEACLETypes.def" 19386 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19387 case BuiltinType::Id: 19388 #include "clang/Basic/PPCTypes.def" 19389 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19390 #include "clang/Basic/RISCVVTypes.def" 19391 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19392 #define PLACEHOLDER_TYPE(Id, SingletonId) 19393 #include "clang/AST/BuiltinTypes.def" 19394 break; 19395 } 19396 19397 llvm_unreachable("invalid placeholder type!"); 19398 } 19399 19400 bool Sema::CheckCaseExpression(Expr *E) { 19401 if (E->isTypeDependent()) 19402 return true; 19403 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19404 return E->getType()->isIntegralOrEnumerationType(); 19405 return false; 19406 } 19407 19408 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19409 ExprResult 19410 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19411 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19412 "Unknown Objective-C Boolean value!"); 19413 QualType BoolT = Context.ObjCBuiltinBoolTy; 19414 if (!Context.getBOOLDecl()) { 19415 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19416 Sema::LookupOrdinaryName); 19417 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19418 NamedDecl *ND = Result.getFoundDecl(); 19419 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19420 Context.setBOOLDecl(TD); 19421 } 19422 } 19423 if (Context.getBOOLDecl()) 19424 BoolT = Context.getBOOLType(); 19425 return new (Context) 19426 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19427 } 19428 19429 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19430 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19431 SourceLocation RParen) { 19432 19433 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19434 19435 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19436 return Spec.getPlatform() == Platform; 19437 }); 19438 19439 VersionTuple Version; 19440 if (Spec != AvailSpecs.end()) 19441 Version = Spec->getVersion(); 19442 19443 // The use of `@available` in the enclosing function should be analyzed to 19444 // warn when it's used inappropriately (i.e. not if(@available)). 19445 if (getCurFunctionOrMethodDecl()) 19446 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19447 else if (getCurBlock() || getCurLambda()) 19448 getCurFunction()->HasPotentialAvailabilityViolations = true; 19449 19450 return new (Context) 19451 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19452 } 19453 19454 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19455 ArrayRef<Expr *> SubExprs, QualType T) { 19456 if (!Context.getLangOpts().RecoveryAST) 19457 return ExprError(); 19458 19459 if (isSFINAEContext()) 19460 return ExprError(); 19461 19462 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19463 // We don't know the concrete type, fallback to dependent type. 19464 T = Context.DependentTy; 19465 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19466 } 19467