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/ADT/STLExtras.h" 50 #include "llvm/Support/ConvertUTF.h" 51 #include "llvm/Support/SaveAndRestore.h" 52 using namespace clang; 53 using namespace sema; 54 using llvm::RoundingMode; 55 56 /// Determine whether the use of this declaration is valid, without 57 /// emitting diagnostics. 58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 59 // See if this is an auto-typed variable whose initializer we are parsing. 60 if (ParsingInitForAutoVars.count(D)) 61 return false; 62 63 // See if this is a deleted function. 64 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 65 if (FD->isDeleted()) 66 return false; 67 68 // If the function has a deduced return type, and we can't deduce it, 69 // then we can't use it either. 70 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 71 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 72 return false; 73 74 // See if this is an aligned allocation/deallocation function that is 75 // unavailable. 76 if (TreatUnavailableAsInvalid && 77 isUnavailableAlignedAllocationFunction(*FD)) 78 return false; 79 } 80 81 // See if this function is unavailable. 82 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 83 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 84 return false; 85 86 return true; 87 } 88 89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 90 // Warn if this is used but marked unused. 91 if (const auto *A = D->getAttr<UnusedAttr>()) { 92 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 93 // should diagnose them. 94 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 95 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 96 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 97 if (DC && !DC->hasAttr<UnusedAttr>()) 98 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 99 } 100 } 101 } 102 103 /// Emit a note explaining that this function is deleted. 104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 105 assert(Decl && Decl->isDeleted()); 106 107 if (Decl->isDefaulted()) { 108 // If the method was explicitly defaulted, point at that declaration. 109 if (!Decl->isImplicit()) 110 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 111 112 // Try to diagnose why this special member function was implicitly 113 // deleted. This might fail, if that reason no longer applies. 114 DiagnoseDeletedDefaultedFunction(Decl); 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 253 // See if this is a deleted function. 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // [expr.prim.id]p4 267 // A program that refers explicitly or implicitly to a function with a 268 // trailing requires-clause whose constraint-expression is not satisfied, 269 // other than to declare it, is ill-formed. [...] 270 // 271 // See if this is a function with constraints that need to be satisfied. 272 // Check this before deducing the return type, as it might instantiate the 273 // definition. 274 if (FD->getTrailingRequiresClause()) { 275 ConstraintSatisfaction Satisfaction; 276 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 277 // A diagnostic will have already been generated (non-constant 278 // constraint expression, for example) 279 return true; 280 if (!Satisfaction.IsSatisfied) { 281 Diag(Loc, 282 diag::err_reference_to_function_with_unsatisfied_constraints) 283 << D; 284 DiagnoseUnsatisfiedConstraint(Satisfaction); 285 return true; 286 } 287 } 288 289 // If the function has a deduced return type, and we can't deduce it, 290 // then we can't use it either. 291 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 292 DeduceReturnType(FD, Loc)) 293 return true; 294 295 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 296 return true; 297 298 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 299 return true; 300 } 301 302 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 303 // Lambdas are only default-constructible or assignable in C++2a onwards. 304 if (MD->getParent()->isLambda() && 305 ((isa<CXXConstructorDecl>(MD) && 306 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 307 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 308 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 309 << !isa<CXXConstructorDecl>(MD); 310 } 311 } 312 313 auto getReferencedObjCProp = [](const NamedDecl *D) -> 314 const ObjCPropertyDecl * { 315 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 316 return MD->findPropertyDecl(); 317 return nullptr; 318 }; 319 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 320 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 321 return true; 322 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 323 return true; 324 } 325 326 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 327 // Only the variables omp_in and omp_out are allowed in the combiner. 328 // Only the variables omp_priv and omp_orig are allowed in the 329 // initializer-clause. 330 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 331 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 332 isa<VarDecl>(D)) { 333 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 334 << getCurFunction()->HasOMPDeclareReductionCombiner; 335 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 336 return true; 337 } 338 339 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 340 // List-items in map clauses on this construct may only refer to the declared 341 // variable var and entities that could be referenced by a procedure defined 342 // at the same location 343 if (LangOpts.OpenMP && isa<VarDecl>(D) && 344 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << getOpenMPDeclareMapperVarName(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 // CUDA/HIP: Diagnose invalid references of host global variables in device 359 // functions. Reference of device global variables in host functions is 360 // allowed through shadow variables therefore it is not diagnosed. 361 if (LangOpts.CUDAIsDevice) { 362 auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext); 363 auto Target = IdentifyCUDATarget(FD); 364 if (FD && Target != CFT_Host) { 365 const auto *VD = dyn_cast<VarDecl>(D); 366 if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() && 367 !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() && 368 !VD->getType()->isCUDADeviceBuiltinSurfaceType() && 369 !VD->getType()->isCUDADeviceBuiltinTextureType() && 370 !VD->isConstexpr() && !VD->getType().isConstQualified()) 371 targetDiag(*Locs.begin(), diag::err_ref_bad_target) 372 << /*host*/ 2 << /*variable*/ 1 << VD << Target; 373 } 374 } 375 376 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 377 if (auto *VD = dyn_cast<ValueDecl>(D)) 378 checkDeviceDecl(VD, Loc); 379 380 if (!Context.getTargetInfo().isTLSSupported()) 381 if (const auto *VD = dyn_cast<VarDecl>(D)) 382 if (VD->getTLSKind() != VarDecl::TLS_None) 383 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 384 } 385 386 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 387 !isUnevaluatedContext()) { 388 // C++ [expr.prim.req.nested] p3 389 // A local parameter shall only appear as an unevaluated operand 390 // (Clause 8) within the constraint-expression. 391 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 392 << D; 393 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 394 return true; 395 } 396 397 return false; 398 } 399 400 /// DiagnoseSentinelCalls - This routine checks whether a call or 401 /// message-send is to a declaration with the sentinel attribute, and 402 /// if so, it checks that the requirements of the sentinel are 403 /// satisfied. 404 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 405 ArrayRef<Expr *> Args) { 406 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 407 if (!attr) 408 return; 409 410 // The number of formal parameters of the declaration. 411 unsigned numFormalParams; 412 413 // The kind of declaration. This is also an index into a %select in 414 // the diagnostic. 415 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 416 417 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 418 numFormalParams = MD->param_size(); 419 calleeType = CT_Method; 420 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 421 numFormalParams = FD->param_size(); 422 calleeType = CT_Function; 423 } else if (isa<VarDecl>(D)) { 424 QualType type = cast<ValueDecl>(D)->getType(); 425 const FunctionType *fn = nullptr; 426 if (const PointerType *ptr = type->getAs<PointerType>()) { 427 fn = ptr->getPointeeType()->getAs<FunctionType>(); 428 if (!fn) return; 429 calleeType = CT_Function; 430 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 431 fn = ptr->getPointeeType()->castAs<FunctionType>(); 432 calleeType = CT_Block; 433 } else { 434 return; 435 } 436 437 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 438 numFormalParams = proto->getNumParams(); 439 } else { 440 numFormalParams = 0; 441 } 442 } else { 443 return; 444 } 445 446 // "nullPos" is the number of formal parameters at the end which 447 // effectively count as part of the variadic arguments. This is 448 // useful if you would prefer to not have *any* formal parameters, 449 // but the language forces you to have at least one. 450 unsigned nullPos = attr->getNullPos(); 451 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 452 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 453 454 // The number of arguments which should follow the sentinel. 455 unsigned numArgsAfterSentinel = attr->getSentinel(); 456 457 // If there aren't enough arguments for all the formal parameters, 458 // the sentinel, and the args after the sentinel, complain. 459 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 460 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 461 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 462 return; 463 } 464 465 // Otherwise, find the sentinel expression. 466 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 467 if (!sentinelExpr) return; 468 if (sentinelExpr->isValueDependent()) return; 469 if (Context.isSentinelNullExpr(sentinelExpr)) return; 470 471 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 472 // or 'NULL' if those are actually defined in the context. Only use 473 // 'nil' for ObjC methods, where it's much more likely that the 474 // variadic arguments form a list of object pointers. 475 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 476 std::string NullValue; 477 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 478 NullValue = "nil"; 479 else if (getLangOpts().CPlusPlus11) 480 NullValue = "nullptr"; 481 else if (PP.isMacroDefined("NULL")) 482 NullValue = "NULL"; 483 else 484 NullValue = "(void*) 0"; 485 486 if (MissingNilLoc.isInvalid()) 487 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 488 else 489 Diag(MissingNilLoc, diag::warn_missing_sentinel) 490 << int(calleeType) 491 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 492 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 493 } 494 495 SourceRange Sema::getExprRange(Expr *E) const { 496 return E ? E->getSourceRange() : SourceRange(); 497 } 498 499 //===----------------------------------------------------------------------===// 500 // Standard Promotions and Conversions 501 //===----------------------------------------------------------------------===// 502 503 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 504 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 505 // Handle any placeholder expressions which made it here. 506 if (E->getType()->isPlaceholderType()) { 507 ExprResult result = CheckPlaceholderExpr(E); 508 if (result.isInvalid()) return ExprError(); 509 E = result.get(); 510 } 511 512 QualType Ty = E->getType(); 513 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 514 515 if (Ty->isFunctionType()) { 516 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 517 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 518 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 519 return ExprError(); 520 521 E = ImpCastExprToType(E, Context.getPointerType(Ty), 522 CK_FunctionToPointerDecay).get(); 523 } else if (Ty->isArrayType()) { 524 // In C90 mode, arrays only promote to pointers if the array expression is 525 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 526 // type 'array of type' is converted to an expression that has type 'pointer 527 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 528 // that has type 'array of type' ...". The relevant change is "an lvalue" 529 // (C90) to "an expression" (C99). 530 // 531 // C++ 4.2p1: 532 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 533 // T" can be converted to an rvalue of type "pointer to T". 534 // 535 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 536 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 537 CK_ArrayToPointerDecay).get(); 538 } 539 return E; 540 } 541 542 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 543 // Check to see if we are dereferencing a null pointer. If so, 544 // and if not volatile-qualified, this is undefined behavior that the 545 // optimizer will delete, so warn about it. People sometimes try to use this 546 // to get a deterministic trap and are surprised by clang's behavior. This 547 // only handles the pattern "*null", which is a very syntactic check. 548 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 549 if (UO && UO->getOpcode() == UO_Deref && 550 UO->getSubExpr()->getType()->isPointerType()) { 551 const LangAS AS = 552 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 553 if ((!isTargetAddressSpace(AS) || 554 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 555 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 556 S.Context, Expr::NPC_ValueDependentIsNotNull) && 557 !UO->getType().isVolatileQualified()) { 558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 559 S.PDiag(diag::warn_indirection_through_null) 560 << UO->getSubExpr()->getSourceRange()); 561 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 562 S.PDiag(diag::note_indirection_through_null)); 563 } 564 } 565 } 566 567 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 568 SourceLocation AssignLoc, 569 const Expr* RHS) { 570 const ObjCIvarDecl *IV = OIRE->getDecl(); 571 if (!IV) 572 return; 573 574 DeclarationName MemberName = IV->getDeclName(); 575 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 576 if (!Member || !Member->isStr("isa")) 577 return; 578 579 const Expr *Base = OIRE->getBase(); 580 QualType BaseType = Base->getType(); 581 if (OIRE->isArrow()) 582 BaseType = BaseType->getPointeeType(); 583 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 584 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 585 ObjCInterfaceDecl *ClassDeclared = nullptr; 586 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 587 if (!ClassDeclared->getSuperClass() 588 && (*ClassDeclared->ivar_begin()) == IV) { 589 if (RHS) { 590 NamedDecl *ObjectSetClass = 591 S.LookupSingleName(S.TUScope, 592 &S.Context.Idents.get("object_setClass"), 593 SourceLocation(), S.LookupOrdinaryName); 594 if (ObjectSetClass) { 595 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 596 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 597 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 598 "object_setClass(") 599 << FixItHint::CreateReplacement( 600 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 601 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 602 } 603 else 604 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 605 } else { 606 NamedDecl *ObjectGetClass = 607 S.LookupSingleName(S.TUScope, 608 &S.Context.Idents.get("object_getClass"), 609 SourceLocation(), S.LookupOrdinaryName); 610 if (ObjectGetClass) 611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 612 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 613 "object_getClass(") 614 << FixItHint::CreateReplacement( 615 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 616 else 617 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 618 } 619 S.Diag(IV->getLocation(), diag::note_ivar_decl); 620 } 621 } 622 } 623 624 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 625 // Handle any placeholder expressions which made it here. 626 if (E->getType()->isPlaceholderType()) { 627 ExprResult result = CheckPlaceholderExpr(E); 628 if (result.isInvalid()) return ExprError(); 629 E = result.get(); 630 } 631 632 // C++ [conv.lval]p1: 633 // A glvalue of a non-function, non-array type T can be 634 // converted to a prvalue. 635 if (!E->isGLValue()) return E; 636 637 QualType T = E->getType(); 638 assert(!T.isNull() && "r-value conversion on typeless expression?"); 639 640 // lvalue-to-rvalue conversion cannot be applied to function or array types. 641 if (T->isFunctionType() || T->isArrayType()) 642 return E; 643 644 // We don't want to throw lvalue-to-rvalue casts on top of 645 // expressions of certain types in C++. 646 if (getLangOpts().CPlusPlus && 647 (E->getType() == Context.OverloadTy || 648 T->isDependentType() || 649 T->isRecordType())) 650 return E; 651 652 // The C standard is actually really unclear on this point, and 653 // DR106 tells us what the result should be but not why. It's 654 // generally best to say that void types just doesn't undergo 655 // lvalue-to-rvalue at all. Note that expressions of unqualified 656 // 'void' type are never l-values, but qualified void can be. 657 if (T->isVoidType()) 658 return E; 659 660 // OpenCL usually rejects direct accesses to values of 'half' type. 661 if (getLangOpts().OpenCL && 662 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 663 T->isHalfType()) { 664 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 665 << 0 << T; 666 return ExprError(); 667 } 668 669 CheckForNullPointerDereference(*this, E); 670 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 671 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 672 &Context.Idents.get("object_getClass"), 673 SourceLocation(), LookupOrdinaryName); 674 if (ObjectGetClass) 675 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 676 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 677 << FixItHint::CreateReplacement( 678 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 679 else 680 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 681 } 682 else if (const ObjCIvarRefExpr *OIRE = 683 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 684 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 685 686 // C++ [conv.lval]p1: 687 // [...] If T is a non-class type, the type of the prvalue is the 688 // cv-unqualified version of T. Otherwise, the type of the 689 // rvalue is T. 690 // 691 // C99 6.3.2.1p2: 692 // If the lvalue has qualified type, the value has the unqualified 693 // version of the type of the lvalue; otherwise, the value has the 694 // type of the lvalue. 695 if (T.hasQualifiers()) 696 T = T.getUnqualifiedType(); 697 698 // Under the MS ABI, lock down the inheritance model now. 699 if (T->isMemberPointerType() && 700 Context.getTargetInfo().getCXXABI().isMicrosoft()) 701 (void)isCompleteType(E->getExprLoc(), T); 702 703 ExprResult Res = CheckLValueToRValueConversionOperand(E); 704 if (Res.isInvalid()) 705 return Res; 706 E = Res.get(); 707 708 // Loading a __weak object implicitly retains the value, so we need a cleanup to 709 // balance that. 710 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 711 Cleanup.setExprNeedsCleanups(true); 712 713 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 714 Cleanup.setExprNeedsCleanups(true); 715 716 // C++ [conv.lval]p3: 717 // If T is cv std::nullptr_t, the result is a null pointer constant. 718 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 719 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 720 CurFPFeatureOverrides()); 721 722 // C11 6.3.2.1p2: 723 // ... if the lvalue has atomic type, the value has the non-atomic version 724 // of the type of the lvalue ... 725 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 726 T = Atomic->getValueType().getUnqualifiedType(); 727 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 728 nullptr, VK_RValue, FPOptionsOverride()); 729 } 730 731 return Res; 732 } 733 734 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 735 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 736 if (Res.isInvalid()) 737 return ExprError(); 738 Res = DefaultLvalueConversion(Res.get()); 739 if (Res.isInvalid()) 740 return ExprError(); 741 return Res; 742 } 743 744 /// CallExprUnaryConversions - a special case of an unary conversion 745 /// performed on a function designator of a call expression. 746 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 747 QualType Ty = E->getType(); 748 ExprResult Res = E; 749 // Only do implicit cast for a function type, but not for a pointer 750 // to function type. 751 if (Ty->isFunctionType()) { 752 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 753 CK_FunctionToPointerDecay); 754 if (Res.isInvalid()) 755 return ExprError(); 756 } 757 Res = DefaultLvalueConversion(Res.get()); 758 if (Res.isInvalid()) 759 return ExprError(); 760 return Res.get(); 761 } 762 763 /// UsualUnaryConversions - Performs various conversions that are common to most 764 /// operators (C99 6.3). The conversions of array and function types are 765 /// sometimes suppressed. For example, the array->pointer conversion doesn't 766 /// apply if the array is an argument to the sizeof or address (&) operators. 767 /// In these instances, this routine should *not* be called. 768 ExprResult Sema::UsualUnaryConversions(Expr *E) { 769 // First, convert to an r-value. 770 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 771 if (Res.isInvalid()) 772 return ExprError(); 773 E = Res.get(); 774 775 QualType Ty = E->getType(); 776 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 777 778 // Half FP have to be promoted to float unless it is natively supported 779 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 780 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 781 782 // Try to perform integral promotions if the object has a theoretically 783 // promotable type. 784 if (Ty->isIntegralOrUnscopedEnumerationType()) { 785 // C99 6.3.1.1p2: 786 // 787 // The following may be used in an expression wherever an int or 788 // unsigned int may be used: 789 // - an object or expression with an integer type whose integer 790 // conversion rank is less than or equal to the rank of int 791 // and unsigned int. 792 // - A bit-field of type _Bool, int, signed int, or unsigned int. 793 // 794 // If an int can represent all values of the original type, the 795 // value is converted to an int; otherwise, it is converted to an 796 // unsigned int. These are called the integer promotions. All 797 // other types are unchanged by the integer promotions. 798 799 QualType PTy = Context.isPromotableBitField(E); 800 if (!PTy.isNull()) { 801 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 802 return E; 803 } 804 if (Ty->isPromotableIntegerType()) { 805 QualType PT = Context.getPromotedIntegerType(Ty); 806 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 807 return E; 808 } 809 } 810 return E; 811 } 812 813 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 814 /// do not have a prototype. Arguments that have type float or __fp16 815 /// are promoted to double. All other argument types are converted by 816 /// UsualUnaryConversions(). 817 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 818 QualType Ty = E->getType(); 819 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 820 821 ExprResult Res = UsualUnaryConversions(E); 822 if (Res.isInvalid()) 823 return ExprError(); 824 E = Res.get(); 825 826 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 827 // promote to double. 828 // Note that default argument promotion applies only to float (and 829 // half/fp16); it does not apply to _Float16. 830 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 831 if (BTy && (BTy->getKind() == BuiltinType::Half || 832 BTy->getKind() == BuiltinType::Float)) { 833 if (getLangOpts().OpenCL && 834 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 835 if (BTy->getKind() == BuiltinType::Half) { 836 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 837 } 838 } else { 839 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 840 } 841 } 842 843 // C++ performs lvalue-to-rvalue conversion as a default argument 844 // promotion, even on class types, but note: 845 // C++11 [conv.lval]p2: 846 // When an lvalue-to-rvalue conversion occurs in an unevaluated 847 // operand or a subexpression thereof the value contained in the 848 // referenced object is not accessed. Otherwise, if the glvalue 849 // has a class type, the conversion copy-initializes a temporary 850 // of type T from the glvalue and the result of the conversion 851 // is a prvalue for the temporary. 852 // FIXME: add some way to gate this entire thing for correctness in 853 // potentially potentially evaluated contexts. 854 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 855 ExprResult Temp = PerformCopyInitialization( 856 InitializedEntity::InitializeTemporary(E->getType()), 857 E->getExprLoc(), E); 858 if (Temp.isInvalid()) 859 return ExprError(); 860 E = Temp.get(); 861 } 862 863 return E; 864 } 865 866 /// Determine the degree of POD-ness for an expression. 867 /// Incomplete types are considered POD, since this check can be performed 868 /// when we're in an unevaluated context. 869 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 870 if (Ty->isIncompleteType()) { 871 // C++11 [expr.call]p7: 872 // After these conversions, if the argument does not have arithmetic, 873 // enumeration, pointer, pointer to member, or class type, the program 874 // is ill-formed. 875 // 876 // Since we've already performed array-to-pointer and function-to-pointer 877 // decay, the only such type in C++ is cv void. This also handles 878 // initializer lists as variadic arguments. 879 if (Ty->isVoidType()) 880 return VAK_Invalid; 881 882 if (Ty->isObjCObjectType()) 883 return VAK_Invalid; 884 return VAK_Valid; 885 } 886 887 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 888 return VAK_Invalid; 889 890 if (Ty.isCXX98PODType(Context)) 891 return VAK_Valid; 892 893 // C++11 [expr.call]p7: 894 // Passing a potentially-evaluated argument of class type (Clause 9) 895 // having a non-trivial copy constructor, a non-trivial move constructor, 896 // or a non-trivial destructor, with no corresponding parameter, 897 // is conditionally-supported with implementation-defined semantics. 898 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 899 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 900 if (!Record->hasNonTrivialCopyConstructor() && 901 !Record->hasNonTrivialMoveConstructor() && 902 !Record->hasNonTrivialDestructor()) 903 return VAK_ValidInCXX11; 904 905 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 906 return VAK_Valid; 907 908 if (Ty->isObjCObjectType()) 909 return VAK_Invalid; 910 911 if (getLangOpts().MSVCCompat) 912 return VAK_MSVCUndefined; 913 914 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 915 // permitted to reject them. We should consider doing so. 916 return VAK_Undefined; 917 } 918 919 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 920 // Don't allow one to pass an Objective-C interface to a vararg. 921 const QualType &Ty = E->getType(); 922 VarArgKind VAK = isValidVarArgType(Ty); 923 924 // Complain about passing non-POD types through varargs. 925 switch (VAK) { 926 case VAK_ValidInCXX11: 927 DiagRuntimeBehavior( 928 E->getBeginLoc(), nullptr, 929 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 930 LLVM_FALLTHROUGH; 931 case VAK_Valid: 932 if (Ty->isRecordType()) { 933 // This is unlikely to be what the user intended. If the class has a 934 // 'c_str' member function, the user probably meant to call that. 935 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 936 PDiag(diag::warn_pass_class_arg_to_vararg) 937 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 938 } 939 break; 940 941 case VAK_Undefined: 942 case VAK_MSVCUndefined: 943 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 944 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 945 << getLangOpts().CPlusPlus11 << Ty << CT); 946 break; 947 948 case VAK_Invalid: 949 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 950 Diag(E->getBeginLoc(), 951 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 952 << Ty << CT; 953 else if (Ty->isObjCObjectType()) 954 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 955 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 956 << Ty << CT); 957 else 958 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 959 << isa<InitListExpr>(E) << Ty << CT; 960 break; 961 } 962 } 963 964 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 965 /// will create a trap if the resulting type is not a POD type. 966 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 967 FunctionDecl *FDecl) { 968 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 969 // Strip the unbridged-cast placeholder expression off, if applicable. 970 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 971 (CT == VariadicMethod || 972 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 973 E = stripARCUnbridgedCast(E); 974 975 // Otherwise, do normal placeholder checking. 976 } else { 977 ExprResult ExprRes = CheckPlaceholderExpr(E); 978 if (ExprRes.isInvalid()) 979 return ExprError(); 980 E = ExprRes.get(); 981 } 982 } 983 984 ExprResult ExprRes = DefaultArgumentPromotion(E); 985 if (ExprRes.isInvalid()) 986 return ExprError(); 987 988 // Copy blocks to the heap. 989 if (ExprRes.get()->getType()->isBlockPointerType()) 990 maybeExtendBlockObject(ExprRes); 991 992 E = ExprRes.get(); 993 994 // Diagnostics regarding non-POD argument types are 995 // emitted along with format string checking in Sema::CheckFunctionCall(). 996 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 997 // Turn this into a trap. 998 CXXScopeSpec SS; 999 SourceLocation TemplateKWLoc; 1000 UnqualifiedId Name; 1001 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1002 E->getBeginLoc()); 1003 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1004 /*HasTrailingLParen=*/true, 1005 /*IsAddressOfOperand=*/false); 1006 if (TrapFn.isInvalid()) 1007 return ExprError(); 1008 1009 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1010 None, E->getEndLoc()); 1011 if (Call.isInvalid()) 1012 return ExprError(); 1013 1014 ExprResult Comma = 1015 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1016 if (Comma.isInvalid()) 1017 return ExprError(); 1018 return Comma.get(); 1019 } 1020 1021 if (!getLangOpts().CPlusPlus && 1022 RequireCompleteType(E->getExprLoc(), E->getType(), 1023 diag::err_call_incomplete_argument)) 1024 return ExprError(); 1025 1026 return E; 1027 } 1028 1029 /// Converts an integer to complex float type. Helper function of 1030 /// UsualArithmeticConversions() 1031 /// 1032 /// \return false if the integer expression is an integer type and is 1033 /// successfully converted to the complex type. 1034 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1035 ExprResult &ComplexExpr, 1036 QualType IntTy, 1037 QualType ComplexTy, 1038 bool SkipCast) { 1039 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1040 if (SkipCast) return false; 1041 if (IntTy->isIntegerType()) { 1042 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1043 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1044 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1045 CK_FloatingRealToComplex); 1046 } else { 1047 assert(IntTy->isComplexIntegerType()); 1048 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1049 CK_IntegralComplexToFloatingComplex); 1050 } 1051 return false; 1052 } 1053 1054 /// Handle arithmetic conversion with complex types. Helper function of 1055 /// UsualArithmeticConversions() 1056 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1057 ExprResult &RHS, QualType LHSType, 1058 QualType RHSType, 1059 bool IsCompAssign) { 1060 // if we have an integer operand, the result is the complex type. 1061 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1062 /*skipCast*/false)) 1063 return LHSType; 1064 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1065 /*skipCast*/IsCompAssign)) 1066 return RHSType; 1067 1068 // This handles complex/complex, complex/float, or float/complex. 1069 // When both operands are complex, the shorter operand is converted to the 1070 // type of the longer, and that is the type of the result. This corresponds 1071 // to what is done when combining two real floating-point operands. 1072 // The fun begins when size promotion occur across type domains. 1073 // From H&S 6.3.4: When one operand is complex and the other is a real 1074 // floating-point type, the less precise type is converted, within it's 1075 // real or complex domain, to the precision of the other type. For example, 1076 // when combining a "long double" with a "double _Complex", the 1077 // "double _Complex" is promoted to "long double _Complex". 1078 1079 // Compute the rank of the two types, regardless of whether they are complex. 1080 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1081 1082 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1083 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1084 QualType LHSElementType = 1085 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1086 QualType RHSElementType = 1087 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1088 1089 QualType ResultType = S.Context.getComplexType(LHSElementType); 1090 if (Order < 0) { 1091 // Promote the precision of the LHS if not an assignment. 1092 ResultType = S.Context.getComplexType(RHSElementType); 1093 if (!IsCompAssign) { 1094 if (LHSComplexType) 1095 LHS = 1096 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1097 else 1098 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1099 } 1100 } else if (Order > 0) { 1101 // Promote the precision of the RHS. 1102 if (RHSComplexType) 1103 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1104 else 1105 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1106 } 1107 return ResultType; 1108 } 1109 1110 /// Handle arithmetic conversion from integer to float. Helper function 1111 /// of UsualArithmeticConversions() 1112 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1113 ExprResult &IntExpr, 1114 QualType FloatTy, QualType IntTy, 1115 bool ConvertFloat, bool ConvertInt) { 1116 if (IntTy->isIntegerType()) { 1117 if (ConvertInt) 1118 // Convert intExpr to the lhs floating point type. 1119 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1120 CK_IntegralToFloating); 1121 return FloatTy; 1122 } 1123 1124 // Convert both sides to the appropriate complex float. 1125 assert(IntTy->isComplexIntegerType()); 1126 QualType result = S.Context.getComplexType(FloatTy); 1127 1128 // _Complex int -> _Complex float 1129 if (ConvertInt) 1130 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1131 CK_IntegralComplexToFloatingComplex); 1132 1133 // float -> _Complex float 1134 if (ConvertFloat) 1135 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1136 CK_FloatingRealToComplex); 1137 1138 return result; 1139 } 1140 1141 /// Handle arithmethic conversion with floating point types. Helper 1142 /// function of UsualArithmeticConversions() 1143 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1144 ExprResult &RHS, QualType LHSType, 1145 QualType RHSType, bool IsCompAssign) { 1146 bool LHSFloat = LHSType->isRealFloatingType(); 1147 bool RHSFloat = RHSType->isRealFloatingType(); 1148 1149 // N1169 4.1.4: If one of the operands has a floating type and the other 1150 // operand has a fixed-point type, the fixed-point operand 1151 // is converted to the floating type [...] 1152 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1153 if (LHSFloat) 1154 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1155 else if (!IsCompAssign) 1156 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1157 return LHSFloat ? LHSType : RHSType; 1158 } 1159 1160 // If we have two real floating types, convert the smaller operand 1161 // to the bigger result. 1162 if (LHSFloat && RHSFloat) { 1163 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1164 if (order > 0) { 1165 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1166 return LHSType; 1167 } 1168 1169 assert(order < 0 && "illegal float comparison"); 1170 if (!IsCompAssign) 1171 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1172 return RHSType; 1173 } 1174 1175 if (LHSFloat) { 1176 // Half FP has to be promoted to float unless it is natively supported 1177 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1178 LHSType = S.Context.FloatTy; 1179 1180 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1181 /*ConvertFloat=*/!IsCompAssign, 1182 /*ConvertInt=*/ true); 1183 } 1184 assert(RHSFloat); 1185 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1186 /*ConvertFloat=*/ true, 1187 /*ConvertInt=*/!IsCompAssign); 1188 } 1189 1190 /// Diagnose attempts to convert between __float128 and long double if 1191 /// there is no support for such conversion. Helper function of 1192 /// UsualArithmeticConversions(). 1193 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1194 QualType RHSType) { 1195 /* No issue converting if at least one of the types is not a floating point 1196 type or the two types have the same rank. 1197 */ 1198 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1199 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1200 return false; 1201 1202 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1203 "The remaining types must be floating point types."); 1204 1205 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1206 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1207 1208 QualType LHSElemType = LHSComplex ? 1209 LHSComplex->getElementType() : LHSType; 1210 QualType RHSElemType = RHSComplex ? 1211 RHSComplex->getElementType() : RHSType; 1212 1213 // No issue if the two types have the same representation 1214 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1215 &S.Context.getFloatTypeSemantics(RHSElemType)) 1216 return false; 1217 1218 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1219 RHSElemType == S.Context.LongDoubleTy); 1220 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1221 RHSElemType == S.Context.Float128Ty); 1222 1223 // We've handled the situation where __float128 and long double have the same 1224 // representation. We allow all conversions for all possible long double types 1225 // except PPC's double double. 1226 return Float128AndLongDouble && 1227 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1228 &llvm::APFloat::PPCDoubleDouble()); 1229 } 1230 1231 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1232 1233 namespace { 1234 /// These helper callbacks are placed in an anonymous namespace to 1235 /// permit their use as function template parameters. 1236 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1237 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1238 } 1239 1240 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1241 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1242 CK_IntegralComplexCast); 1243 } 1244 } 1245 1246 /// Handle integer arithmetic conversions. Helper function of 1247 /// UsualArithmeticConversions() 1248 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1249 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1250 ExprResult &RHS, QualType LHSType, 1251 QualType RHSType, bool IsCompAssign) { 1252 // The rules for this case are in C99 6.3.1.8 1253 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1254 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1255 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1256 if (LHSSigned == RHSSigned) { 1257 // Same signedness; use the higher-ranked type 1258 if (order >= 0) { 1259 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1260 return LHSType; 1261 } else if (!IsCompAssign) 1262 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1263 return RHSType; 1264 } else if (order != (LHSSigned ? 1 : -1)) { 1265 // The unsigned type has greater than or equal rank to the 1266 // signed type, so use the unsigned type 1267 if (RHSSigned) { 1268 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1269 return LHSType; 1270 } else if (!IsCompAssign) 1271 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1272 return RHSType; 1273 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1274 // The two types are different widths; if we are here, that 1275 // means the signed type is larger than the unsigned type, so 1276 // use the signed type. 1277 if (LHSSigned) { 1278 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1279 return LHSType; 1280 } else if (!IsCompAssign) 1281 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1282 return RHSType; 1283 } else { 1284 // The signed type is higher-ranked than the unsigned type, 1285 // but isn't actually any bigger (like unsigned int and long 1286 // on most 32-bit systems). Use the unsigned type corresponding 1287 // to the signed type. 1288 QualType result = 1289 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1290 RHS = (*doRHSCast)(S, RHS.get(), result); 1291 if (!IsCompAssign) 1292 LHS = (*doLHSCast)(S, LHS.get(), result); 1293 return result; 1294 } 1295 } 1296 1297 /// Handle conversions with GCC complex int extension. Helper function 1298 /// of UsualArithmeticConversions() 1299 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1300 ExprResult &RHS, QualType LHSType, 1301 QualType RHSType, 1302 bool IsCompAssign) { 1303 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1304 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1305 1306 if (LHSComplexInt && RHSComplexInt) { 1307 QualType LHSEltType = LHSComplexInt->getElementType(); 1308 QualType RHSEltType = RHSComplexInt->getElementType(); 1309 QualType ScalarType = 1310 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1311 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1312 1313 return S.Context.getComplexType(ScalarType); 1314 } 1315 1316 if (LHSComplexInt) { 1317 QualType LHSEltType = LHSComplexInt->getElementType(); 1318 QualType ScalarType = 1319 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1320 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1321 QualType ComplexType = S.Context.getComplexType(ScalarType); 1322 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1323 CK_IntegralRealToComplex); 1324 1325 return ComplexType; 1326 } 1327 1328 assert(RHSComplexInt); 1329 1330 QualType RHSEltType = RHSComplexInt->getElementType(); 1331 QualType ScalarType = 1332 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1333 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1334 QualType ComplexType = S.Context.getComplexType(ScalarType); 1335 1336 if (!IsCompAssign) 1337 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1338 CK_IntegralRealToComplex); 1339 return ComplexType; 1340 } 1341 1342 /// Return the rank of a given fixed point or integer type. The value itself 1343 /// doesn't matter, but the values must be increasing with proper increasing 1344 /// rank as described in N1169 4.1.1. 1345 static unsigned GetFixedPointRank(QualType Ty) { 1346 const auto *BTy = Ty->getAs<BuiltinType>(); 1347 assert(BTy && "Expected a builtin type."); 1348 1349 switch (BTy->getKind()) { 1350 case BuiltinType::ShortFract: 1351 case BuiltinType::UShortFract: 1352 case BuiltinType::SatShortFract: 1353 case BuiltinType::SatUShortFract: 1354 return 1; 1355 case BuiltinType::Fract: 1356 case BuiltinType::UFract: 1357 case BuiltinType::SatFract: 1358 case BuiltinType::SatUFract: 1359 return 2; 1360 case BuiltinType::LongFract: 1361 case BuiltinType::ULongFract: 1362 case BuiltinType::SatLongFract: 1363 case BuiltinType::SatULongFract: 1364 return 3; 1365 case BuiltinType::ShortAccum: 1366 case BuiltinType::UShortAccum: 1367 case BuiltinType::SatShortAccum: 1368 case BuiltinType::SatUShortAccum: 1369 return 4; 1370 case BuiltinType::Accum: 1371 case BuiltinType::UAccum: 1372 case BuiltinType::SatAccum: 1373 case BuiltinType::SatUAccum: 1374 return 5; 1375 case BuiltinType::LongAccum: 1376 case BuiltinType::ULongAccum: 1377 case BuiltinType::SatLongAccum: 1378 case BuiltinType::SatULongAccum: 1379 return 6; 1380 default: 1381 if (BTy->isInteger()) 1382 return 0; 1383 llvm_unreachable("Unexpected fixed point or integer type"); 1384 } 1385 } 1386 1387 /// handleFixedPointConversion - Fixed point operations between fixed 1388 /// point types and integers or other fixed point types do not fall under 1389 /// usual arithmetic conversion since these conversions could result in loss 1390 /// of precsision (N1169 4.1.4). These operations should be calculated with 1391 /// the full precision of their result type (N1169 4.1.6.2.1). 1392 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1393 QualType RHSTy) { 1394 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1395 "Expected at least one of the operands to be a fixed point type"); 1396 assert((LHSTy->isFixedPointOrIntegerType() || 1397 RHSTy->isFixedPointOrIntegerType()) && 1398 "Special fixed point arithmetic operation conversions are only " 1399 "applied to ints or other fixed point types"); 1400 1401 // If one operand has signed fixed-point type and the other operand has 1402 // unsigned fixed-point type, then the unsigned fixed-point operand is 1403 // converted to its corresponding signed fixed-point type and the resulting 1404 // type is the type of the converted operand. 1405 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1406 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1407 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1408 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1409 1410 // The result type is the type with the highest rank, whereby a fixed-point 1411 // conversion rank is always greater than an integer conversion rank; if the 1412 // type of either of the operands is a saturating fixedpoint type, the result 1413 // type shall be the saturating fixed-point type corresponding to the type 1414 // with the highest rank; the resulting value is converted (taking into 1415 // account rounding and overflow) to the precision of the resulting type. 1416 // Same ranks between signed and unsigned types are resolved earlier, so both 1417 // types are either signed or both unsigned at this point. 1418 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1419 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1420 1421 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1422 1423 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1424 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1425 1426 return ResultTy; 1427 } 1428 1429 /// Check that the usual arithmetic conversions can be performed on this pair of 1430 /// expressions that might be of enumeration type. 1431 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1432 SourceLocation Loc, 1433 Sema::ArithConvKind ACK) { 1434 // C++2a [expr.arith.conv]p1: 1435 // If one operand is of enumeration type and the other operand is of a 1436 // different enumeration type or a floating-point type, this behavior is 1437 // deprecated ([depr.arith.conv.enum]). 1438 // 1439 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1440 // Eventually we will presumably reject these cases (in C++23 onwards?). 1441 QualType L = LHS->getType(), R = RHS->getType(); 1442 bool LEnum = L->isUnscopedEnumerationType(), 1443 REnum = R->isUnscopedEnumerationType(); 1444 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1445 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1446 (REnum && L->isFloatingType())) { 1447 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1448 ? diag::warn_arith_conv_enum_float_cxx20 1449 : diag::warn_arith_conv_enum_float) 1450 << LHS->getSourceRange() << RHS->getSourceRange() 1451 << (int)ACK << LEnum << L << R; 1452 } else if (!IsCompAssign && LEnum && REnum && 1453 !S.Context.hasSameUnqualifiedType(L, R)) { 1454 unsigned DiagID; 1455 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1456 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1457 // If either enumeration type is unnamed, it's less likely that the 1458 // user cares about this, but this situation is still deprecated in 1459 // C++2a. Use a different warning group. 1460 DiagID = S.getLangOpts().CPlusPlus20 1461 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1462 : diag::warn_arith_conv_mixed_anon_enum_types; 1463 } else if (ACK == Sema::ACK_Conditional) { 1464 // Conditional expressions are separated out because they have 1465 // historically had a different warning flag. 1466 DiagID = S.getLangOpts().CPlusPlus20 1467 ? diag::warn_conditional_mixed_enum_types_cxx20 1468 : diag::warn_conditional_mixed_enum_types; 1469 } else if (ACK == Sema::ACK_Comparison) { 1470 // Comparison expressions are separated out because they have 1471 // historically had a different warning flag. 1472 DiagID = S.getLangOpts().CPlusPlus20 1473 ? diag::warn_comparison_mixed_enum_types_cxx20 1474 : diag::warn_comparison_mixed_enum_types; 1475 } else { 1476 DiagID = S.getLangOpts().CPlusPlus20 1477 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1478 : diag::warn_arith_conv_mixed_enum_types; 1479 } 1480 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1481 << (int)ACK << L << R; 1482 } 1483 } 1484 1485 /// UsualArithmeticConversions - Performs various conversions that are common to 1486 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1487 /// routine returns the first non-arithmetic type found. The client is 1488 /// responsible for emitting appropriate error diagnostics. 1489 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1490 SourceLocation Loc, 1491 ArithConvKind ACK) { 1492 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1493 1494 if (ACK != ACK_CompAssign) { 1495 LHS = UsualUnaryConversions(LHS.get()); 1496 if (LHS.isInvalid()) 1497 return QualType(); 1498 } 1499 1500 RHS = UsualUnaryConversions(RHS.get()); 1501 if (RHS.isInvalid()) 1502 return QualType(); 1503 1504 // For conversion purposes, we ignore any qualifiers. 1505 // For example, "const float" and "float" are equivalent. 1506 QualType LHSType = 1507 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1508 QualType RHSType = 1509 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1510 1511 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1512 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1513 LHSType = AtomicLHS->getValueType(); 1514 1515 // If both types are identical, no conversion is needed. 1516 if (LHSType == RHSType) 1517 return LHSType; 1518 1519 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1520 // The caller can deal with this (e.g. pointer + int). 1521 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1522 return QualType(); 1523 1524 // Apply unary and bitfield promotions to the LHS's type. 1525 QualType LHSUnpromotedType = LHSType; 1526 if (LHSType->isPromotableIntegerType()) 1527 LHSType = Context.getPromotedIntegerType(LHSType); 1528 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1529 if (!LHSBitfieldPromoteTy.isNull()) 1530 LHSType = LHSBitfieldPromoteTy; 1531 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1532 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1533 1534 // If both types are identical, no conversion is needed. 1535 if (LHSType == RHSType) 1536 return LHSType; 1537 1538 // ExtInt types aren't subject to conversions between them or normal integers, 1539 // so this fails. 1540 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1541 return QualType(); 1542 1543 // At this point, we have two different arithmetic types. 1544 1545 // Diagnose attempts to convert between __float128 and long double where 1546 // such conversions currently can't be handled. 1547 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1548 return QualType(); 1549 1550 // Handle complex types first (C99 6.3.1.8p1). 1551 if (LHSType->isComplexType() || RHSType->isComplexType()) 1552 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1553 ACK == ACK_CompAssign); 1554 1555 // Now handle "real" floating types (i.e. float, double, long double). 1556 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1557 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1558 ACK == ACK_CompAssign); 1559 1560 // Handle GCC complex int extension. 1561 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1562 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1563 ACK == ACK_CompAssign); 1564 1565 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1566 return handleFixedPointConversion(*this, LHSType, RHSType); 1567 1568 // Finally, we have two differing integer types. 1569 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1570 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1571 } 1572 1573 //===----------------------------------------------------------------------===// 1574 // Semantic Analysis for various Expression Types 1575 //===----------------------------------------------------------------------===// 1576 1577 1578 ExprResult 1579 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1580 SourceLocation DefaultLoc, 1581 SourceLocation RParenLoc, 1582 Expr *ControllingExpr, 1583 ArrayRef<ParsedType> ArgTypes, 1584 ArrayRef<Expr *> ArgExprs) { 1585 unsigned NumAssocs = ArgTypes.size(); 1586 assert(NumAssocs == ArgExprs.size()); 1587 1588 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1589 for (unsigned i = 0; i < NumAssocs; ++i) { 1590 if (ArgTypes[i]) 1591 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1592 else 1593 Types[i] = nullptr; 1594 } 1595 1596 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1597 ControllingExpr, 1598 llvm::makeArrayRef(Types, NumAssocs), 1599 ArgExprs); 1600 delete [] Types; 1601 return ER; 1602 } 1603 1604 ExprResult 1605 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1606 SourceLocation DefaultLoc, 1607 SourceLocation RParenLoc, 1608 Expr *ControllingExpr, 1609 ArrayRef<TypeSourceInfo *> Types, 1610 ArrayRef<Expr *> Exprs) { 1611 unsigned NumAssocs = Types.size(); 1612 assert(NumAssocs == Exprs.size()); 1613 1614 // Decay and strip qualifiers for the controlling expression type, and handle 1615 // placeholder type replacement. See committee discussion from WG14 DR423. 1616 { 1617 EnterExpressionEvaluationContext Unevaluated( 1618 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1619 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1620 if (R.isInvalid()) 1621 return ExprError(); 1622 ControllingExpr = R.get(); 1623 } 1624 1625 // The controlling expression is an unevaluated operand, so side effects are 1626 // likely unintended. 1627 if (!inTemplateInstantiation() && 1628 ControllingExpr->HasSideEffects(Context, false)) 1629 Diag(ControllingExpr->getExprLoc(), 1630 diag::warn_side_effects_unevaluated_context); 1631 1632 bool TypeErrorFound = false, 1633 IsResultDependent = ControllingExpr->isTypeDependent(), 1634 ContainsUnexpandedParameterPack 1635 = ControllingExpr->containsUnexpandedParameterPack(); 1636 1637 for (unsigned i = 0; i < NumAssocs; ++i) { 1638 if (Exprs[i]->containsUnexpandedParameterPack()) 1639 ContainsUnexpandedParameterPack = true; 1640 1641 if (Types[i]) { 1642 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1643 ContainsUnexpandedParameterPack = true; 1644 1645 if (Types[i]->getType()->isDependentType()) { 1646 IsResultDependent = true; 1647 } else { 1648 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1649 // complete object type other than a variably modified type." 1650 unsigned D = 0; 1651 if (Types[i]->getType()->isIncompleteType()) 1652 D = diag::err_assoc_type_incomplete; 1653 else if (!Types[i]->getType()->isObjectType()) 1654 D = diag::err_assoc_type_nonobject; 1655 else if (Types[i]->getType()->isVariablyModifiedType()) 1656 D = diag::err_assoc_type_variably_modified; 1657 1658 if (D != 0) { 1659 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1660 << Types[i]->getTypeLoc().getSourceRange() 1661 << Types[i]->getType(); 1662 TypeErrorFound = true; 1663 } 1664 1665 // C11 6.5.1.1p2 "No two generic associations in the same generic 1666 // selection shall specify compatible types." 1667 for (unsigned j = i+1; j < NumAssocs; ++j) 1668 if (Types[j] && !Types[j]->getType()->isDependentType() && 1669 Context.typesAreCompatible(Types[i]->getType(), 1670 Types[j]->getType())) { 1671 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1672 diag::err_assoc_compatible_types) 1673 << Types[j]->getTypeLoc().getSourceRange() 1674 << Types[j]->getType() 1675 << Types[i]->getType(); 1676 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1677 diag::note_compat_assoc) 1678 << Types[i]->getTypeLoc().getSourceRange() 1679 << Types[i]->getType(); 1680 TypeErrorFound = true; 1681 } 1682 } 1683 } 1684 } 1685 if (TypeErrorFound) 1686 return ExprError(); 1687 1688 // If we determined that the generic selection is result-dependent, don't 1689 // try to compute the result expression. 1690 if (IsResultDependent) 1691 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1692 Exprs, DefaultLoc, RParenLoc, 1693 ContainsUnexpandedParameterPack); 1694 1695 SmallVector<unsigned, 1> CompatIndices; 1696 unsigned DefaultIndex = -1U; 1697 for (unsigned i = 0; i < NumAssocs; ++i) { 1698 if (!Types[i]) 1699 DefaultIndex = i; 1700 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1701 Types[i]->getType())) 1702 CompatIndices.push_back(i); 1703 } 1704 1705 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1706 // type compatible with at most one of the types named in its generic 1707 // association list." 1708 if (CompatIndices.size() > 1) { 1709 // We strip parens here because the controlling expression is typically 1710 // parenthesized in macro definitions. 1711 ControllingExpr = ControllingExpr->IgnoreParens(); 1712 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1713 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1714 << (unsigned)CompatIndices.size(); 1715 for (unsigned I : CompatIndices) { 1716 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1717 diag::note_compat_assoc) 1718 << Types[I]->getTypeLoc().getSourceRange() 1719 << Types[I]->getType(); 1720 } 1721 return ExprError(); 1722 } 1723 1724 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1725 // its controlling expression shall have type compatible with exactly one of 1726 // the types named in its generic association list." 1727 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1728 // We strip parens here because the controlling expression is typically 1729 // parenthesized in macro definitions. 1730 ControllingExpr = ControllingExpr->IgnoreParens(); 1731 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1732 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1733 return ExprError(); 1734 } 1735 1736 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1737 // type name that is compatible with the type of the controlling expression, 1738 // then the result expression of the generic selection is the expression 1739 // in that generic association. Otherwise, the result expression of the 1740 // generic selection is the expression in the default generic association." 1741 unsigned ResultIndex = 1742 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1743 1744 return GenericSelectionExpr::Create( 1745 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1746 ContainsUnexpandedParameterPack, ResultIndex); 1747 } 1748 1749 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1750 /// location of the token and the offset of the ud-suffix within it. 1751 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1752 unsigned Offset) { 1753 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1754 S.getLangOpts()); 1755 } 1756 1757 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1758 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1759 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1760 IdentifierInfo *UDSuffix, 1761 SourceLocation UDSuffixLoc, 1762 ArrayRef<Expr*> Args, 1763 SourceLocation LitEndLoc) { 1764 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1765 1766 QualType ArgTy[2]; 1767 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1768 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1769 if (ArgTy[ArgIdx]->isArrayType()) 1770 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1771 } 1772 1773 DeclarationName OpName = 1774 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1775 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1776 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1777 1778 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1779 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1780 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1781 /*AllowStringTemplatePack*/ false, 1782 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1783 return ExprError(); 1784 1785 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1786 } 1787 1788 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1789 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1790 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1791 /// multiple tokens. However, the common case is that StringToks points to one 1792 /// string. 1793 /// 1794 ExprResult 1795 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1796 assert(!StringToks.empty() && "Must have at least one string!"); 1797 1798 StringLiteralParser Literal(StringToks, PP); 1799 if (Literal.hadError) 1800 return ExprError(); 1801 1802 SmallVector<SourceLocation, 4> StringTokLocs; 1803 for (const Token &Tok : StringToks) 1804 StringTokLocs.push_back(Tok.getLocation()); 1805 1806 QualType CharTy = Context.CharTy; 1807 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1808 if (Literal.isWide()) { 1809 CharTy = Context.getWideCharType(); 1810 Kind = StringLiteral::Wide; 1811 } else if (Literal.isUTF8()) { 1812 if (getLangOpts().Char8) 1813 CharTy = Context.Char8Ty; 1814 Kind = StringLiteral::UTF8; 1815 } else if (Literal.isUTF16()) { 1816 CharTy = Context.Char16Ty; 1817 Kind = StringLiteral::UTF16; 1818 } else if (Literal.isUTF32()) { 1819 CharTy = Context.Char32Ty; 1820 Kind = StringLiteral::UTF32; 1821 } else if (Literal.isPascal()) { 1822 CharTy = Context.UnsignedCharTy; 1823 } 1824 1825 // Warn on initializing an array of char from a u8 string literal; this 1826 // becomes ill-formed in C++2a. 1827 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1828 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1829 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1830 1831 // Create removals for all 'u8' prefixes in the string literal(s). This 1832 // ensures C++2a compatibility (but may change the program behavior when 1833 // built by non-Clang compilers for which the execution character set is 1834 // not always UTF-8). 1835 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1836 SourceLocation RemovalDiagLoc; 1837 for (const Token &Tok : StringToks) { 1838 if (Tok.getKind() == tok::utf8_string_literal) { 1839 if (RemovalDiagLoc.isInvalid()) 1840 RemovalDiagLoc = Tok.getLocation(); 1841 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1842 Tok.getLocation(), 1843 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1844 getSourceManager(), getLangOpts()))); 1845 } 1846 } 1847 Diag(RemovalDiagLoc, RemovalDiag); 1848 } 1849 1850 QualType StrTy = 1851 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1852 1853 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1854 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1855 Kind, Literal.Pascal, StrTy, 1856 &StringTokLocs[0], 1857 StringTokLocs.size()); 1858 if (Literal.getUDSuffix().empty()) 1859 return Lit; 1860 1861 // We're building a user-defined literal. 1862 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1863 SourceLocation UDSuffixLoc = 1864 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1865 Literal.getUDSuffixOffset()); 1866 1867 // Make sure we're allowed user-defined literals here. 1868 if (!UDLScope) 1869 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1870 1871 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1872 // operator "" X (str, len) 1873 QualType SizeType = Context.getSizeType(); 1874 1875 DeclarationName OpName = 1876 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1877 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1878 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1879 1880 QualType ArgTy[] = { 1881 Context.getArrayDecayedType(StrTy), SizeType 1882 }; 1883 1884 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1885 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1886 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1887 /*AllowStringTemplatePack*/ true, 1888 /*DiagnoseMissing*/ true, Lit)) { 1889 1890 case LOLR_Cooked: { 1891 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1892 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1893 StringTokLocs[0]); 1894 Expr *Args[] = { Lit, LenArg }; 1895 1896 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1897 } 1898 1899 case LOLR_Template: { 1900 TemplateArgumentListInfo ExplicitArgs; 1901 TemplateArgument Arg(Lit); 1902 TemplateArgumentLocInfo ArgInfo(Lit); 1903 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1904 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1905 &ExplicitArgs); 1906 } 1907 1908 case LOLR_StringTemplatePack: { 1909 TemplateArgumentListInfo ExplicitArgs; 1910 1911 unsigned CharBits = Context.getIntWidth(CharTy); 1912 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1913 llvm::APSInt Value(CharBits, CharIsUnsigned); 1914 1915 TemplateArgument TypeArg(CharTy); 1916 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1917 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1918 1919 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1920 Value = Lit->getCodeUnit(I); 1921 TemplateArgument Arg(Context, Value, CharTy); 1922 TemplateArgumentLocInfo ArgInfo; 1923 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1924 } 1925 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1926 &ExplicitArgs); 1927 } 1928 case LOLR_Raw: 1929 case LOLR_ErrorNoDiagnostic: 1930 llvm_unreachable("unexpected literal operator lookup result"); 1931 case LOLR_Error: 1932 return ExprError(); 1933 } 1934 llvm_unreachable("unexpected literal operator lookup result"); 1935 } 1936 1937 DeclRefExpr * 1938 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1939 SourceLocation Loc, 1940 const CXXScopeSpec *SS) { 1941 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1942 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1943 } 1944 1945 DeclRefExpr * 1946 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1947 const DeclarationNameInfo &NameInfo, 1948 const CXXScopeSpec *SS, NamedDecl *FoundD, 1949 SourceLocation TemplateKWLoc, 1950 const TemplateArgumentListInfo *TemplateArgs) { 1951 NestedNameSpecifierLoc NNS = 1952 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1953 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1954 TemplateArgs); 1955 } 1956 1957 // CUDA/HIP: Check whether a captured reference variable is referencing a 1958 // host variable in a device or host device lambda. 1959 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1960 VarDecl *VD) { 1961 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1962 return false; 1963 assert(VD->getType()->isReferenceType()); 1964 1965 // Check whether the reference variable is referencing a host variable. 1966 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1967 if (!DRE) 1968 return false; 1969 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1970 if (!Referee || !Referee->hasGlobalStorage() || 1971 Referee->hasAttr<CUDADeviceAttr>()) 1972 return false; 1973 1974 // Check whether the current function is a device or host device lambda. 1975 // Check whether the reference variable is a capture by getDeclContext() 1976 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1977 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1978 if (MD && MD->getParent()->isLambda() && 1979 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1980 VD->getDeclContext() != MD) 1981 return true; 1982 1983 return false; 1984 } 1985 1986 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1987 // A declaration named in an unevaluated operand never constitutes an odr-use. 1988 if (isUnevaluatedContext()) 1989 return NOUR_Unevaluated; 1990 1991 // C++2a [basic.def.odr]p4: 1992 // A variable x whose name appears as a potentially-evaluated expression e 1993 // is odr-used by e unless [...] x is a reference that is usable in 1994 // constant expressions. 1995 // CUDA/HIP: 1996 // If a reference variable referencing a host variable is captured in a 1997 // device or host device lambda, the value of the referee must be copied 1998 // to the capture and the reference variable must be treated as odr-use 1999 // since the value of the referee is not known at compile time and must 2000 // be loaded from the captured. 2001 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2002 if (VD->getType()->isReferenceType() && 2003 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2004 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2005 VD->isUsableInConstantExpressions(Context)) 2006 return NOUR_Constant; 2007 } 2008 2009 // All remaining non-variable cases constitute an odr-use. For variables, we 2010 // need to wait and see how the expression is used. 2011 return NOUR_None; 2012 } 2013 2014 /// BuildDeclRefExpr - Build an expression that references a 2015 /// declaration that does not require a closure capture. 2016 DeclRefExpr * 2017 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2018 const DeclarationNameInfo &NameInfo, 2019 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2020 SourceLocation TemplateKWLoc, 2021 const TemplateArgumentListInfo *TemplateArgs) { 2022 bool RefersToCapturedVariable = 2023 isa<VarDecl>(D) && 2024 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2025 2026 DeclRefExpr *E = DeclRefExpr::Create( 2027 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2028 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2029 MarkDeclRefReferenced(E); 2030 2031 // C++ [except.spec]p17: 2032 // An exception-specification is considered to be needed when: 2033 // - in an expression, the function is the unique lookup result or 2034 // the selected member of a set of overloaded functions. 2035 // 2036 // We delay doing this until after we've built the function reference and 2037 // marked it as used so that: 2038 // a) if the function is defaulted, we get errors from defining it before / 2039 // instead of errors from computing its exception specification, and 2040 // b) if the function is a defaulted comparison, we can use the body we 2041 // build when defining it as input to the exception specification 2042 // computation rather than computing a new body. 2043 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2044 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2045 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2046 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2047 } 2048 } 2049 2050 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2051 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2052 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2053 getCurFunction()->recordUseOfWeak(E); 2054 2055 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2056 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2057 FD = IFD->getAnonField(); 2058 if (FD) { 2059 UnusedPrivateFields.remove(FD); 2060 // Just in case we're building an illegal pointer-to-member. 2061 if (FD->isBitField()) 2062 E->setObjectKind(OK_BitField); 2063 } 2064 2065 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2066 // designates a bit-field. 2067 if (auto *BD = dyn_cast<BindingDecl>(D)) 2068 if (auto *BE = BD->getBinding()) 2069 E->setObjectKind(BE->getObjectKind()); 2070 2071 return E; 2072 } 2073 2074 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2075 /// possibly a list of template arguments. 2076 /// 2077 /// If this produces template arguments, it is permitted to call 2078 /// DecomposeTemplateName. 2079 /// 2080 /// This actually loses a lot of source location information for 2081 /// non-standard name kinds; we should consider preserving that in 2082 /// some way. 2083 void 2084 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2085 TemplateArgumentListInfo &Buffer, 2086 DeclarationNameInfo &NameInfo, 2087 const TemplateArgumentListInfo *&TemplateArgs) { 2088 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2089 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2090 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2091 2092 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2093 Id.TemplateId->NumArgs); 2094 translateTemplateArguments(TemplateArgsPtr, Buffer); 2095 2096 TemplateName TName = Id.TemplateId->Template.get(); 2097 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2098 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2099 TemplateArgs = &Buffer; 2100 } else { 2101 NameInfo = GetNameFromUnqualifiedId(Id); 2102 TemplateArgs = nullptr; 2103 } 2104 } 2105 2106 static void emitEmptyLookupTypoDiagnostic( 2107 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2108 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2109 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2110 DeclContext *Ctx = 2111 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2112 if (!TC) { 2113 // Emit a special diagnostic for failed member lookups. 2114 // FIXME: computing the declaration context might fail here (?) 2115 if (Ctx) 2116 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2117 << SS.getRange(); 2118 else 2119 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2120 return; 2121 } 2122 2123 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2124 bool DroppedSpecifier = 2125 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2126 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2127 ? diag::note_implicit_param_decl 2128 : diag::note_previous_decl; 2129 if (!Ctx) 2130 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2131 SemaRef.PDiag(NoteID)); 2132 else 2133 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2134 << Typo << Ctx << DroppedSpecifier 2135 << SS.getRange(), 2136 SemaRef.PDiag(NoteID)); 2137 } 2138 2139 /// Diagnose a lookup that found results in an enclosing class during error 2140 /// recovery. This usually indicates that the results were found in a dependent 2141 /// base class that could not be searched as part of a template definition. 2142 /// Always issues a diagnostic (though this may be only a warning in MS 2143 /// compatibility mode). 2144 /// 2145 /// Return \c true if the error is unrecoverable, or \c false if the caller 2146 /// should attempt to recover using these lookup results. 2147 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2148 // During a default argument instantiation the CurContext points 2149 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2150 // function parameter list, hence add an explicit check. 2151 bool isDefaultArgument = 2152 !CodeSynthesisContexts.empty() && 2153 CodeSynthesisContexts.back().Kind == 2154 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2155 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2156 bool isInstance = CurMethod && CurMethod->isInstance() && 2157 R.getNamingClass() == CurMethod->getParent() && 2158 !isDefaultArgument; 2159 2160 // There are two ways we can find a class-scope declaration during template 2161 // instantiation that we did not find in the template definition: if it is a 2162 // member of a dependent base class, or if it is declared after the point of 2163 // use in the same class. Distinguish these by comparing the class in which 2164 // the member was found to the naming class of the lookup. 2165 unsigned DiagID = diag::err_found_in_dependent_base; 2166 unsigned NoteID = diag::note_member_declared_at; 2167 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2168 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2169 : diag::err_found_later_in_class; 2170 } else if (getLangOpts().MSVCCompat) { 2171 DiagID = diag::ext_found_in_dependent_base; 2172 NoteID = diag::note_dependent_member_use; 2173 } 2174 2175 if (isInstance) { 2176 // Give a code modification hint to insert 'this->'. 2177 Diag(R.getNameLoc(), DiagID) 2178 << R.getLookupName() 2179 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2180 CheckCXXThisCapture(R.getNameLoc()); 2181 } else { 2182 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2183 // they're not shadowed). 2184 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2185 } 2186 2187 for (NamedDecl *D : R) 2188 Diag(D->getLocation(), NoteID); 2189 2190 // Return true if we are inside a default argument instantiation 2191 // and the found name refers to an instance member function, otherwise 2192 // the caller will try to create an implicit member call and this is wrong 2193 // for default arguments. 2194 // 2195 // FIXME: Is this special case necessary? We could allow the caller to 2196 // diagnose this. 2197 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2198 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2199 return true; 2200 } 2201 2202 // Tell the callee to try to recover. 2203 return false; 2204 } 2205 2206 /// Diagnose an empty lookup. 2207 /// 2208 /// \return false if new lookup candidates were found 2209 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2210 CorrectionCandidateCallback &CCC, 2211 TemplateArgumentListInfo *ExplicitTemplateArgs, 2212 ArrayRef<Expr *> Args, TypoExpr **Out) { 2213 DeclarationName Name = R.getLookupName(); 2214 2215 unsigned diagnostic = diag::err_undeclared_var_use; 2216 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2217 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2218 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2219 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2220 diagnostic = diag::err_undeclared_use; 2221 diagnostic_suggest = diag::err_undeclared_use_suggest; 2222 } 2223 2224 // If the original lookup was an unqualified lookup, fake an 2225 // unqualified lookup. This is useful when (for example) the 2226 // original lookup would not have found something because it was a 2227 // dependent name. 2228 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2229 while (DC) { 2230 if (isa<CXXRecordDecl>(DC)) { 2231 LookupQualifiedName(R, DC); 2232 2233 if (!R.empty()) { 2234 // Don't give errors about ambiguities in this lookup. 2235 R.suppressDiagnostics(); 2236 2237 // If there's a best viable function among the results, only mention 2238 // that one in the notes. 2239 OverloadCandidateSet Candidates(R.getNameLoc(), 2240 OverloadCandidateSet::CSK_Normal); 2241 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2242 OverloadCandidateSet::iterator Best; 2243 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2244 OR_Success) { 2245 R.clear(); 2246 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2247 R.resolveKind(); 2248 } 2249 2250 return DiagnoseDependentMemberLookup(R); 2251 } 2252 2253 R.clear(); 2254 } 2255 2256 DC = DC->getLookupParent(); 2257 } 2258 2259 // We didn't find anything, so try to correct for a typo. 2260 TypoCorrection Corrected; 2261 if (S && Out) { 2262 SourceLocation TypoLoc = R.getNameLoc(); 2263 assert(!ExplicitTemplateArgs && 2264 "Diagnosing an empty lookup with explicit template args!"); 2265 *Out = CorrectTypoDelayed( 2266 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2267 [=](const TypoCorrection &TC) { 2268 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2269 diagnostic, diagnostic_suggest); 2270 }, 2271 nullptr, CTK_ErrorRecovery); 2272 if (*Out) 2273 return true; 2274 } else if (S && 2275 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2276 S, &SS, CCC, CTK_ErrorRecovery))) { 2277 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2278 bool DroppedSpecifier = 2279 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2280 R.setLookupName(Corrected.getCorrection()); 2281 2282 bool AcceptableWithRecovery = false; 2283 bool AcceptableWithoutRecovery = false; 2284 NamedDecl *ND = Corrected.getFoundDecl(); 2285 if (ND) { 2286 if (Corrected.isOverloaded()) { 2287 OverloadCandidateSet OCS(R.getNameLoc(), 2288 OverloadCandidateSet::CSK_Normal); 2289 OverloadCandidateSet::iterator Best; 2290 for (NamedDecl *CD : Corrected) { 2291 if (FunctionTemplateDecl *FTD = 2292 dyn_cast<FunctionTemplateDecl>(CD)) 2293 AddTemplateOverloadCandidate( 2294 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2295 Args, OCS); 2296 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2297 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2298 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2299 Args, OCS); 2300 } 2301 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2302 case OR_Success: 2303 ND = Best->FoundDecl; 2304 Corrected.setCorrectionDecl(ND); 2305 break; 2306 default: 2307 // FIXME: Arbitrarily pick the first declaration for the note. 2308 Corrected.setCorrectionDecl(ND); 2309 break; 2310 } 2311 } 2312 R.addDecl(ND); 2313 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2314 CXXRecordDecl *Record = nullptr; 2315 if (Corrected.getCorrectionSpecifier()) { 2316 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2317 Record = Ty->getAsCXXRecordDecl(); 2318 } 2319 if (!Record) 2320 Record = cast<CXXRecordDecl>( 2321 ND->getDeclContext()->getRedeclContext()); 2322 R.setNamingClass(Record); 2323 } 2324 2325 auto *UnderlyingND = ND->getUnderlyingDecl(); 2326 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2327 isa<FunctionTemplateDecl>(UnderlyingND); 2328 // FIXME: If we ended up with a typo for a type name or 2329 // Objective-C class name, we're in trouble because the parser 2330 // is in the wrong place to recover. Suggest the typo 2331 // correction, but don't make it a fix-it since we're not going 2332 // to recover well anyway. 2333 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2334 getAsTypeTemplateDecl(UnderlyingND) || 2335 isa<ObjCInterfaceDecl>(UnderlyingND); 2336 } else { 2337 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2338 // because we aren't able to recover. 2339 AcceptableWithoutRecovery = true; 2340 } 2341 2342 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2343 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2344 ? diag::note_implicit_param_decl 2345 : diag::note_previous_decl; 2346 if (SS.isEmpty()) 2347 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2348 PDiag(NoteID), AcceptableWithRecovery); 2349 else 2350 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2351 << Name << computeDeclContext(SS, false) 2352 << DroppedSpecifier << SS.getRange(), 2353 PDiag(NoteID), AcceptableWithRecovery); 2354 2355 // Tell the callee whether to try to recover. 2356 return !AcceptableWithRecovery; 2357 } 2358 } 2359 R.clear(); 2360 2361 // Emit a special diagnostic for failed member lookups. 2362 // FIXME: computing the declaration context might fail here (?) 2363 if (!SS.isEmpty()) { 2364 Diag(R.getNameLoc(), diag::err_no_member) 2365 << Name << computeDeclContext(SS, false) 2366 << SS.getRange(); 2367 return true; 2368 } 2369 2370 // Give up, we can't recover. 2371 Diag(R.getNameLoc(), diagnostic) << Name; 2372 return true; 2373 } 2374 2375 /// In Microsoft mode, if we are inside a template class whose parent class has 2376 /// dependent base classes, and we can't resolve an unqualified identifier, then 2377 /// assume the identifier is a member of a dependent base class. We can only 2378 /// recover successfully in static methods, instance methods, and other contexts 2379 /// where 'this' is available. This doesn't precisely match MSVC's 2380 /// instantiation model, but it's close enough. 2381 static Expr * 2382 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2383 DeclarationNameInfo &NameInfo, 2384 SourceLocation TemplateKWLoc, 2385 const TemplateArgumentListInfo *TemplateArgs) { 2386 // Only try to recover from lookup into dependent bases in static methods or 2387 // contexts where 'this' is available. 2388 QualType ThisType = S.getCurrentThisType(); 2389 const CXXRecordDecl *RD = nullptr; 2390 if (!ThisType.isNull()) 2391 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2392 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2393 RD = MD->getParent(); 2394 if (!RD || !RD->hasAnyDependentBases()) 2395 return nullptr; 2396 2397 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2398 // is available, suggest inserting 'this->' as a fixit. 2399 SourceLocation Loc = NameInfo.getLoc(); 2400 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2401 DB << NameInfo.getName() << RD; 2402 2403 if (!ThisType.isNull()) { 2404 DB << FixItHint::CreateInsertion(Loc, "this->"); 2405 return CXXDependentScopeMemberExpr::Create( 2406 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2407 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2408 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2409 } 2410 2411 // Synthesize a fake NNS that points to the derived class. This will 2412 // perform name lookup during template instantiation. 2413 CXXScopeSpec SS; 2414 auto *NNS = 2415 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2416 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2417 return DependentScopeDeclRefExpr::Create( 2418 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2419 TemplateArgs); 2420 } 2421 2422 ExprResult 2423 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2424 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2425 bool HasTrailingLParen, bool IsAddressOfOperand, 2426 CorrectionCandidateCallback *CCC, 2427 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2428 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2429 "cannot be direct & operand and have a trailing lparen"); 2430 if (SS.isInvalid()) 2431 return ExprError(); 2432 2433 TemplateArgumentListInfo TemplateArgsBuffer; 2434 2435 // Decompose the UnqualifiedId into the following data. 2436 DeclarationNameInfo NameInfo; 2437 const TemplateArgumentListInfo *TemplateArgs; 2438 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2439 2440 DeclarationName Name = NameInfo.getName(); 2441 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2442 SourceLocation NameLoc = NameInfo.getLoc(); 2443 2444 if (II && II->isEditorPlaceholder()) { 2445 // FIXME: When typed placeholders are supported we can create a typed 2446 // placeholder expression node. 2447 return ExprError(); 2448 } 2449 2450 // C++ [temp.dep.expr]p3: 2451 // An id-expression is type-dependent if it contains: 2452 // -- an identifier that was declared with a dependent type, 2453 // (note: handled after lookup) 2454 // -- a template-id that is dependent, 2455 // (note: handled in BuildTemplateIdExpr) 2456 // -- a conversion-function-id that specifies a dependent type, 2457 // -- a nested-name-specifier that contains a class-name that 2458 // names a dependent type. 2459 // Determine whether this is a member of an unknown specialization; 2460 // we need to handle these differently. 2461 bool DependentID = false; 2462 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2463 Name.getCXXNameType()->isDependentType()) { 2464 DependentID = true; 2465 } else if (SS.isSet()) { 2466 if (DeclContext *DC = computeDeclContext(SS, false)) { 2467 if (RequireCompleteDeclContext(SS, DC)) 2468 return ExprError(); 2469 } else { 2470 DependentID = true; 2471 } 2472 } 2473 2474 if (DependentID) 2475 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2476 IsAddressOfOperand, TemplateArgs); 2477 2478 // Perform the required lookup. 2479 LookupResult R(*this, NameInfo, 2480 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2481 ? LookupObjCImplicitSelfParam 2482 : LookupOrdinaryName); 2483 if (TemplateKWLoc.isValid() || TemplateArgs) { 2484 // Lookup the template name again to correctly establish the context in 2485 // which it was found. This is really unfortunate as we already did the 2486 // lookup to determine that it was a template name in the first place. If 2487 // this becomes a performance hit, we can work harder to preserve those 2488 // results until we get here but it's likely not worth it. 2489 bool MemberOfUnknownSpecialization; 2490 AssumedTemplateKind AssumedTemplate; 2491 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2492 MemberOfUnknownSpecialization, TemplateKWLoc, 2493 &AssumedTemplate)) 2494 return ExprError(); 2495 2496 if (MemberOfUnknownSpecialization || 2497 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2498 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2499 IsAddressOfOperand, TemplateArgs); 2500 } else { 2501 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2502 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2503 2504 // If the result might be in a dependent base class, this is a dependent 2505 // id-expression. 2506 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2507 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2508 IsAddressOfOperand, TemplateArgs); 2509 2510 // If this reference is in an Objective-C method, then we need to do 2511 // some special Objective-C lookup, too. 2512 if (IvarLookupFollowUp) { 2513 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2514 if (E.isInvalid()) 2515 return ExprError(); 2516 2517 if (Expr *Ex = E.getAs<Expr>()) 2518 return Ex; 2519 } 2520 } 2521 2522 if (R.isAmbiguous()) 2523 return ExprError(); 2524 2525 // This could be an implicitly declared function reference (legal in C90, 2526 // extension in C99, forbidden in C++). 2527 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2528 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2529 if (D) R.addDecl(D); 2530 } 2531 2532 // Determine whether this name might be a candidate for 2533 // argument-dependent lookup. 2534 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2535 2536 if (R.empty() && !ADL) { 2537 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2538 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2539 TemplateKWLoc, TemplateArgs)) 2540 return E; 2541 } 2542 2543 // Don't diagnose an empty lookup for inline assembly. 2544 if (IsInlineAsmIdentifier) 2545 return ExprError(); 2546 2547 // If this name wasn't predeclared and if this is not a function 2548 // call, diagnose the problem. 2549 TypoExpr *TE = nullptr; 2550 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2551 : nullptr); 2552 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2553 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2554 "Typo correction callback misconfigured"); 2555 if (CCC) { 2556 // Make sure the callback knows what the typo being diagnosed is. 2557 CCC->setTypoName(II); 2558 if (SS.isValid()) 2559 CCC->setTypoNNS(SS.getScopeRep()); 2560 } 2561 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2562 // a template name, but we happen to have always already looked up the name 2563 // before we get here if it must be a template name. 2564 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2565 None, &TE)) { 2566 if (TE && KeywordReplacement) { 2567 auto &State = getTypoExprState(TE); 2568 auto BestTC = State.Consumer->getNextCorrection(); 2569 if (BestTC.isKeyword()) { 2570 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2571 if (State.DiagHandler) 2572 State.DiagHandler(BestTC); 2573 KeywordReplacement->startToken(); 2574 KeywordReplacement->setKind(II->getTokenID()); 2575 KeywordReplacement->setIdentifierInfo(II); 2576 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2577 // Clean up the state associated with the TypoExpr, since it has 2578 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2579 clearDelayedTypo(TE); 2580 // Signal that a correction to a keyword was performed by returning a 2581 // valid-but-null ExprResult. 2582 return (Expr*)nullptr; 2583 } 2584 State.Consumer->resetCorrectionStream(); 2585 } 2586 return TE ? TE : ExprError(); 2587 } 2588 2589 assert(!R.empty() && 2590 "DiagnoseEmptyLookup returned false but added no results"); 2591 2592 // If we found an Objective-C instance variable, let 2593 // LookupInObjCMethod build the appropriate expression to 2594 // reference the ivar. 2595 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2596 R.clear(); 2597 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2598 // In a hopelessly buggy code, Objective-C instance variable 2599 // lookup fails and no expression will be built to reference it. 2600 if (!E.isInvalid() && !E.get()) 2601 return ExprError(); 2602 return E; 2603 } 2604 } 2605 2606 // This is guaranteed from this point on. 2607 assert(!R.empty() || ADL); 2608 2609 // Check whether this might be a C++ implicit instance member access. 2610 // C++ [class.mfct.non-static]p3: 2611 // When an id-expression that is not part of a class member access 2612 // syntax and not used to form a pointer to member is used in the 2613 // body of a non-static member function of class X, if name lookup 2614 // resolves the name in the id-expression to a non-static non-type 2615 // member of some class C, the id-expression is transformed into a 2616 // class member access expression using (*this) as the 2617 // postfix-expression to the left of the . operator. 2618 // 2619 // But we don't actually need to do this for '&' operands if R 2620 // resolved to a function or overloaded function set, because the 2621 // expression is ill-formed if it actually works out to be a 2622 // non-static member function: 2623 // 2624 // C++ [expr.ref]p4: 2625 // Otherwise, if E1.E2 refers to a non-static member function. . . 2626 // [t]he expression can be used only as the left-hand operand of a 2627 // member function call. 2628 // 2629 // There are other safeguards against such uses, but it's important 2630 // to get this right here so that we don't end up making a 2631 // spuriously dependent expression if we're inside a dependent 2632 // instance method. 2633 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2634 bool MightBeImplicitMember; 2635 if (!IsAddressOfOperand) 2636 MightBeImplicitMember = true; 2637 else if (!SS.isEmpty()) 2638 MightBeImplicitMember = false; 2639 else if (R.isOverloadedResult()) 2640 MightBeImplicitMember = false; 2641 else if (R.isUnresolvableResult()) 2642 MightBeImplicitMember = true; 2643 else 2644 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2645 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2646 isa<MSPropertyDecl>(R.getFoundDecl()); 2647 2648 if (MightBeImplicitMember) 2649 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2650 R, TemplateArgs, S); 2651 } 2652 2653 if (TemplateArgs || TemplateKWLoc.isValid()) { 2654 2655 // In C++1y, if this is a variable template id, then check it 2656 // in BuildTemplateIdExpr(). 2657 // The single lookup result must be a variable template declaration. 2658 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2659 Id.TemplateId->Kind == TNK_Var_template) { 2660 assert(R.getAsSingle<VarTemplateDecl>() && 2661 "There should only be one declaration found."); 2662 } 2663 2664 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2665 } 2666 2667 return BuildDeclarationNameExpr(SS, R, ADL); 2668 } 2669 2670 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2671 /// declaration name, generally during template instantiation. 2672 /// There's a large number of things which don't need to be done along 2673 /// this path. 2674 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2675 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2676 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2677 DeclContext *DC = computeDeclContext(SS, false); 2678 if (!DC) 2679 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2680 NameInfo, /*TemplateArgs=*/nullptr); 2681 2682 if (RequireCompleteDeclContext(SS, DC)) 2683 return ExprError(); 2684 2685 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2686 LookupQualifiedName(R, DC); 2687 2688 if (R.isAmbiguous()) 2689 return ExprError(); 2690 2691 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2692 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2693 NameInfo, /*TemplateArgs=*/nullptr); 2694 2695 if (R.empty()) { 2696 // Don't diagnose problems with invalid record decl, the secondary no_member 2697 // diagnostic during template instantiation is likely bogus, e.g. if a class 2698 // is invalid because it's derived from an invalid base class, then missing 2699 // members were likely supposed to be inherited. 2700 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2701 if (CD->isInvalidDecl()) 2702 return ExprError(); 2703 Diag(NameInfo.getLoc(), diag::err_no_member) 2704 << NameInfo.getName() << DC << SS.getRange(); 2705 return ExprError(); 2706 } 2707 2708 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2709 // Diagnose a missing typename if this resolved unambiguously to a type in 2710 // a dependent context. If we can recover with a type, downgrade this to 2711 // a warning in Microsoft compatibility mode. 2712 unsigned DiagID = diag::err_typename_missing; 2713 if (RecoveryTSI && getLangOpts().MSVCCompat) 2714 DiagID = diag::ext_typename_missing; 2715 SourceLocation Loc = SS.getBeginLoc(); 2716 auto D = Diag(Loc, DiagID); 2717 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2718 << SourceRange(Loc, NameInfo.getEndLoc()); 2719 2720 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2721 // context. 2722 if (!RecoveryTSI) 2723 return ExprError(); 2724 2725 // Only issue the fixit if we're prepared to recover. 2726 D << FixItHint::CreateInsertion(Loc, "typename "); 2727 2728 // Recover by pretending this was an elaborated type. 2729 QualType Ty = Context.getTypeDeclType(TD); 2730 TypeLocBuilder TLB; 2731 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2732 2733 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2734 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2735 QTL.setElaboratedKeywordLoc(SourceLocation()); 2736 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2737 2738 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2739 2740 return ExprEmpty(); 2741 } 2742 2743 // Defend against this resolving to an implicit member access. We usually 2744 // won't get here if this might be a legitimate a class member (we end up in 2745 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2746 // a pointer-to-member or in an unevaluated context in C++11. 2747 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2748 return BuildPossibleImplicitMemberExpr(SS, 2749 /*TemplateKWLoc=*/SourceLocation(), 2750 R, /*TemplateArgs=*/nullptr, S); 2751 2752 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2753 } 2754 2755 /// The parser has read a name in, and Sema has detected that we're currently 2756 /// inside an ObjC method. Perform some additional checks and determine if we 2757 /// should form a reference to an ivar. 2758 /// 2759 /// Ideally, most of this would be done by lookup, but there's 2760 /// actually quite a lot of extra work involved. 2761 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2762 IdentifierInfo *II) { 2763 SourceLocation Loc = Lookup.getNameLoc(); 2764 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2765 2766 // Check for error condition which is already reported. 2767 if (!CurMethod) 2768 return DeclResult(true); 2769 2770 // There are two cases to handle here. 1) scoped lookup could have failed, 2771 // in which case we should look for an ivar. 2) scoped lookup could have 2772 // found a decl, but that decl is outside the current instance method (i.e. 2773 // a global variable). In these two cases, we do a lookup for an ivar with 2774 // this name, if the lookup sucedes, we replace it our current decl. 2775 2776 // If we're in a class method, we don't normally want to look for 2777 // ivars. But if we don't find anything else, and there's an 2778 // ivar, that's an error. 2779 bool IsClassMethod = CurMethod->isClassMethod(); 2780 2781 bool LookForIvars; 2782 if (Lookup.empty()) 2783 LookForIvars = true; 2784 else if (IsClassMethod) 2785 LookForIvars = false; 2786 else 2787 LookForIvars = (Lookup.isSingleResult() && 2788 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2789 ObjCInterfaceDecl *IFace = nullptr; 2790 if (LookForIvars) { 2791 IFace = CurMethod->getClassInterface(); 2792 ObjCInterfaceDecl *ClassDeclared; 2793 ObjCIvarDecl *IV = nullptr; 2794 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2795 // Diagnose using an ivar in a class method. 2796 if (IsClassMethod) { 2797 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2798 return DeclResult(true); 2799 } 2800 2801 // Diagnose the use of an ivar outside of the declaring class. 2802 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2803 !declaresSameEntity(ClassDeclared, IFace) && 2804 !getLangOpts().DebuggerSupport) 2805 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2806 2807 // Success. 2808 return IV; 2809 } 2810 } else if (CurMethod->isInstanceMethod()) { 2811 // We should warn if a local variable hides an ivar. 2812 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2813 ObjCInterfaceDecl *ClassDeclared; 2814 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2815 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2816 declaresSameEntity(IFace, ClassDeclared)) 2817 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2818 } 2819 } 2820 } else if (Lookup.isSingleResult() && 2821 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2822 // If accessing a stand-alone ivar in a class method, this is an error. 2823 if (const ObjCIvarDecl *IV = 2824 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2825 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2826 return DeclResult(true); 2827 } 2828 } 2829 2830 // Didn't encounter an error, didn't find an ivar. 2831 return DeclResult(false); 2832 } 2833 2834 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2835 ObjCIvarDecl *IV) { 2836 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2837 assert(CurMethod && CurMethod->isInstanceMethod() && 2838 "should not reference ivar from this context"); 2839 2840 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2841 assert(IFace && "should not reference ivar from this context"); 2842 2843 // If we're referencing an invalid decl, just return this as a silent 2844 // error node. The error diagnostic was already emitted on the decl. 2845 if (IV->isInvalidDecl()) 2846 return ExprError(); 2847 2848 // Check if referencing a field with __attribute__((deprecated)). 2849 if (DiagnoseUseOfDecl(IV, Loc)) 2850 return ExprError(); 2851 2852 // FIXME: This should use a new expr for a direct reference, don't 2853 // turn this into Self->ivar, just return a BareIVarExpr or something. 2854 IdentifierInfo &II = Context.Idents.get("self"); 2855 UnqualifiedId SelfName; 2856 SelfName.setImplicitSelfParam(&II); 2857 CXXScopeSpec SelfScopeSpec; 2858 SourceLocation TemplateKWLoc; 2859 ExprResult SelfExpr = 2860 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2861 /*HasTrailingLParen=*/false, 2862 /*IsAddressOfOperand=*/false); 2863 if (SelfExpr.isInvalid()) 2864 return ExprError(); 2865 2866 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2867 if (SelfExpr.isInvalid()) 2868 return ExprError(); 2869 2870 MarkAnyDeclReferenced(Loc, IV, true); 2871 2872 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2873 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2874 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2875 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2876 2877 ObjCIvarRefExpr *Result = new (Context) 2878 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2879 IV->getLocation(), SelfExpr.get(), true, true); 2880 2881 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2882 if (!isUnevaluatedContext() && 2883 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2884 getCurFunction()->recordUseOfWeak(Result); 2885 } 2886 if (getLangOpts().ObjCAutoRefCount) 2887 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2888 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2889 2890 return Result; 2891 } 2892 2893 /// The parser has read a name in, and Sema has detected that we're currently 2894 /// inside an ObjC method. Perform some additional checks and determine if we 2895 /// should form a reference to an ivar. If so, build an expression referencing 2896 /// that ivar. 2897 ExprResult 2898 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2899 IdentifierInfo *II, bool AllowBuiltinCreation) { 2900 // FIXME: Integrate this lookup step into LookupParsedName. 2901 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2902 if (Ivar.isInvalid()) 2903 return ExprError(); 2904 if (Ivar.isUsable()) 2905 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2906 cast<ObjCIvarDecl>(Ivar.get())); 2907 2908 if (Lookup.empty() && II && AllowBuiltinCreation) 2909 LookupBuiltin(Lookup); 2910 2911 // Sentinel value saying that we didn't do anything special. 2912 return ExprResult(false); 2913 } 2914 2915 /// Cast a base object to a member's actual type. 2916 /// 2917 /// There are two relevant checks: 2918 /// 2919 /// C++ [class.access.base]p7: 2920 /// 2921 /// If a class member access operator [...] is used to access a non-static 2922 /// data member or non-static member function, the reference is ill-formed if 2923 /// the left operand [...] cannot be implicitly converted to a pointer to the 2924 /// naming class of the right operand. 2925 /// 2926 /// C++ [expr.ref]p7: 2927 /// 2928 /// If E2 is a non-static data member or a non-static member function, the 2929 /// program is ill-formed if the class of which E2 is directly a member is an 2930 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2931 /// 2932 /// Note that the latter check does not consider access; the access of the 2933 /// "real" base class is checked as appropriate when checking the access of the 2934 /// member name. 2935 ExprResult 2936 Sema::PerformObjectMemberConversion(Expr *From, 2937 NestedNameSpecifier *Qualifier, 2938 NamedDecl *FoundDecl, 2939 NamedDecl *Member) { 2940 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2941 if (!RD) 2942 return From; 2943 2944 QualType DestRecordType; 2945 QualType DestType; 2946 QualType FromRecordType; 2947 QualType FromType = From->getType(); 2948 bool PointerConversions = false; 2949 if (isa<FieldDecl>(Member)) { 2950 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2951 auto FromPtrType = FromType->getAs<PointerType>(); 2952 DestRecordType = Context.getAddrSpaceQualType( 2953 DestRecordType, FromPtrType 2954 ? FromType->getPointeeType().getAddressSpace() 2955 : FromType.getAddressSpace()); 2956 2957 if (FromPtrType) { 2958 DestType = Context.getPointerType(DestRecordType); 2959 FromRecordType = FromPtrType->getPointeeType(); 2960 PointerConversions = true; 2961 } else { 2962 DestType = DestRecordType; 2963 FromRecordType = FromType; 2964 } 2965 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2966 if (Method->isStatic()) 2967 return From; 2968 2969 DestType = Method->getThisType(); 2970 DestRecordType = DestType->getPointeeType(); 2971 2972 if (FromType->getAs<PointerType>()) { 2973 FromRecordType = FromType->getPointeeType(); 2974 PointerConversions = true; 2975 } else { 2976 FromRecordType = FromType; 2977 DestType = DestRecordType; 2978 } 2979 2980 LangAS FromAS = FromRecordType.getAddressSpace(); 2981 LangAS DestAS = DestRecordType.getAddressSpace(); 2982 if (FromAS != DestAS) { 2983 QualType FromRecordTypeWithoutAS = 2984 Context.removeAddrSpaceQualType(FromRecordType); 2985 QualType FromTypeWithDestAS = 2986 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2987 if (PointerConversions) 2988 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2989 From = ImpCastExprToType(From, FromTypeWithDestAS, 2990 CK_AddressSpaceConversion, From->getValueKind()) 2991 .get(); 2992 } 2993 } else { 2994 // No conversion necessary. 2995 return From; 2996 } 2997 2998 if (DestType->isDependentType() || FromType->isDependentType()) 2999 return From; 3000 3001 // If the unqualified types are the same, no conversion is necessary. 3002 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3003 return From; 3004 3005 SourceRange FromRange = From->getSourceRange(); 3006 SourceLocation FromLoc = FromRange.getBegin(); 3007 3008 ExprValueKind VK = From->getValueKind(); 3009 3010 // C++ [class.member.lookup]p8: 3011 // [...] Ambiguities can often be resolved by qualifying a name with its 3012 // class name. 3013 // 3014 // If the member was a qualified name and the qualified referred to a 3015 // specific base subobject type, we'll cast to that intermediate type 3016 // first and then to the object in which the member is declared. That allows 3017 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3018 // 3019 // class Base { public: int x; }; 3020 // class Derived1 : public Base { }; 3021 // class Derived2 : public Base { }; 3022 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3023 // 3024 // void VeryDerived::f() { 3025 // x = 17; // error: ambiguous base subobjects 3026 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3027 // } 3028 if (Qualifier && Qualifier->getAsType()) { 3029 QualType QType = QualType(Qualifier->getAsType(), 0); 3030 assert(QType->isRecordType() && "lookup done with non-record type"); 3031 3032 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3033 3034 // In C++98, the qualifier type doesn't actually have to be a base 3035 // type of the object type, in which case we just ignore it. 3036 // Otherwise build the appropriate casts. 3037 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3038 CXXCastPath BasePath; 3039 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3040 FromLoc, FromRange, &BasePath)) 3041 return ExprError(); 3042 3043 if (PointerConversions) 3044 QType = Context.getPointerType(QType); 3045 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3046 VK, &BasePath).get(); 3047 3048 FromType = QType; 3049 FromRecordType = QRecordType; 3050 3051 // If the qualifier type was the same as the destination type, 3052 // we're done. 3053 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3054 return From; 3055 } 3056 } 3057 3058 CXXCastPath BasePath; 3059 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3060 FromLoc, FromRange, &BasePath, 3061 /*IgnoreAccess=*/true)) 3062 return ExprError(); 3063 3064 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3065 VK, &BasePath); 3066 } 3067 3068 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3069 const LookupResult &R, 3070 bool HasTrailingLParen) { 3071 // Only when used directly as the postfix-expression of a call. 3072 if (!HasTrailingLParen) 3073 return false; 3074 3075 // Never if a scope specifier was provided. 3076 if (SS.isSet()) 3077 return false; 3078 3079 // Only in C++ or ObjC++. 3080 if (!getLangOpts().CPlusPlus) 3081 return false; 3082 3083 // Turn off ADL when we find certain kinds of declarations during 3084 // normal lookup: 3085 for (NamedDecl *D : R) { 3086 // C++0x [basic.lookup.argdep]p3: 3087 // -- a declaration of a class member 3088 // Since using decls preserve this property, we check this on the 3089 // original decl. 3090 if (D->isCXXClassMember()) 3091 return false; 3092 3093 // C++0x [basic.lookup.argdep]p3: 3094 // -- a block-scope function declaration that is not a 3095 // using-declaration 3096 // NOTE: we also trigger this for function templates (in fact, we 3097 // don't check the decl type at all, since all other decl types 3098 // turn off ADL anyway). 3099 if (isa<UsingShadowDecl>(D)) 3100 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3101 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3102 return false; 3103 3104 // C++0x [basic.lookup.argdep]p3: 3105 // -- a declaration that is neither a function or a function 3106 // template 3107 // And also for builtin functions. 3108 if (isa<FunctionDecl>(D)) { 3109 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3110 3111 // But also builtin functions. 3112 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3113 return false; 3114 } else if (!isa<FunctionTemplateDecl>(D)) 3115 return false; 3116 } 3117 3118 return true; 3119 } 3120 3121 3122 /// Diagnoses obvious problems with the use of the given declaration 3123 /// as an expression. This is only actually called for lookups that 3124 /// were not overloaded, and it doesn't promise that the declaration 3125 /// will in fact be used. 3126 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3127 if (D->isInvalidDecl()) 3128 return true; 3129 3130 if (isa<TypedefNameDecl>(D)) { 3131 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3132 return true; 3133 } 3134 3135 if (isa<ObjCInterfaceDecl>(D)) { 3136 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3137 return true; 3138 } 3139 3140 if (isa<NamespaceDecl>(D)) { 3141 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3142 return true; 3143 } 3144 3145 return false; 3146 } 3147 3148 // Certain multiversion types should be treated as overloaded even when there is 3149 // only one result. 3150 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3151 assert(R.isSingleResult() && "Expected only a single result"); 3152 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3153 return FD && 3154 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3155 } 3156 3157 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3158 LookupResult &R, bool NeedsADL, 3159 bool AcceptInvalidDecl) { 3160 // If this is a single, fully-resolved result and we don't need ADL, 3161 // just build an ordinary singleton decl ref. 3162 if (!NeedsADL && R.isSingleResult() && 3163 !R.getAsSingle<FunctionTemplateDecl>() && 3164 !ShouldLookupResultBeMultiVersionOverload(R)) 3165 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3166 R.getRepresentativeDecl(), nullptr, 3167 AcceptInvalidDecl); 3168 3169 // We only need to check the declaration if there's exactly one 3170 // result, because in the overloaded case the results can only be 3171 // functions and function templates. 3172 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3173 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3174 return ExprError(); 3175 3176 // Otherwise, just build an unresolved lookup expression. Suppress 3177 // any lookup-related diagnostics; we'll hash these out later, when 3178 // we've picked a target. 3179 R.suppressDiagnostics(); 3180 3181 UnresolvedLookupExpr *ULE 3182 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3183 SS.getWithLocInContext(Context), 3184 R.getLookupNameInfo(), 3185 NeedsADL, R.isOverloadedResult(), 3186 R.begin(), R.end()); 3187 3188 return ULE; 3189 } 3190 3191 static void 3192 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3193 ValueDecl *var, DeclContext *DC); 3194 3195 /// Complete semantic analysis for a reference to the given declaration. 3196 ExprResult Sema::BuildDeclarationNameExpr( 3197 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3198 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3199 bool AcceptInvalidDecl) { 3200 assert(D && "Cannot refer to a NULL declaration"); 3201 assert(!isa<FunctionTemplateDecl>(D) && 3202 "Cannot refer unambiguously to a function template"); 3203 3204 SourceLocation Loc = NameInfo.getLoc(); 3205 if (CheckDeclInExpr(*this, Loc, D)) 3206 return ExprError(); 3207 3208 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3209 // Specifically diagnose references to class templates that are missing 3210 // a template argument list. 3211 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3212 return ExprError(); 3213 } 3214 3215 // Make sure that we're referring to a value. 3216 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3217 if (!VD) { 3218 Diag(Loc, diag::err_ref_non_value) 3219 << D << SS.getRange(); 3220 Diag(D->getLocation(), diag::note_declared_at); 3221 return ExprError(); 3222 } 3223 3224 // Check whether this declaration can be used. Note that we suppress 3225 // this check when we're going to perform argument-dependent lookup 3226 // on this function name, because this might not be the function 3227 // that overload resolution actually selects. 3228 if (DiagnoseUseOfDecl(VD, Loc)) 3229 return ExprError(); 3230 3231 // Only create DeclRefExpr's for valid Decl's. 3232 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3233 return ExprError(); 3234 3235 // Handle members of anonymous structs and unions. If we got here, 3236 // and the reference is to a class member indirect field, then this 3237 // must be the subject of a pointer-to-member expression. 3238 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3239 if (!indirectField->isCXXClassMember()) 3240 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3241 indirectField); 3242 3243 { 3244 QualType type = VD->getType(); 3245 if (type.isNull()) 3246 return ExprError(); 3247 ExprValueKind valueKind = VK_RValue; 3248 3249 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3250 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3251 // is expanded by some outer '...' in the context of the use. 3252 type = type.getNonPackExpansionType(); 3253 3254 switch (D->getKind()) { 3255 // Ignore all the non-ValueDecl kinds. 3256 #define ABSTRACT_DECL(kind) 3257 #define VALUE(type, base) 3258 #define DECL(type, base) \ 3259 case Decl::type: 3260 #include "clang/AST/DeclNodes.inc" 3261 llvm_unreachable("invalid value decl kind"); 3262 3263 // These shouldn't make it here. 3264 case Decl::ObjCAtDefsField: 3265 llvm_unreachable("forming non-member reference to ivar?"); 3266 3267 // Enum constants are always r-values and never references. 3268 // Unresolved using declarations are dependent. 3269 case Decl::EnumConstant: 3270 case Decl::UnresolvedUsingValue: 3271 case Decl::OMPDeclareReduction: 3272 case Decl::OMPDeclareMapper: 3273 valueKind = VK_RValue; 3274 break; 3275 3276 // Fields and indirect fields that got here must be for 3277 // pointer-to-member expressions; we just call them l-values for 3278 // internal consistency, because this subexpression doesn't really 3279 // exist in the high-level semantics. 3280 case Decl::Field: 3281 case Decl::IndirectField: 3282 case Decl::ObjCIvar: 3283 assert(getLangOpts().CPlusPlus && 3284 "building reference to field in C?"); 3285 3286 // These can't have reference type in well-formed programs, but 3287 // for internal consistency we do this anyway. 3288 type = type.getNonReferenceType(); 3289 valueKind = VK_LValue; 3290 break; 3291 3292 // Non-type template parameters are either l-values or r-values 3293 // depending on the type. 3294 case Decl::NonTypeTemplateParm: { 3295 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3296 type = reftype->getPointeeType(); 3297 valueKind = VK_LValue; // even if the parameter is an r-value reference 3298 break; 3299 } 3300 3301 // [expr.prim.id.unqual]p2: 3302 // If the entity is a template parameter object for a template 3303 // parameter of type T, the type of the expression is const T. 3304 // [...] The expression is an lvalue if the entity is a [...] template 3305 // parameter object. 3306 if (type->isRecordType()) { 3307 type = type.getUnqualifiedType().withConst(); 3308 valueKind = VK_LValue; 3309 break; 3310 } 3311 3312 // For non-references, we need to strip qualifiers just in case 3313 // the template parameter was declared as 'const int' or whatever. 3314 valueKind = VK_RValue; 3315 type = type.getUnqualifiedType(); 3316 break; 3317 } 3318 3319 case Decl::Var: 3320 case Decl::VarTemplateSpecialization: 3321 case Decl::VarTemplatePartialSpecialization: 3322 case Decl::Decomposition: 3323 case Decl::OMPCapturedExpr: 3324 // In C, "extern void blah;" is valid and is an r-value. 3325 if (!getLangOpts().CPlusPlus && 3326 !type.hasQualifiers() && 3327 type->isVoidType()) { 3328 valueKind = VK_RValue; 3329 break; 3330 } 3331 LLVM_FALLTHROUGH; 3332 3333 case Decl::ImplicitParam: 3334 case Decl::ParmVar: { 3335 // These are always l-values. 3336 valueKind = VK_LValue; 3337 type = type.getNonReferenceType(); 3338 3339 // FIXME: Does the addition of const really only apply in 3340 // potentially-evaluated contexts? Since the variable isn't actually 3341 // captured in an unevaluated context, it seems that the answer is no. 3342 if (!isUnevaluatedContext()) { 3343 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3344 if (!CapturedType.isNull()) 3345 type = CapturedType; 3346 } 3347 3348 break; 3349 } 3350 3351 case Decl::Binding: { 3352 // These are always lvalues. 3353 valueKind = VK_LValue; 3354 type = type.getNonReferenceType(); 3355 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3356 // decides how that's supposed to work. 3357 auto *BD = cast<BindingDecl>(VD); 3358 if (BD->getDeclContext() != CurContext) { 3359 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3360 if (DD && DD->hasLocalStorage()) 3361 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3362 } 3363 break; 3364 } 3365 3366 case Decl::Function: { 3367 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3368 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3369 type = Context.BuiltinFnTy; 3370 valueKind = VK_RValue; 3371 break; 3372 } 3373 } 3374 3375 const FunctionType *fty = type->castAs<FunctionType>(); 3376 3377 // If we're referring to a function with an __unknown_anytype 3378 // result type, make the entire expression __unknown_anytype. 3379 if (fty->getReturnType() == Context.UnknownAnyTy) { 3380 type = Context.UnknownAnyTy; 3381 valueKind = VK_RValue; 3382 break; 3383 } 3384 3385 // Functions are l-values in C++. 3386 if (getLangOpts().CPlusPlus) { 3387 valueKind = VK_LValue; 3388 break; 3389 } 3390 3391 // C99 DR 316 says that, if a function type comes from a 3392 // function definition (without a prototype), that type is only 3393 // used for checking compatibility. Therefore, when referencing 3394 // the function, we pretend that we don't have the full function 3395 // type. 3396 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3397 isa<FunctionProtoType>(fty)) 3398 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3399 fty->getExtInfo()); 3400 3401 // Functions are r-values in C. 3402 valueKind = VK_RValue; 3403 break; 3404 } 3405 3406 case Decl::CXXDeductionGuide: 3407 llvm_unreachable("building reference to deduction guide"); 3408 3409 case Decl::MSProperty: 3410 case Decl::MSGuid: 3411 case Decl::TemplateParamObject: 3412 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3413 // capture in OpenMP, or duplicated between host and device? 3414 valueKind = VK_LValue; 3415 break; 3416 3417 case Decl::CXXMethod: 3418 // If we're referring to a method with an __unknown_anytype 3419 // result type, make the entire expression __unknown_anytype. 3420 // This should only be possible with a type written directly. 3421 if (const FunctionProtoType *proto 3422 = dyn_cast<FunctionProtoType>(VD->getType())) 3423 if (proto->getReturnType() == Context.UnknownAnyTy) { 3424 type = Context.UnknownAnyTy; 3425 valueKind = VK_RValue; 3426 break; 3427 } 3428 3429 // C++ methods are l-values if static, r-values if non-static. 3430 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3431 valueKind = VK_LValue; 3432 break; 3433 } 3434 LLVM_FALLTHROUGH; 3435 3436 case Decl::CXXConversion: 3437 case Decl::CXXDestructor: 3438 case Decl::CXXConstructor: 3439 valueKind = VK_RValue; 3440 break; 3441 } 3442 3443 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3444 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3445 TemplateArgs); 3446 } 3447 } 3448 3449 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3450 SmallString<32> &Target) { 3451 Target.resize(CharByteWidth * (Source.size() + 1)); 3452 char *ResultPtr = &Target[0]; 3453 const llvm::UTF8 *ErrorPtr; 3454 bool success = 3455 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3456 (void)success; 3457 assert(success); 3458 Target.resize(ResultPtr - &Target[0]); 3459 } 3460 3461 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3462 PredefinedExpr::IdentKind IK) { 3463 // Pick the current block, lambda, captured statement or function. 3464 Decl *currentDecl = nullptr; 3465 if (const BlockScopeInfo *BSI = getCurBlock()) 3466 currentDecl = BSI->TheDecl; 3467 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3468 currentDecl = LSI->CallOperator; 3469 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3470 currentDecl = CSI->TheCapturedDecl; 3471 else 3472 currentDecl = getCurFunctionOrMethodDecl(); 3473 3474 if (!currentDecl) { 3475 Diag(Loc, diag::ext_predef_outside_function); 3476 currentDecl = Context.getTranslationUnitDecl(); 3477 } 3478 3479 QualType ResTy; 3480 StringLiteral *SL = nullptr; 3481 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3482 ResTy = Context.DependentTy; 3483 else { 3484 // Pre-defined identifiers are of type char[x], where x is the length of 3485 // the string. 3486 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3487 unsigned Length = Str.length(); 3488 3489 llvm::APInt LengthI(32, Length + 1); 3490 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3491 ResTy = 3492 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3493 SmallString<32> RawChars; 3494 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3495 Str, RawChars); 3496 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3497 ArrayType::Normal, 3498 /*IndexTypeQuals*/ 0); 3499 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3500 /*Pascal*/ false, ResTy, Loc); 3501 } else { 3502 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3503 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3504 ArrayType::Normal, 3505 /*IndexTypeQuals*/ 0); 3506 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3507 /*Pascal*/ false, ResTy, Loc); 3508 } 3509 } 3510 3511 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3512 } 3513 3514 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3515 PredefinedExpr::IdentKind IK; 3516 3517 switch (Kind) { 3518 default: llvm_unreachable("Unknown simple primary expr!"); 3519 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3520 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3521 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3522 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3523 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3524 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3525 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3526 } 3527 3528 return BuildPredefinedExpr(Loc, IK); 3529 } 3530 3531 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3532 SmallString<16> CharBuffer; 3533 bool Invalid = false; 3534 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3535 if (Invalid) 3536 return ExprError(); 3537 3538 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3539 PP, Tok.getKind()); 3540 if (Literal.hadError()) 3541 return ExprError(); 3542 3543 QualType Ty; 3544 if (Literal.isWide()) 3545 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3546 else if (Literal.isUTF8() && getLangOpts().Char8) 3547 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3548 else if (Literal.isUTF16()) 3549 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3550 else if (Literal.isUTF32()) 3551 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3552 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3553 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3554 else 3555 Ty = Context.CharTy; // 'x' -> char in C++ 3556 3557 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3558 if (Literal.isWide()) 3559 Kind = CharacterLiteral::Wide; 3560 else if (Literal.isUTF16()) 3561 Kind = CharacterLiteral::UTF16; 3562 else if (Literal.isUTF32()) 3563 Kind = CharacterLiteral::UTF32; 3564 else if (Literal.isUTF8()) 3565 Kind = CharacterLiteral::UTF8; 3566 3567 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3568 Tok.getLocation()); 3569 3570 if (Literal.getUDSuffix().empty()) 3571 return Lit; 3572 3573 // We're building a user-defined literal. 3574 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3575 SourceLocation UDSuffixLoc = 3576 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3577 3578 // Make sure we're allowed user-defined literals here. 3579 if (!UDLScope) 3580 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3581 3582 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3583 // operator "" X (ch) 3584 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3585 Lit, Tok.getLocation()); 3586 } 3587 3588 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3589 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3590 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3591 Context.IntTy, Loc); 3592 } 3593 3594 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3595 QualType Ty, SourceLocation Loc) { 3596 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3597 3598 using llvm::APFloat; 3599 APFloat Val(Format); 3600 3601 APFloat::opStatus result = Literal.GetFloatValue(Val); 3602 3603 // Overflow is always an error, but underflow is only an error if 3604 // we underflowed to zero (APFloat reports denormals as underflow). 3605 if ((result & APFloat::opOverflow) || 3606 ((result & APFloat::opUnderflow) && Val.isZero())) { 3607 unsigned diagnostic; 3608 SmallString<20> buffer; 3609 if (result & APFloat::opOverflow) { 3610 diagnostic = diag::warn_float_overflow; 3611 APFloat::getLargest(Format).toString(buffer); 3612 } else { 3613 diagnostic = diag::warn_float_underflow; 3614 APFloat::getSmallest(Format).toString(buffer); 3615 } 3616 3617 S.Diag(Loc, diagnostic) 3618 << Ty 3619 << StringRef(buffer.data(), buffer.size()); 3620 } 3621 3622 bool isExact = (result == APFloat::opOK); 3623 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3624 } 3625 3626 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3627 assert(E && "Invalid expression"); 3628 3629 if (E->isValueDependent()) 3630 return false; 3631 3632 QualType QT = E->getType(); 3633 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3634 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3635 return true; 3636 } 3637 3638 llvm::APSInt ValueAPS; 3639 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3640 3641 if (R.isInvalid()) 3642 return true; 3643 3644 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3645 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3646 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3647 << ValueAPS.toString(10) << ValueIsPositive; 3648 return true; 3649 } 3650 3651 return false; 3652 } 3653 3654 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3655 // Fast path for a single digit (which is quite common). A single digit 3656 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3657 if (Tok.getLength() == 1) { 3658 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3659 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3660 } 3661 3662 SmallString<128> SpellingBuffer; 3663 // NumericLiteralParser wants to overread by one character. Add padding to 3664 // the buffer in case the token is copied to the buffer. If getSpelling() 3665 // returns a StringRef to the memory buffer, it should have a null char at 3666 // the EOF, so it is also safe. 3667 SpellingBuffer.resize(Tok.getLength() + 1); 3668 3669 // Get the spelling of the token, which eliminates trigraphs, etc. 3670 bool Invalid = false; 3671 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3672 if (Invalid) 3673 return ExprError(); 3674 3675 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3676 PP.getSourceManager(), PP.getLangOpts(), 3677 PP.getTargetInfo(), PP.getDiagnostics()); 3678 if (Literal.hadError) 3679 return ExprError(); 3680 3681 if (Literal.hasUDSuffix()) { 3682 // We're building a user-defined literal. 3683 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3684 SourceLocation UDSuffixLoc = 3685 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3686 3687 // Make sure we're allowed user-defined literals here. 3688 if (!UDLScope) 3689 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3690 3691 QualType CookedTy; 3692 if (Literal.isFloatingLiteral()) { 3693 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3694 // long double, the literal is treated as a call of the form 3695 // operator "" X (f L) 3696 CookedTy = Context.LongDoubleTy; 3697 } else { 3698 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3699 // unsigned long long, the literal is treated as a call of the form 3700 // operator "" X (n ULL) 3701 CookedTy = Context.UnsignedLongLongTy; 3702 } 3703 3704 DeclarationName OpName = 3705 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3706 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3707 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3708 3709 SourceLocation TokLoc = Tok.getLocation(); 3710 3711 // Perform literal operator lookup to determine if we're building a raw 3712 // literal or a cooked one. 3713 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3714 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3715 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3716 /*AllowStringTemplatePack*/ false, 3717 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3718 case LOLR_ErrorNoDiagnostic: 3719 // Lookup failure for imaginary constants isn't fatal, there's still the 3720 // GNU extension producing _Complex types. 3721 break; 3722 case LOLR_Error: 3723 return ExprError(); 3724 case LOLR_Cooked: { 3725 Expr *Lit; 3726 if (Literal.isFloatingLiteral()) { 3727 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3728 } else { 3729 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3730 if (Literal.GetIntegerValue(ResultVal)) 3731 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3732 << /* Unsigned */ 1; 3733 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3734 Tok.getLocation()); 3735 } 3736 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3737 } 3738 3739 case LOLR_Raw: { 3740 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3741 // literal is treated as a call of the form 3742 // operator "" X ("n") 3743 unsigned Length = Literal.getUDSuffixOffset(); 3744 QualType StrTy = Context.getConstantArrayType( 3745 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3746 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3747 Expr *Lit = StringLiteral::Create( 3748 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3749 /*Pascal*/false, StrTy, &TokLoc, 1); 3750 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3751 } 3752 3753 case LOLR_Template: { 3754 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3755 // template), L is treated as a call fo the form 3756 // operator "" X <'c1', 'c2', ... 'ck'>() 3757 // where n is the source character sequence c1 c2 ... ck. 3758 TemplateArgumentListInfo ExplicitArgs; 3759 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3760 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3761 llvm::APSInt Value(CharBits, CharIsUnsigned); 3762 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3763 Value = TokSpelling[I]; 3764 TemplateArgument Arg(Context, Value, Context.CharTy); 3765 TemplateArgumentLocInfo ArgInfo; 3766 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3767 } 3768 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3769 &ExplicitArgs); 3770 } 3771 case LOLR_StringTemplatePack: 3772 llvm_unreachable("unexpected literal operator lookup result"); 3773 } 3774 } 3775 3776 Expr *Res; 3777 3778 if (Literal.isFixedPointLiteral()) { 3779 QualType Ty; 3780 3781 if (Literal.isAccum) { 3782 if (Literal.isHalf) { 3783 Ty = Context.ShortAccumTy; 3784 } else if (Literal.isLong) { 3785 Ty = Context.LongAccumTy; 3786 } else { 3787 Ty = Context.AccumTy; 3788 } 3789 } else if (Literal.isFract) { 3790 if (Literal.isHalf) { 3791 Ty = Context.ShortFractTy; 3792 } else if (Literal.isLong) { 3793 Ty = Context.LongFractTy; 3794 } else { 3795 Ty = Context.FractTy; 3796 } 3797 } 3798 3799 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3800 3801 bool isSigned = !Literal.isUnsigned; 3802 unsigned scale = Context.getFixedPointScale(Ty); 3803 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3804 3805 llvm::APInt Val(bit_width, 0, isSigned); 3806 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3807 bool ValIsZero = Val.isNullValue() && !Overflowed; 3808 3809 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3810 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3811 // Clause 6.4.4 - The value of a constant shall be in the range of 3812 // representable values for its type, with exception for constants of a 3813 // fract type with a value of exactly 1; such a constant shall denote 3814 // the maximal value for the type. 3815 --Val; 3816 else if (Val.ugt(MaxVal) || Overflowed) 3817 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3818 3819 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3820 Tok.getLocation(), scale); 3821 } else if (Literal.isFloatingLiteral()) { 3822 QualType Ty; 3823 if (Literal.isHalf){ 3824 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3825 Ty = Context.HalfTy; 3826 else { 3827 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3828 return ExprError(); 3829 } 3830 } else if (Literal.isFloat) 3831 Ty = Context.FloatTy; 3832 else if (Literal.isLong) 3833 Ty = Context.LongDoubleTy; 3834 else if (Literal.isFloat16) 3835 Ty = Context.Float16Ty; 3836 else if (Literal.isFloat128) 3837 Ty = Context.Float128Ty; 3838 else 3839 Ty = Context.DoubleTy; 3840 3841 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3842 3843 if (Ty == Context.DoubleTy) { 3844 if (getLangOpts().SinglePrecisionConstants) { 3845 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3846 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3847 } 3848 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3849 "cl_khr_fp64", getLangOpts())) { 3850 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3851 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3852 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3853 } 3854 } 3855 } else if (!Literal.isIntegerLiteral()) { 3856 return ExprError(); 3857 } else { 3858 QualType Ty; 3859 3860 // 'long long' is a C99 or C++11 feature. 3861 if (!getLangOpts().C99 && Literal.isLongLong) { 3862 if (getLangOpts().CPlusPlus) 3863 Diag(Tok.getLocation(), 3864 getLangOpts().CPlusPlus11 ? 3865 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3866 else 3867 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3868 } 3869 3870 // Get the value in the widest-possible width. 3871 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3872 llvm::APInt ResultVal(MaxWidth, 0); 3873 3874 if (Literal.GetIntegerValue(ResultVal)) { 3875 // If this value didn't fit into uintmax_t, error and force to ull. 3876 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3877 << /* Unsigned */ 1; 3878 Ty = Context.UnsignedLongLongTy; 3879 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3880 "long long is not intmax_t?"); 3881 } else { 3882 // If this value fits into a ULL, try to figure out what else it fits into 3883 // according to the rules of C99 6.4.4.1p5. 3884 3885 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3886 // be an unsigned int. 3887 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3888 3889 // Check from smallest to largest, picking the smallest type we can. 3890 unsigned Width = 0; 3891 3892 // Microsoft specific integer suffixes are explicitly sized. 3893 if (Literal.MicrosoftInteger) { 3894 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3895 Width = 8; 3896 Ty = Context.CharTy; 3897 } else { 3898 Width = Literal.MicrosoftInteger; 3899 Ty = Context.getIntTypeForBitwidth(Width, 3900 /*Signed=*/!Literal.isUnsigned); 3901 } 3902 } 3903 3904 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3905 // Are int/unsigned possibilities? 3906 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3907 3908 // Does it fit in a unsigned int? 3909 if (ResultVal.isIntN(IntSize)) { 3910 // Does it fit in a signed int? 3911 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3912 Ty = Context.IntTy; 3913 else if (AllowUnsigned) 3914 Ty = Context.UnsignedIntTy; 3915 Width = IntSize; 3916 } 3917 } 3918 3919 // Are long/unsigned long possibilities? 3920 if (Ty.isNull() && !Literal.isLongLong) { 3921 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3922 3923 // Does it fit in a unsigned long? 3924 if (ResultVal.isIntN(LongSize)) { 3925 // Does it fit in a signed long? 3926 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3927 Ty = Context.LongTy; 3928 else if (AllowUnsigned) 3929 Ty = Context.UnsignedLongTy; 3930 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3931 // is compatible. 3932 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3933 const unsigned LongLongSize = 3934 Context.getTargetInfo().getLongLongWidth(); 3935 Diag(Tok.getLocation(), 3936 getLangOpts().CPlusPlus 3937 ? Literal.isLong 3938 ? diag::warn_old_implicitly_unsigned_long_cxx 3939 : /*C++98 UB*/ diag:: 3940 ext_old_implicitly_unsigned_long_cxx 3941 : diag::warn_old_implicitly_unsigned_long) 3942 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3943 : /*will be ill-formed*/ 1); 3944 Ty = Context.UnsignedLongTy; 3945 } 3946 Width = LongSize; 3947 } 3948 } 3949 3950 // Check long long if needed. 3951 if (Ty.isNull()) { 3952 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3953 3954 // Does it fit in a unsigned long long? 3955 if (ResultVal.isIntN(LongLongSize)) { 3956 // Does it fit in a signed long long? 3957 // To be compatible with MSVC, hex integer literals ending with the 3958 // LL or i64 suffix are always signed in Microsoft mode. 3959 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3960 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3961 Ty = Context.LongLongTy; 3962 else if (AllowUnsigned) 3963 Ty = Context.UnsignedLongLongTy; 3964 Width = LongLongSize; 3965 } 3966 } 3967 3968 // If we still couldn't decide a type, we probably have something that 3969 // does not fit in a signed long long, but has no U suffix. 3970 if (Ty.isNull()) { 3971 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3972 Ty = Context.UnsignedLongLongTy; 3973 Width = Context.getTargetInfo().getLongLongWidth(); 3974 } 3975 3976 if (ResultVal.getBitWidth() != Width) 3977 ResultVal = ResultVal.trunc(Width); 3978 } 3979 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3980 } 3981 3982 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3983 if (Literal.isImaginary) { 3984 Res = new (Context) ImaginaryLiteral(Res, 3985 Context.getComplexType(Res->getType())); 3986 3987 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3988 } 3989 return Res; 3990 } 3991 3992 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3993 assert(E && "ActOnParenExpr() missing expr"); 3994 return new (Context) ParenExpr(L, R, E); 3995 } 3996 3997 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3998 SourceLocation Loc, 3999 SourceRange ArgRange) { 4000 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4001 // scalar or vector data type argument..." 4002 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4003 // type (C99 6.2.5p18) or void. 4004 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4005 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4006 << T << ArgRange; 4007 return true; 4008 } 4009 4010 assert((T->isVoidType() || !T->isIncompleteType()) && 4011 "Scalar types should always be complete"); 4012 return false; 4013 } 4014 4015 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4016 SourceLocation Loc, 4017 SourceRange ArgRange, 4018 UnaryExprOrTypeTrait TraitKind) { 4019 // Invalid types must be hard errors for SFINAE in C++. 4020 if (S.LangOpts.CPlusPlus) 4021 return true; 4022 4023 // C99 6.5.3.4p1: 4024 if (T->isFunctionType() && 4025 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4026 TraitKind == UETT_PreferredAlignOf)) { 4027 // sizeof(function)/alignof(function) is allowed as an extension. 4028 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4029 << getTraitSpelling(TraitKind) << ArgRange; 4030 return false; 4031 } 4032 4033 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4034 // this is an error (OpenCL v1.1 s6.3.k) 4035 if (T->isVoidType()) { 4036 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4037 : diag::ext_sizeof_alignof_void_type; 4038 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4039 return false; 4040 } 4041 4042 return true; 4043 } 4044 4045 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4046 SourceLocation Loc, 4047 SourceRange ArgRange, 4048 UnaryExprOrTypeTrait TraitKind) { 4049 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4050 // runtime doesn't allow it. 4051 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4052 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4053 << T << (TraitKind == UETT_SizeOf) 4054 << ArgRange; 4055 return true; 4056 } 4057 4058 return false; 4059 } 4060 4061 /// Check whether E is a pointer from a decayed array type (the decayed 4062 /// pointer type is equal to T) and emit a warning if it is. 4063 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4064 Expr *E) { 4065 // Don't warn if the operation changed the type. 4066 if (T != E->getType()) 4067 return; 4068 4069 // Now look for array decays. 4070 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4071 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4072 return; 4073 4074 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4075 << ICE->getType() 4076 << ICE->getSubExpr()->getType(); 4077 } 4078 4079 /// Check the constraints on expression operands to unary type expression 4080 /// and type traits. 4081 /// 4082 /// Completes any types necessary and validates the constraints on the operand 4083 /// expression. The logic mostly mirrors the type-based overload, but may modify 4084 /// the expression as it completes the type for that expression through template 4085 /// instantiation, etc. 4086 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4087 UnaryExprOrTypeTrait ExprKind) { 4088 QualType ExprTy = E->getType(); 4089 assert(!ExprTy->isReferenceType()); 4090 4091 bool IsUnevaluatedOperand = 4092 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4093 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4094 if (IsUnevaluatedOperand) { 4095 ExprResult Result = CheckUnevaluatedOperand(E); 4096 if (Result.isInvalid()) 4097 return true; 4098 E = Result.get(); 4099 } 4100 4101 // The operand for sizeof and alignof is in an unevaluated expression context, 4102 // so side effects could result in unintended consequences. 4103 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4104 // used to build SFINAE gadgets. 4105 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4106 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4107 !E->isInstantiationDependent() && 4108 E->HasSideEffects(Context, false)) 4109 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4110 4111 if (ExprKind == UETT_VecStep) 4112 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4113 E->getSourceRange()); 4114 4115 // Explicitly list some types as extensions. 4116 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4117 E->getSourceRange(), ExprKind)) 4118 return false; 4119 4120 // 'alignof' applied to an expression only requires the base element type of 4121 // the expression to be complete. 'sizeof' requires the expression's type to 4122 // be complete (and will attempt to complete it if it's an array of unknown 4123 // bound). 4124 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4125 if (RequireCompleteSizedType( 4126 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4127 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4128 getTraitSpelling(ExprKind), E->getSourceRange())) 4129 return true; 4130 } else { 4131 if (RequireCompleteSizedExprType( 4132 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4133 getTraitSpelling(ExprKind), E->getSourceRange())) 4134 return true; 4135 } 4136 4137 // Completing the expression's type may have changed it. 4138 ExprTy = E->getType(); 4139 assert(!ExprTy->isReferenceType()); 4140 4141 if (ExprTy->isFunctionType()) { 4142 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4143 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4144 return true; 4145 } 4146 4147 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4148 E->getSourceRange(), ExprKind)) 4149 return true; 4150 4151 if (ExprKind == UETT_SizeOf) { 4152 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4153 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4154 QualType OType = PVD->getOriginalType(); 4155 QualType Type = PVD->getType(); 4156 if (Type->isPointerType() && OType->isArrayType()) { 4157 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4158 << Type << OType; 4159 Diag(PVD->getLocation(), diag::note_declared_at); 4160 } 4161 } 4162 } 4163 4164 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4165 // decays into a pointer and returns an unintended result. This is most 4166 // likely a typo for "sizeof(array) op x". 4167 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4168 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4169 BO->getLHS()); 4170 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4171 BO->getRHS()); 4172 } 4173 } 4174 4175 return false; 4176 } 4177 4178 /// Check the constraints on operands to unary expression and type 4179 /// traits. 4180 /// 4181 /// This will complete any types necessary, and validate the various constraints 4182 /// on those operands. 4183 /// 4184 /// The UsualUnaryConversions() function is *not* called by this routine. 4185 /// C99 6.3.2.1p[2-4] all state: 4186 /// Except when it is the operand of the sizeof operator ... 4187 /// 4188 /// C++ [expr.sizeof]p4 4189 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4190 /// standard conversions are not applied to the operand of sizeof. 4191 /// 4192 /// This policy is followed for all of the unary trait expressions. 4193 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4194 SourceLocation OpLoc, 4195 SourceRange ExprRange, 4196 UnaryExprOrTypeTrait ExprKind) { 4197 if (ExprType->isDependentType()) 4198 return false; 4199 4200 // C++ [expr.sizeof]p2: 4201 // When applied to a reference or a reference type, the result 4202 // is the size of the referenced type. 4203 // C++11 [expr.alignof]p3: 4204 // When alignof is applied to a reference type, the result 4205 // shall be the alignment of the referenced type. 4206 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4207 ExprType = Ref->getPointeeType(); 4208 4209 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4210 // When alignof or _Alignof is applied to an array type, the result 4211 // is the alignment of the element type. 4212 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4213 ExprKind == UETT_OpenMPRequiredSimdAlign) 4214 ExprType = Context.getBaseElementType(ExprType); 4215 4216 if (ExprKind == UETT_VecStep) 4217 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4218 4219 // Explicitly list some types as extensions. 4220 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4221 ExprKind)) 4222 return false; 4223 4224 if (RequireCompleteSizedType( 4225 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4226 getTraitSpelling(ExprKind), ExprRange)) 4227 return true; 4228 4229 if (ExprType->isFunctionType()) { 4230 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4231 << getTraitSpelling(ExprKind) << ExprRange; 4232 return true; 4233 } 4234 4235 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4236 ExprKind)) 4237 return true; 4238 4239 return false; 4240 } 4241 4242 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4243 // Cannot know anything else if the expression is dependent. 4244 if (E->isTypeDependent()) 4245 return false; 4246 4247 if (E->getObjectKind() == OK_BitField) { 4248 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4249 << 1 << E->getSourceRange(); 4250 return true; 4251 } 4252 4253 ValueDecl *D = nullptr; 4254 Expr *Inner = E->IgnoreParens(); 4255 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4256 D = DRE->getDecl(); 4257 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4258 D = ME->getMemberDecl(); 4259 } 4260 4261 // If it's a field, require the containing struct to have a 4262 // complete definition so that we can compute the layout. 4263 // 4264 // This can happen in C++11 onwards, either by naming the member 4265 // in a way that is not transformed into a member access expression 4266 // (in an unevaluated operand, for instance), or by naming the member 4267 // in a trailing-return-type. 4268 // 4269 // For the record, since __alignof__ on expressions is a GCC 4270 // extension, GCC seems to permit this but always gives the 4271 // nonsensical answer 0. 4272 // 4273 // We don't really need the layout here --- we could instead just 4274 // directly check for all the appropriate alignment-lowing 4275 // attributes --- but that would require duplicating a lot of 4276 // logic that just isn't worth duplicating for such a marginal 4277 // use-case. 4278 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4279 // Fast path this check, since we at least know the record has a 4280 // definition if we can find a member of it. 4281 if (!FD->getParent()->isCompleteDefinition()) { 4282 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4283 << E->getSourceRange(); 4284 return true; 4285 } 4286 4287 // Otherwise, if it's a field, and the field doesn't have 4288 // reference type, then it must have a complete type (or be a 4289 // flexible array member, which we explicitly want to 4290 // white-list anyway), which makes the following checks trivial. 4291 if (!FD->getType()->isReferenceType()) 4292 return false; 4293 } 4294 4295 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4296 } 4297 4298 bool Sema::CheckVecStepExpr(Expr *E) { 4299 E = E->IgnoreParens(); 4300 4301 // Cannot know anything else if the expression is dependent. 4302 if (E->isTypeDependent()) 4303 return false; 4304 4305 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4306 } 4307 4308 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4309 CapturingScopeInfo *CSI) { 4310 assert(T->isVariablyModifiedType()); 4311 assert(CSI != nullptr); 4312 4313 // We're going to walk down into the type and look for VLA expressions. 4314 do { 4315 const Type *Ty = T.getTypePtr(); 4316 switch (Ty->getTypeClass()) { 4317 #define TYPE(Class, Base) 4318 #define ABSTRACT_TYPE(Class, Base) 4319 #define NON_CANONICAL_TYPE(Class, Base) 4320 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4321 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4322 #include "clang/AST/TypeNodes.inc" 4323 T = QualType(); 4324 break; 4325 // These types are never variably-modified. 4326 case Type::Builtin: 4327 case Type::Complex: 4328 case Type::Vector: 4329 case Type::ExtVector: 4330 case Type::ConstantMatrix: 4331 case Type::Record: 4332 case Type::Enum: 4333 case Type::Elaborated: 4334 case Type::TemplateSpecialization: 4335 case Type::ObjCObject: 4336 case Type::ObjCInterface: 4337 case Type::ObjCObjectPointer: 4338 case Type::ObjCTypeParam: 4339 case Type::Pipe: 4340 case Type::ExtInt: 4341 llvm_unreachable("type class is never variably-modified!"); 4342 case Type::Adjusted: 4343 T = cast<AdjustedType>(Ty)->getOriginalType(); 4344 break; 4345 case Type::Decayed: 4346 T = cast<DecayedType>(Ty)->getPointeeType(); 4347 break; 4348 case Type::Pointer: 4349 T = cast<PointerType>(Ty)->getPointeeType(); 4350 break; 4351 case Type::BlockPointer: 4352 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4353 break; 4354 case Type::LValueReference: 4355 case Type::RValueReference: 4356 T = cast<ReferenceType>(Ty)->getPointeeType(); 4357 break; 4358 case Type::MemberPointer: 4359 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4360 break; 4361 case Type::ConstantArray: 4362 case Type::IncompleteArray: 4363 // Losing element qualification here is fine. 4364 T = cast<ArrayType>(Ty)->getElementType(); 4365 break; 4366 case Type::VariableArray: { 4367 // Losing element qualification here is fine. 4368 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4369 4370 // Unknown size indication requires no size computation. 4371 // Otherwise, evaluate and record it. 4372 auto Size = VAT->getSizeExpr(); 4373 if (Size && !CSI->isVLATypeCaptured(VAT) && 4374 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4375 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4376 4377 T = VAT->getElementType(); 4378 break; 4379 } 4380 case Type::FunctionProto: 4381 case Type::FunctionNoProto: 4382 T = cast<FunctionType>(Ty)->getReturnType(); 4383 break; 4384 case Type::Paren: 4385 case Type::TypeOf: 4386 case Type::UnaryTransform: 4387 case Type::Attributed: 4388 case Type::SubstTemplateTypeParm: 4389 case Type::MacroQualified: 4390 // Keep walking after single level desugaring. 4391 T = T.getSingleStepDesugaredType(Context); 4392 break; 4393 case Type::Typedef: 4394 T = cast<TypedefType>(Ty)->desugar(); 4395 break; 4396 case Type::Decltype: 4397 T = cast<DecltypeType>(Ty)->desugar(); 4398 break; 4399 case Type::Auto: 4400 case Type::DeducedTemplateSpecialization: 4401 T = cast<DeducedType>(Ty)->getDeducedType(); 4402 break; 4403 case Type::TypeOfExpr: 4404 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4405 break; 4406 case Type::Atomic: 4407 T = cast<AtomicType>(Ty)->getValueType(); 4408 break; 4409 } 4410 } while (!T.isNull() && T->isVariablyModifiedType()); 4411 } 4412 4413 /// Build a sizeof or alignof expression given a type operand. 4414 ExprResult 4415 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4416 SourceLocation OpLoc, 4417 UnaryExprOrTypeTrait ExprKind, 4418 SourceRange R) { 4419 if (!TInfo) 4420 return ExprError(); 4421 4422 QualType T = TInfo->getType(); 4423 4424 if (!T->isDependentType() && 4425 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4426 return ExprError(); 4427 4428 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4429 if (auto *TT = T->getAs<TypedefType>()) { 4430 for (auto I = FunctionScopes.rbegin(), 4431 E = std::prev(FunctionScopes.rend()); 4432 I != E; ++I) { 4433 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4434 if (CSI == nullptr) 4435 break; 4436 DeclContext *DC = nullptr; 4437 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4438 DC = LSI->CallOperator; 4439 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4440 DC = CRSI->TheCapturedDecl; 4441 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4442 DC = BSI->TheDecl; 4443 if (DC) { 4444 if (DC->containsDecl(TT->getDecl())) 4445 break; 4446 captureVariablyModifiedType(Context, T, CSI); 4447 } 4448 } 4449 } 4450 } 4451 4452 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4453 return new (Context) UnaryExprOrTypeTraitExpr( 4454 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4455 } 4456 4457 /// Build a sizeof or alignof expression given an expression 4458 /// operand. 4459 ExprResult 4460 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4461 UnaryExprOrTypeTrait ExprKind) { 4462 ExprResult PE = CheckPlaceholderExpr(E); 4463 if (PE.isInvalid()) 4464 return ExprError(); 4465 4466 E = PE.get(); 4467 4468 // Verify that the operand is valid. 4469 bool isInvalid = false; 4470 if (E->isTypeDependent()) { 4471 // Delay type-checking for type-dependent expressions. 4472 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4473 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4474 } else if (ExprKind == UETT_VecStep) { 4475 isInvalid = CheckVecStepExpr(E); 4476 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4477 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4478 isInvalid = true; 4479 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4480 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4481 isInvalid = true; 4482 } else { 4483 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4484 } 4485 4486 if (isInvalid) 4487 return ExprError(); 4488 4489 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4490 PE = TransformToPotentiallyEvaluated(E); 4491 if (PE.isInvalid()) return ExprError(); 4492 E = PE.get(); 4493 } 4494 4495 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4496 return new (Context) UnaryExprOrTypeTraitExpr( 4497 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4498 } 4499 4500 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4501 /// expr and the same for @c alignof and @c __alignof 4502 /// Note that the ArgRange is invalid if isType is false. 4503 ExprResult 4504 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4505 UnaryExprOrTypeTrait ExprKind, bool IsType, 4506 void *TyOrEx, SourceRange ArgRange) { 4507 // If error parsing type, ignore. 4508 if (!TyOrEx) return ExprError(); 4509 4510 if (IsType) { 4511 TypeSourceInfo *TInfo; 4512 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4513 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4514 } 4515 4516 Expr *ArgEx = (Expr *)TyOrEx; 4517 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4518 return Result; 4519 } 4520 4521 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4522 bool IsReal) { 4523 if (V.get()->isTypeDependent()) 4524 return S.Context.DependentTy; 4525 4526 // _Real and _Imag are only l-values for normal l-values. 4527 if (V.get()->getObjectKind() != OK_Ordinary) { 4528 V = S.DefaultLvalueConversion(V.get()); 4529 if (V.isInvalid()) 4530 return QualType(); 4531 } 4532 4533 // These operators return the element type of a complex type. 4534 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4535 return CT->getElementType(); 4536 4537 // Otherwise they pass through real integer and floating point types here. 4538 if (V.get()->getType()->isArithmeticType()) 4539 return V.get()->getType(); 4540 4541 // Test for placeholders. 4542 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4543 if (PR.isInvalid()) return QualType(); 4544 if (PR.get() != V.get()) { 4545 V = PR; 4546 return CheckRealImagOperand(S, V, Loc, IsReal); 4547 } 4548 4549 // Reject anything else. 4550 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4551 << (IsReal ? "__real" : "__imag"); 4552 return QualType(); 4553 } 4554 4555 4556 4557 ExprResult 4558 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4559 tok::TokenKind Kind, Expr *Input) { 4560 UnaryOperatorKind Opc; 4561 switch (Kind) { 4562 default: llvm_unreachable("Unknown unary op!"); 4563 case tok::plusplus: Opc = UO_PostInc; break; 4564 case tok::minusminus: Opc = UO_PostDec; break; 4565 } 4566 4567 // Since this might is a postfix expression, get rid of ParenListExprs. 4568 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4569 if (Result.isInvalid()) return ExprError(); 4570 Input = Result.get(); 4571 4572 return BuildUnaryOp(S, OpLoc, Opc, Input); 4573 } 4574 4575 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4576 /// 4577 /// \return true on error 4578 static bool checkArithmeticOnObjCPointer(Sema &S, 4579 SourceLocation opLoc, 4580 Expr *op) { 4581 assert(op->getType()->isObjCObjectPointerType()); 4582 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4583 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4584 return false; 4585 4586 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4587 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4588 << op->getSourceRange(); 4589 return true; 4590 } 4591 4592 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4593 auto *BaseNoParens = Base->IgnoreParens(); 4594 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4595 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4596 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4597 } 4598 4599 ExprResult 4600 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4601 Expr *idx, SourceLocation rbLoc) { 4602 if (base && !base->getType().isNull() && 4603 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4604 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4605 SourceLocation(), /*Length*/ nullptr, 4606 /*Stride=*/nullptr, rbLoc); 4607 4608 // Since this might be a postfix expression, get rid of ParenListExprs. 4609 if (isa<ParenListExpr>(base)) { 4610 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4611 if (result.isInvalid()) return ExprError(); 4612 base = result.get(); 4613 } 4614 4615 // Check if base and idx form a MatrixSubscriptExpr. 4616 // 4617 // Helper to check for comma expressions, which are not allowed as indices for 4618 // matrix subscript expressions. 4619 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4620 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4621 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4622 << SourceRange(base->getBeginLoc(), rbLoc); 4623 return true; 4624 } 4625 return false; 4626 }; 4627 // The matrix subscript operator ([][])is considered a single operator. 4628 // Separating the index expressions by parenthesis is not allowed. 4629 if (base->getType()->isSpecificPlaceholderType( 4630 BuiltinType::IncompleteMatrixIdx) && 4631 !isa<MatrixSubscriptExpr>(base)) { 4632 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4633 << SourceRange(base->getBeginLoc(), rbLoc); 4634 return ExprError(); 4635 } 4636 // If the base is a MatrixSubscriptExpr, try to create a new 4637 // MatrixSubscriptExpr. 4638 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4639 if (matSubscriptE) { 4640 if (CheckAndReportCommaError(idx)) 4641 return ExprError(); 4642 4643 assert(matSubscriptE->isIncomplete() && 4644 "base has to be an incomplete matrix subscript"); 4645 return CreateBuiltinMatrixSubscriptExpr( 4646 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4647 } 4648 4649 // Handle any non-overload placeholder types in the base and index 4650 // expressions. We can't handle overloads here because the other 4651 // operand might be an overloadable type, in which case the overload 4652 // resolution for the operator overload should get the first crack 4653 // at the overload. 4654 bool IsMSPropertySubscript = false; 4655 if (base->getType()->isNonOverloadPlaceholderType()) { 4656 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4657 if (!IsMSPropertySubscript) { 4658 ExprResult result = CheckPlaceholderExpr(base); 4659 if (result.isInvalid()) 4660 return ExprError(); 4661 base = result.get(); 4662 } 4663 } 4664 4665 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4666 if (base->getType()->isMatrixType()) { 4667 if (CheckAndReportCommaError(idx)) 4668 return ExprError(); 4669 4670 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4671 } 4672 4673 // A comma-expression as the index is deprecated in C++2a onwards. 4674 if (getLangOpts().CPlusPlus20 && 4675 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4676 (isa<CXXOperatorCallExpr>(idx) && 4677 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4678 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4679 << SourceRange(base->getBeginLoc(), rbLoc); 4680 } 4681 4682 if (idx->getType()->isNonOverloadPlaceholderType()) { 4683 ExprResult result = CheckPlaceholderExpr(idx); 4684 if (result.isInvalid()) return ExprError(); 4685 idx = result.get(); 4686 } 4687 4688 // Build an unanalyzed expression if either operand is type-dependent. 4689 if (getLangOpts().CPlusPlus && 4690 (base->isTypeDependent() || idx->isTypeDependent())) { 4691 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4692 VK_LValue, OK_Ordinary, rbLoc); 4693 } 4694 4695 // MSDN, property (C++) 4696 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4697 // This attribute can also be used in the declaration of an empty array in a 4698 // class or structure definition. For example: 4699 // __declspec(property(get=GetX, put=PutX)) int x[]; 4700 // The above statement indicates that x[] can be used with one or more array 4701 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4702 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4703 if (IsMSPropertySubscript) { 4704 // Build MS property subscript expression if base is MS property reference 4705 // or MS property subscript. 4706 return new (Context) MSPropertySubscriptExpr( 4707 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4708 } 4709 4710 // Use C++ overloaded-operator rules if either operand has record 4711 // type. The spec says to do this if either type is *overloadable*, 4712 // but enum types can't declare subscript operators or conversion 4713 // operators, so there's nothing interesting for overload resolution 4714 // to do if there aren't any record types involved. 4715 // 4716 // ObjC pointers have their own subscripting logic that is not tied 4717 // to overload resolution and so should not take this path. 4718 if (getLangOpts().CPlusPlus && 4719 (base->getType()->isRecordType() || 4720 (!base->getType()->isObjCObjectPointerType() && 4721 idx->getType()->isRecordType()))) { 4722 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4723 } 4724 4725 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4726 4727 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4728 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4729 4730 return Res; 4731 } 4732 4733 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4734 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4735 InitializationKind Kind = 4736 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4737 InitializationSequence InitSeq(*this, Entity, Kind, E); 4738 return InitSeq.Perform(*this, Entity, Kind, E); 4739 } 4740 4741 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4742 Expr *ColumnIdx, 4743 SourceLocation RBLoc) { 4744 ExprResult BaseR = CheckPlaceholderExpr(Base); 4745 if (BaseR.isInvalid()) 4746 return BaseR; 4747 Base = BaseR.get(); 4748 4749 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4750 if (RowR.isInvalid()) 4751 return RowR; 4752 RowIdx = RowR.get(); 4753 4754 if (!ColumnIdx) 4755 return new (Context) MatrixSubscriptExpr( 4756 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4757 4758 // Build an unanalyzed expression if any of the operands is type-dependent. 4759 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4760 ColumnIdx->isTypeDependent()) 4761 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4762 Context.DependentTy, RBLoc); 4763 4764 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4765 if (ColumnR.isInvalid()) 4766 return ColumnR; 4767 ColumnIdx = ColumnR.get(); 4768 4769 // Check that IndexExpr is an integer expression. If it is a constant 4770 // expression, check that it is less than Dim (= the number of elements in the 4771 // corresponding dimension). 4772 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4773 bool IsColumnIdx) -> Expr * { 4774 if (!IndexExpr->getType()->isIntegerType() && 4775 !IndexExpr->isTypeDependent()) { 4776 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4777 << IsColumnIdx; 4778 return nullptr; 4779 } 4780 4781 if (Optional<llvm::APSInt> Idx = 4782 IndexExpr->getIntegerConstantExpr(Context)) { 4783 if ((*Idx < 0 || *Idx >= Dim)) { 4784 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4785 << IsColumnIdx << Dim; 4786 return nullptr; 4787 } 4788 } 4789 4790 ExprResult ConvExpr = 4791 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4792 assert(!ConvExpr.isInvalid() && 4793 "should be able to convert any integer type to size type"); 4794 return ConvExpr.get(); 4795 }; 4796 4797 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4798 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4799 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4800 if (!RowIdx || !ColumnIdx) 4801 return ExprError(); 4802 4803 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4804 MTy->getElementType(), RBLoc); 4805 } 4806 4807 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4808 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4809 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4810 4811 // For expressions like `&(*s).b`, the base is recorded and what should be 4812 // checked. 4813 const MemberExpr *Member = nullptr; 4814 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4815 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4816 4817 LastRecord.PossibleDerefs.erase(StrippedExpr); 4818 } 4819 4820 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4821 if (isUnevaluatedContext()) 4822 return; 4823 4824 QualType ResultTy = E->getType(); 4825 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4826 4827 // Bail if the element is an array since it is not memory access. 4828 if (isa<ArrayType>(ResultTy)) 4829 return; 4830 4831 if (ResultTy->hasAttr(attr::NoDeref)) { 4832 LastRecord.PossibleDerefs.insert(E); 4833 return; 4834 } 4835 4836 // Check if the base type is a pointer to a member access of a struct 4837 // marked with noderef. 4838 const Expr *Base = E->getBase(); 4839 QualType BaseTy = Base->getType(); 4840 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4841 // Not a pointer access 4842 return; 4843 4844 const MemberExpr *Member = nullptr; 4845 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4846 Member->isArrow()) 4847 Base = Member->getBase(); 4848 4849 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4850 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4851 LastRecord.PossibleDerefs.insert(E); 4852 } 4853 } 4854 4855 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4856 Expr *LowerBound, 4857 SourceLocation ColonLocFirst, 4858 SourceLocation ColonLocSecond, 4859 Expr *Length, Expr *Stride, 4860 SourceLocation RBLoc) { 4861 if (Base->getType()->isPlaceholderType() && 4862 !Base->getType()->isSpecificPlaceholderType( 4863 BuiltinType::OMPArraySection)) { 4864 ExprResult Result = CheckPlaceholderExpr(Base); 4865 if (Result.isInvalid()) 4866 return ExprError(); 4867 Base = Result.get(); 4868 } 4869 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4870 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4871 if (Result.isInvalid()) 4872 return ExprError(); 4873 Result = DefaultLvalueConversion(Result.get()); 4874 if (Result.isInvalid()) 4875 return ExprError(); 4876 LowerBound = Result.get(); 4877 } 4878 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4879 ExprResult Result = CheckPlaceholderExpr(Length); 4880 if (Result.isInvalid()) 4881 return ExprError(); 4882 Result = DefaultLvalueConversion(Result.get()); 4883 if (Result.isInvalid()) 4884 return ExprError(); 4885 Length = Result.get(); 4886 } 4887 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4888 ExprResult Result = CheckPlaceholderExpr(Stride); 4889 if (Result.isInvalid()) 4890 return ExprError(); 4891 Result = DefaultLvalueConversion(Result.get()); 4892 if (Result.isInvalid()) 4893 return ExprError(); 4894 Stride = Result.get(); 4895 } 4896 4897 // Build an unanalyzed expression if either operand is type-dependent. 4898 if (Base->isTypeDependent() || 4899 (LowerBound && 4900 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4901 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4902 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4903 return new (Context) OMPArraySectionExpr( 4904 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4905 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4906 } 4907 4908 // Perform default conversions. 4909 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4910 QualType ResultTy; 4911 if (OriginalTy->isAnyPointerType()) { 4912 ResultTy = OriginalTy->getPointeeType(); 4913 } else if (OriginalTy->isArrayType()) { 4914 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4915 } else { 4916 return ExprError( 4917 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4918 << Base->getSourceRange()); 4919 } 4920 // C99 6.5.2.1p1 4921 if (LowerBound) { 4922 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4923 LowerBound); 4924 if (Res.isInvalid()) 4925 return ExprError(Diag(LowerBound->getExprLoc(), 4926 diag::err_omp_typecheck_section_not_integer) 4927 << 0 << LowerBound->getSourceRange()); 4928 LowerBound = Res.get(); 4929 4930 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4931 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4932 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4933 << 0 << LowerBound->getSourceRange(); 4934 } 4935 if (Length) { 4936 auto Res = 4937 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4938 if (Res.isInvalid()) 4939 return ExprError(Diag(Length->getExprLoc(), 4940 diag::err_omp_typecheck_section_not_integer) 4941 << 1 << Length->getSourceRange()); 4942 Length = Res.get(); 4943 4944 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4945 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4946 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4947 << 1 << Length->getSourceRange(); 4948 } 4949 if (Stride) { 4950 ExprResult Res = 4951 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4952 if (Res.isInvalid()) 4953 return ExprError(Diag(Stride->getExprLoc(), 4954 diag::err_omp_typecheck_section_not_integer) 4955 << 1 << Stride->getSourceRange()); 4956 Stride = Res.get(); 4957 4958 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4959 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4960 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4961 << 1 << Stride->getSourceRange(); 4962 } 4963 4964 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4965 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4966 // type. Note that functions are not objects, and that (in C99 parlance) 4967 // incomplete types are not object types. 4968 if (ResultTy->isFunctionType()) { 4969 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4970 << ResultTy << Base->getSourceRange(); 4971 return ExprError(); 4972 } 4973 4974 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4975 diag::err_omp_section_incomplete_type, Base)) 4976 return ExprError(); 4977 4978 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4979 Expr::EvalResult Result; 4980 if (LowerBound->EvaluateAsInt(Result, Context)) { 4981 // OpenMP 5.0, [2.1.5 Array Sections] 4982 // The array section must be a subset of the original array. 4983 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4984 if (LowerBoundValue.isNegative()) { 4985 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4986 << LowerBound->getSourceRange(); 4987 return ExprError(); 4988 } 4989 } 4990 } 4991 4992 if (Length) { 4993 Expr::EvalResult Result; 4994 if (Length->EvaluateAsInt(Result, Context)) { 4995 // OpenMP 5.0, [2.1.5 Array Sections] 4996 // The length must evaluate to non-negative integers. 4997 llvm::APSInt LengthValue = Result.Val.getInt(); 4998 if (LengthValue.isNegative()) { 4999 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5000 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 5001 << Length->getSourceRange(); 5002 return ExprError(); 5003 } 5004 } 5005 } else if (ColonLocFirst.isValid() && 5006 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5007 !OriginalTy->isVariableArrayType()))) { 5008 // OpenMP 5.0, [2.1.5 Array Sections] 5009 // When the size of the array dimension is not known, the length must be 5010 // specified explicitly. 5011 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5012 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5013 return ExprError(); 5014 } 5015 5016 if (Stride) { 5017 Expr::EvalResult Result; 5018 if (Stride->EvaluateAsInt(Result, Context)) { 5019 // OpenMP 5.0, [2.1.5 Array Sections] 5020 // The stride must evaluate to a positive integer. 5021 llvm::APSInt StrideValue = Result.Val.getInt(); 5022 if (!StrideValue.isStrictlyPositive()) { 5023 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5024 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5025 << Stride->getSourceRange(); 5026 return ExprError(); 5027 } 5028 } 5029 } 5030 5031 if (!Base->getType()->isSpecificPlaceholderType( 5032 BuiltinType::OMPArraySection)) { 5033 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5034 if (Result.isInvalid()) 5035 return ExprError(); 5036 Base = Result.get(); 5037 } 5038 return new (Context) OMPArraySectionExpr( 5039 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5040 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5041 } 5042 5043 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5044 SourceLocation RParenLoc, 5045 ArrayRef<Expr *> Dims, 5046 ArrayRef<SourceRange> Brackets) { 5047 if (Base->getType()->isPlaceholderType()) { 5048 ExprResult Result = CheckPlaceholderExpr(Base); 5049 if (Result.isInvalid()) 5050 return ExprError(); 5051 Result = DefaultLvalueConversion(Result.get()); 5052 if (Result.isInvalid()) 5053 return ExprError(); 5054 Base = Result.get(); 5055 } 5056 QualType BaseTy = Base->getType(); 5057 // Delay analysis of the types/expressions if instantiation/specialization is 5058 // required. 5059 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5060 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5061 LParenLoc, RParenLoc, Dims, Brackets); 5062 if (!BaseTy->isPointerType() || 5063 (!Base->isTypeDependent() && 5064 BaseTy->getPointeeType()->isIncompleteType())) 5065 return ExprError(Diag(Base->getExprLoc(), 5066 diag::err_omp_non_pointer_type_array_shaping_base) 5067 << Base->getSourceRange()); 5068 5069 SmallVector<Expr *, 4> NewDims; 5070 bool ErrorFound = false; 5071 for (Expr *Dim : Dims) { 5072 if (Dim->getType()->isPlaceholderType()) { 5073 ExprResult Result = CheckPlaceholderExpr(Dim); 5074 if (Result.isInvalid()) { 5075 ErrorFound = true; 5076 continue; 5077 } 5078 Result = DefaultLvalueConversion(Result.get()); 5079 if (Result.isInvalid()) { 5080 ErrorFound = true; 5081 continue; 5082 } 5083 Dim = Result.get(); 5084 } 5085 if (!Dim->isTypeDependent()) { 5086 ExprResult Result = 5087 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5088 if (Result.isInvalid()) { 5089 ErrorFound = true; 5090 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5091 << Dim->getSourceRange(); 5092 continue; 5093 } 5094 Dim = Result.get(); 5095 Expr::EvalResult EvResult; 5096 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5097 // OpenMP 5.0, [2.1.4 Array Shaping] 5098 // Each si is an integral type expression that must evaluate to a 5099 // positive integer. 5100 llvm::APSInt Value = EvResult.Val.getInt(); 5101 if (!Value.isStrictlyPositive()) { 5102 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5103 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5104 << Dim->getSourceRange(); 5105 ErrorFound = true; 5106 continue; 5107 } 5108 } 5109 } 5110 NewDims.push_back(Dim); 5111 } 5112 if (ErrorFound) 5113 return ExprError(); 5114 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5115 LParenLoc, RParenLoc, NewDims, Brackets); 5116 } 5117 5118 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5119 SourceLocation LLoc, SourceLocation RLoc, 5120 ArrayRef<OMPIteratorData> Data) { 5121 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5122 bool IsCorrect = true; 5123 for (const OMPIteratorData &D : Data) { 5124 TypeSourceInfo *TInfo = nullptr; 5125 SourceLocation StartLoc; 5126 QualType DeclTy; 5127 if (!D.Type.getAsOpaquePtr()) { 5128 // OpenMP 5.0, 2.1.6 Iterators 5129 // In an iterator-specifier, if the iterator-type is not specified then 5130 // the type of that iterator is of int type. 5131 DeclTy = Context.IntTy; 5132 StartLoc = D.DeclIdentLoc; 5133 } else { 5134 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5135 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5136 } 5137 5138 bool IsDeclTyDependent = DeclTy->isDependentType() || 5139 DeclTy->containsUnexpandedParameterPack() || 5140 DeclTy->isInstantiationDependentType(); 5141 if (!IsDeclTyDependent) { 5142 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5143 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5144 // The iterator-type must be an integral or pointer type. 5145 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5146 << DeclTy; 5147 IsCorrect = false; 5148 continue; 5149 } 5150 if (DeclTy.isConstant(Context)) { 5151 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5152 // The iterator-type must not be const qualified. 5153 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5154 << DeclTy; 5155 IsCorrect = false; 5156 continue; 5157 } 5158 } 5159 5160 // Iterator declaration. 5161 assert(D.DeclIdent && "Identifier expected."); 5162 // Always try to create iterator declarator to avoid extra error messages 5163 // about unknown declarations use. 5164 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5165 D.DeclIdent, DeclTy, TInfo, SC_None); 5166 VD->setImplicit(); 5167 if (S) { 5168 // Check for conflicting previous declaration. 5169 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5170 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5171 ForVisibleRedeclaration); 5172 Previous.suppressDiagnostics(); 5173 LookupName(Previous, S); 5174 5175 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5176 /*AllowInlineNamespace=*/false); 5177 if (!Previous.empty()) { 5178 NamedDecl *Old = Previous.getRepresentativeDecl(); 5179 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5180 Diag(Old->getLocation(), diag::note_previous_definition); 5181 } else { 5182 PushOnScopeChains(VD, S); 5183 } 5184 } else { 5185 CurContext->addDecl(VD); 5186 } 5187 Expr *Begin = D.Range.Begin; 5188 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5189 ExprResult BeginRes = 5190 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5191 Begin = BeginRes.get(); 5192 } 5193 Expr *End = D.Range.End; 5194 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5195 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5196 End = EndRes.get(); 5197 } 5198 Expr *Step = D.Range.Step; 5199 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5200 if (!Step->getType()->isIntegralType(Context)) { 5201 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5202 << Step << Step->getSourceRange(); 5203 IsCorrect = false; 5204 continue; 5205 } 5206 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5207 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5208 // If the step expression of a range-specification equals zero, the 5209 // behavior is unspecified. 5210 if (Result && Result->isNullValue()) { 5211 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5212 << Step << Step->getSourceRange(); 5213 IsCorrect = false; 5214 continue; 5215 } 5216 } 5217 if (!Begin || !End || !IsCorrect) { 5218 IsCorrect = false; 5219 continue; 5220 } 5221 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5222 IDElem.IteratorDecl = VD; 5223 IDElem.AssignmentLoc = D.AssignLoc; 5224 IDElem.Range.Begin = Begin; 5225 IDElem.Range.End = End; 5226 IDElem.Range.Step = Step; 5227 IDElem.ColonLoc = D.ColonLoc; 5228 IDElem.SecondColonLoc = D.SecColonLoc; 5229 } 5230 if (!IsCorrect) { 5231 // Invalidate all created iterator declarations if error is found. 5232 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5233 if (Decl *ID = D.IteratorDecl) 5234 ID->setInvalidDecl(); 5235 } 5236 return ExprError(); 5237 } 5238 SmallVector<OMPIteratorHelperData, 4> Helpers; 5239 if (!CurContext->isDependentContext()) { 5240 // Build number of ityeration for each iteration range. 5241 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5242 // ((Begini-Stepi-1-Endi) / -Stepi); 5243 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5244 // (Endi - Begini) 5245 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5246 D.Range.Begin); 5247 if(!Res.isUsable()) { 5248 IsCorrect = false; 5249 continue; 5250 } 5251 ExprResult St, St1; 5252 if (D.Range.Step) { 5253 St = D.Range.Step; 5254 // (Endi - Begini) + Stepi 5255 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5256 if (!Res.isUsable()) { 5257 IsCorrect = false; 5258 continue; 5259 } 5260 // (Endi - Begini) + Stepi - 1 5261 Res = 5262 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5263 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5264 if (!Res.isUsable()) { 5265 IsCorrect = false; 5266 continue; 5267 } 5268 // ((Endi - Begini) + Stepi - 1) / Stepi 5269 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5270 if (!Res.isUsable()) { 5271 IsCorrect = false; 5272 continue; 5273 } 5274 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5275 // (Begini - Endi) 5276 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5277 D.Range.Begin, D.Range.End); 5278 if (!Res1.isUsable()) { 5279 IsCorrect = false; 5280 continue; 5281 } 5282 // (Begini - Endi) - Stepi 5283 Res1 = 5284 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5285 if (!Res1.isUsable()) { 5286 IsCorrect = false; 5287 continue; 5288 } 5289 // (Begini - Endi) - Stepi - 1 5290 Res1 = 5291 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5292 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5293 if (!Res1.isUsable()) { 5294 IsCorrect = false; 5295 continue; 5296 } 5297 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5298 Res1 = 5299 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5300 if (!Res1.isUsable()) { 5301 IsCorrect = false; 5302 continue; 5303 } 5304 // Stepi > 0. 5305 ExprResult CmpRes = 5306 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5307 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5308 if (!CmpRes.isUsable()) { 5309 IsCorrect = false; 5310 continue; 5311 } 5312 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5313 Res.get(), Res1.get()); 5314 if (!Res.isUsable()) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 } 5319 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5320 if (!Res.isUsable()) { 5321 IsCorrect = false; 5322 continue; 5323 } 5324 5325 // Build counter update. 5326 // Build counter. 5327 auto *CounterVD = 5328 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5329 D.IteratorDecl->getBeginLoc(), nullptr, 5330 Res.get()->getType(), nullptr, SC_None); 5331 CounterVD->setImplicit(); 5332 ExprResult RefRes = 5333 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5334 D.IteratorDecl->getBeginLoc()); 5335 // Build counter update. 5336 // I = Begini + counter * Stepi; 5337 ExprResult UpdateRes; 5338 if (D.Range.Step) { 5339 UpdateRes = CreateBuiltinBinOp( 5340 D.AssignmentLoc, BO_Mul, 5341 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5342 } else { 5343 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5344 } 5345 if (!UpdateRes.isUsable()) { 5346 IsCorrect = false; 5347 continue; 5348 } 5349 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5350 UpdateRes.get()); 5351 if (!UpdateRes.isUsable()) { 5352 IsCorrect = false; 5353 continue; 5354 } 5355 ExprResult VDRes = 5356 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5357 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5358 D.IteratorDecl->getBeginLoc()); 5359 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5360 UpdateRes.get()); 5361 if (!UpdateRes.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 UpdateRes = 5366 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5367 if (!UpdateRes.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 ExprResult CounterUpdateRes = 5372 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5373 if (!CounterUpdateRes.isUsable()) { 5374 IsCorrect = false; 5375 continue; 5376 } 5377 CounterUpdateRes = 5378 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5379 if (!CounterUpdateRes.isUsable()) { 5380 IsCorrect = false; 5381 continue; 5382 } 5383 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5384 HD.CounterVD = CounterVD; 5385 HD.Upper = Res.get(); 5386 HD.Update = UpdateRes.get(); 5387 HD.CounterUpdate = CounterUpdateRes.get(); 5388 } 5389 } else { 5390 Helpers.assign(ID.size(), {}); 5391 } 5392 if (!IsCorrect) { 5393 // Invalidate all created iterator declarations if error is found. 5394 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5395 if (Decl *ID = D.IteratorDecl) 5396 ID->setInvalidDecl(); 5397 } 5398 return ExprError(); 5399 } 5400 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5401 LLoc, RLoc, ID, Helpers); 5402 } 5403 5404 ExprResult 5405 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5406 Expr *Idx, SourceLocation RLoc) { 5407 Expr *LHSExp = Base; 5408 Expr *RHSExp = Idx; 5409 5410 ExprValueKind VK = VK_LValue; 5411 ExprObjectKind OK = OK_Ordinary; 5412 5413 // Per C++ core issue 1213, the result is an xvalue if either operand is 5414 // a non-lvalue array, and an lvalue otherwise. 5415 if (getLangOpts().CPlusPlus11) { 5416 for (auto *Op : {LHSExp, RHSExp}) { 5417 Op = Op->IgnoreImplicit(); 5418 if (Op->getType()->isArrayType() && !Op->isLValue()) 5419 VK = VK_XValue; 5420 } 5421 } 5422 5423 // Perform default conversions. 5424 if (!LHSExp->getType()->getAs<VectorType>()) { 5425 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5426 if (Result.isInvalid()) 5427 return ExprError(); 5428 LHSExp = Result.get(); 5429 } 5430 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5431 if (Result.isInvalid()) 5432 return ExprError(); 5433 RHSExp = Result.get(); 5434 5435 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5436 5437 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5438 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5439 // in the subscript position. As a result, we need to derive the array base 5440 // and index from the expression types. 5441 Expr *BaseExpr, *IndexExpr; 5442 QualType ResultType; 5443 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5444 BaseExpr = LHSExp; 5445 IndexExpr = RHSExp; 5446 ResultType = Context.DependentTy; 5447 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5448 BaseExpr = LHSExp; 5449 IndexExpr = RHSExp; 5450 ResultType = PTy->getPointeeType(); 5451 } else if (const ObjCObjectPointerType *PTy = 5452 LHSTy->getAs<ObjCObjectPointerType>()) { 5453 BaseExpr = LHSExp; 5454 IndexExpr = RHSExp; 5455 5456 // Use custom logic if this should be the pseudo-object subscript 5457 // expression. 5458 if (!LangOpts.isSubscriptPointerArithmetic()) 5459 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5460 nullptr); 5461 5462 ResultType = PTy->getPointeeType(); 5463 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5464 // Handle the uncommon case of "123[Ptr]". 5465 BaseExpr = RHSExp; 5466 IndexExpr = LHSExp; 5467 ResultType = PTy->getPointeeType(); 5468 } else if (const ObjCObjectPointerType *PTy = 5469 RHSTy->getAs<ObjCObjectPointerType>()) { 5470 // Handle the uncommon case of "123[Ptr]". 5471 BaseExpr = RHSExp; 5472 IndexExpr = LHSExp; 5473 ResultType = PTy->getPointeeType(); 5474 if (!LangOpts.isSubscriptPointerArithmetic()) { 5475 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5476 << ResultType << BaseExpr->getSourceRange(); 5477 return ExprError(); 5478 } 5479 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5480 BaseExpr = LHSExp; // vectors: V[123] 5481 IndexExpr = RHSExp; 5482 // We apply C++ DR1213 to vector subscripting too. 5483 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5484 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5485 if (Materialized.isInvalid()) 5486 return ExprError(); 5487 LHSExp = Materialized.get(); 5488 } 5489 VK = LHSExp->getValueKind(); 5490 if (VK != VK_RValue) 5491 OK = OK_VectorComponent; 5492 5493 ResultType = VTy->getElementType(); 5494 QualType BaseType = BaseExpr->getType(); 5495 Qualifiers BaseQuals = BaseType.getQualifiers(); 5496 Qualifiers MemberQuals = ResultType.getQualifiers(); 5497 Qualifiers Combined = BaseQuals + MemberQuals; 5498 if (Combined != MemberQuals) 5499 ResultType = Context.getQualifiedType(ResultType, Combined); 5500 } else if (LHSTy->isArrayType()) { 5501 // If we see an array that wasn't promoted by 5502 // DefaultFunctionArrayLvalueConversion, it must be an array that 5503 // wasn't promoted because of the C90 rule that doesn't 5504 // allow promoting non-lvalue arrays. Warn, then 5505 // force the promotion here. 5506 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5507 << LHSExp->getSourceRange(); 5508 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5509 CK_ArrayToPointerDecay).get(); 5510 LHSTy = LHSExp->getType(); 5511 5512 BaseExpr = LHSExp; 5513 IndexExpr = RHSExp; 5514 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 5515 } else if (RHSTy->isArrayType()) { 5516 // Same as previous, except for 123[f().a] case 5517 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5518 << RHSExp->getSourceRange(); 5519 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5520 CK_ArrayToPointerDecay).get(); 5521 RHSTy = RHSExp->getType(); 5522 5523 BaseExpr = RHSExp; 5524 IndexExpr = LHSExp; 5525 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 5526 } else { 5527 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5528 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5529 } 5530 // C99 6.5.2.1p1 5531 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5532 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5533 << IndexExpr->getSourceRange()); 5534 5535 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5536 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5537 && !IndexExpr->isTypeDependent()) 5538 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5539 5540 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5541 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5542 // type. Note that Functions are not objects, and that (in C99 parlance) 5543 // incomplete types are not object types. 5544 if (ResultType->isFunctionType()) { 5545 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5546 << ResultType << BaseExpr->getSourceRange(); 5547 return ExprError(); 5548 } 5549 5550 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5551 // GNU extension: subscripting on pointer to void 5552 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5553 << BaseExpr->getSourceRange(); 5554 5555 // C forbids expressions of unqualified void type from being l-values. 5556 // See IsCForbiddenLValueType. 5557 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5558 } else if (!ResultType->isDependentType() && 5559 RequireCompleteSizedType( 5560 LLoc, ResultType, 5561 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5562 return ExprError(); 5563 5564 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5565 !ResultType.isCForbiddenLValueType()); 5566 5567 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5568 FunctionScopes.size() > 1) { 5569 if (auto *TT = 5570 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5571 for (auto I = FunctionScopes.rbegin(), 5572 E = std::prev(FunctionScopes.rend()); 5573 I != E; ++I) { 5574 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5575 if (CSI == nullptr) 5576 break; 5577 DeclContext *DC = nullptr; 5578 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5579 DC = LSI->CallOperator; 5580 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5581 DC = CRSI->TheCapturedDecl; 5582 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5583 DC = BSI->TheDecl; 5584 if (DC) { 5585 if (DC->containsDecl(TT->getDecl())) 5586 break; 5587 captureVariablyModifiedType( 5588 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5589 } 5590 } 5591 } 5592 } 5593 5594 return new (Context) 5595 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5596 } 5597 5598 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5599 ParmVarDecl *Param) { 5600 if (Param->hasUnparsedDefaultArg()) { 5601 // If we've already cleared out the location for the default argument, 5602 // that means we're parsing it right now. 5603 if (!UnparsedDefaultArgLocs.count(Param)) { 5604 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5605 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5606 Param->setInvalidDecl(); 5607 return true; 5608 } 5609 5610 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5611 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5612 Diag(UnparsedDefaultArgLocs[Param], 5613 diag::note_default_argument_declared_here); 5614 return true; 5615 } 5616 5617 if (Param->hasUninstantiatedDefaultArg() && 5618 InstantiateDefaultArgument(CallLoc, FD, Param)) 5619 return true; 5620 5621 assert(Param->hasInit() && "default argument but no initializer?"); 5622 5623 // If the default expression creates temporaries, we need to 5624 // push them to the current stack of expression temporaries so they'll 5625 // be properly destroyed. 5626 // FIXME: We should really be rebuilding the default argument with new 5627 // bound temporaries; see the comment in PR5810. 5628 // We don't need to do that with block decls, though, because 5629 // blocks in default argument expression can never capture anything. 5630 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5631 // Set the "needs cleanups" bit regardless of whether there are 5632 // any explicit objects. 5633 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5634 5635 // Append all the objects to the cleanup list. Right now, this 5636 // should always be a no-op, because blocks in default argument 5637 // expressions should never be able to capture anything. 5638 assert(!Init->getNumObjects() && 5639 "default argument expression has capturing blocks?"); 5640 } 5641 5642 // We already type-checked the argument, so we know it works. 5643 // Just mark all of the declarations in this potentially-evaluated expression 5644 // as being "referenced". 5645 EnterExpressionEvaluationContext EvalContext( 5646 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5647 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5648 /*SkipLocalVariables=*/true); 5649 return false; 5650 } 5651 5652 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5653 FunctionDecl *FD, ParmVarDecl *Param) { 5654 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5655 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5656 return ExprError(); 5657 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5658 } 5659 5660 Sema::VariadicCallType 5661 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5662 Expr *Fn) { 5663 if (Proto && Proto->isVariadic()) { 5664 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5665 return VariadicConstructor; 5666 else if (Fn && Fn->getType()->isBlockPointerType()) 5667 return VariadicBlock; 5668 else if (FDecl) { 5669 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5670 if (Method->isInstance()) 5671 return VariadicMethod; 5672 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5673 return VariadicMethod; 5674 return VariadicFunction; 5675 } 5676 return VariadicDoesNotApply; 5677 } 5678 5679 namespace { 5680 class FunctionCallCCC final : public FunctionCallFilterCCC { 5681 public: 5682 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5683 unsigned NumArgs, MemberExpr *ME) 5684 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5685 FunctionName(FuncName) {} 5686 5687 bool ValidateCandidate(const TypoCorrection &candidate) override { 5688 if (!candidate.getCorrectionSpecifier() || 5689 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5690 return false; 5691 } 5692 5693 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5694 } 5695 5696 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5697 return std::make_unique<FunctionCallCCC>(*this); 5698 } 5699 5700 private: 5701 const IdentifierInfo *const FunctionName; 5702 }; 5703 } 5704 5705 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5706 FunctionDecl *FDecl, 5707 ArrayRef<Expr *> Args) { 5708 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5709 DeclarationName FuncName = FDecl->getDeclName(); 5710 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5711 5712 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5713 if (TypoCorrection Corrected = S.CorrectTypo( 5714 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5715 S.getScopeForContext(S.CurContext), nullptr, CCC, 5716 Sema::CTK_ErrorRecovery)) { 5717 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5718 if (Corrected.isOverloaded()) { 5719 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5720 OverloadCandidateSet::iterator Best; 5721 for (NamedDecl *CD : Corrected) { 5722 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5723 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5724 OCS); 5725 } 5726 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5727 case OR_Success: 5728 ND = Best->FoundDecl; 5729 Corrected.setCorrectionDecl(ND); 5730 break; 5731 default: 5732 break; 5733 } 5734 } 5735 ND = ND->getUnderlyingDecl(); 5736 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5737 return Corrected; 5738 } 5739 } 5740 return TypoCorrection(); 5741 } 5742 5743 /// ConvertArgumentsForCall - Converts the arguments specified in 5744 /// Args/NumArgs to the parameter types of the function FDecl with 5745 /// function prototype Proto. Call is the call expression itself, and 5746 /// Fn is the function expression. For a C++ member function, this 5747 /// routine does not attempt to convert the object argument. Returns 5748 /// true if the call is ill-formed. 5749 bool 5750 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5751 FunctionDecl *FDecl, 5752 const FunctionProtoType *Proto, 5753 ArrayRef<Expr *> Args, 5754 SourceLocation RParenLoc, 5755 bool IsExecConfig) { 5756 // Bail out early if calling a builtin with custom typechecking. 5757 if (FDecl) 5758 if (unsigned ID = FDecl->getBuiltinID()) 5759 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5760 return false; 5761 5762 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5763 // assignment, to the types of the corresponding parameter, ... 5764 unsigned NumParams = Proto->getNumParams(); 5765 bool Invalid = false; 5766 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5767 unsigned FnKind = Fn->getType()->isBlockPointerType() 5768 ? 1 /* block */ 5769 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5770 : 0 /* function */); 5771 5772 // If too few arguments are available (and we don't have default 5773 // arguments for the remaining parameters), don't make the call. 5774 if (Args.size() < NumParams) { 5775 if (Args.size() < MinArgs) { 5776 TypoCorrection TC; 5777 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5778 unsigned diag_id = 5779 MinArgs == NumParams && !Proto->isVariadic() 5780 ? diag::err_typecheck_call_too_few_args_suggest 5781 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5782 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5783 << static_cast<unsigned>(Args.size()) 5784 << TC.getCorrectionRange()); 5785 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5786 Diag(RParenLoc, 5787 MinArgs == NumParams && !Proto->isVariadic() 5788 ? diag::err_typecheck_call_too_few_args_one 5789 : diag::err_typecheck_call_too_few_args_at_least_one) 5790 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5791 else 5792 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5793 ? diag::err_typecheck_call_too_few_args 5794 : diag::err_typecheck_call_too_few_args_at_least) 5795 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5796 << Fn->getSourceRange(); 5797 5798 // Emit the location of the prototype. 5799 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5800 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5801 5802 return true; 5803 } 5804 // We reserve space for the default arguments when we create 5805 // the call expression, before calling ConvertArgumentsForCall. 5806 assert((Call->getNumArgs() == NumParams) && 5807 "We should have reserved space for the default arguments before!"); 5808 } 5809 5810 // If too many are passed and not variadic, error on the extras and drop 5811 // them. 5812 if (Args.size() > NumParams) { 5813 if (!Proto->isVariadic()) { 5814 TypoCorrection TC; 5815 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5816 unsigned diag_id = 5817 MinArgs == NumParams && !Proto->isVariadic() 5818 ? diag::err_typecheck_call_too_many_args_suggest 5819 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5820 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5821 << static_cast<unsigned>(Args.size()) 5822 << TC.getCorrectionRange()); 5823 } else if (NumParams == 1 && FDecl && 5824 FDecl->getParamDecl(0)->getDeclName()) 5825 Diag(Args[NumParams]->getBeginLoc(), 5826 MinArgs == NumParams 5827 ? diag::err_typecheck_call_too_many_args_one 5828 : diag::err_typecheck_call_too_many_args_at_most_one) 5829 << FnKind << FDecl->getParamDecl(0) 5830 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5831 << SourceRange(Args[NumParams]->getBeginLoc(), 5832 Args.back()->getEndLoc()); 5833 else 5834 Diag(Args[NumParams]->getBeginLoc(), 5835 MinArgs == NumParams 5836 ? diag::err_typecheck_call_too_many_args 5837 : diag::err_typecheck_call_too_many_args_at_most) 5838 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5839 << Fn->getSourceRange() 5840 << SourceRange(Args[NumParams]->getBeginLoc(), 5841 Args.back()->getEndLoc()); 5842 5843 // Emit the location of the prototype. 5844 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5845 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5846 5847 // This deletes the extra arguments. 5848 Call->shrinkNumArgs(NumParams); 5849 return true; 5850 } 5851 } 5852 SmallVector<Expr *, 8> AllArgs; 5853 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5854 5855 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5856 AllArgs, CallType); 5857 if (Invalid) 5858 return true; 5859 unsigned TotalNumArgs = AllArgs.size(); 5860 for (unsigned i = 0; i < TotalNumArgs; ++i) 5861 Call->setArg(i, AllArgs[i]); 5862 5863 return false; 5864 } 5865 5866 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5867 const FunctionProtoType *Proto, 5868 unsigned FirstParam, ArrayRef<Expr *> Args, 5869 SmallVectorImpl<Expr *> &AllArgs, 5870 VariadicCallType CallType, bool AllowExplicit, 5871 bool IsListInitialization) { 5872 unsigned NumParams = Proto->getNumParams(); 5873 bool Invalid = false; 5874 size_t ArgIx = 0; 5875 // Continue to check argument types (even if we have too few/many args). 5876 for (unsigned i = FirstParam; i < NumParams; i++) { 5877 QualType ProtoArgType = Proto->getParamType(i); 5878 5879 Expr *Arg; 5880 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5881 if (ArgIx < Args.size()) { 5882 Arg = Args[ArgIx++]; 5883 5884 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5885 diag::err_call_incomplete_argument, Arg)) 5886 return true; 5887 5888 // Strip the unbridged-cast placeholder expression off, if applicable. 5889 bool CFAudited = false; 5890 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5891 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5892 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5893 Arg = stripARCUnbridgedCast(Arg); 5894 else if (getLangOpts().ObjCAutoRefCount && 5895 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5896 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5897 CFAudited = true; 5898 5899 if (Proto->getExtParameterInfo(i).isNoEscape()) 5900 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5901 BE->getBlockDecl()->setDoesNotEscape(); 5902 5903 InitializedEntity Entity = 5904 Param ? InitializedEntity::InitializeParameter(Context, Param, 5905 ProtoArgType) 5906 : InitializedEntity::InitializeParameter( 5907 Context, ProtoArgType, Proto->isParamConsumed(i)); 5908 5909 // Remember that parameter belongs to a CF audited API. 5910 if (CFAudited) 5911 Entity.setParameterCFAudited(); 5912 5913 ExprResult ArgE = PerformCopyInitialization( 5914 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5915 if (ArgE.isInvalid()) 5916 return true; 5917 5918 Arg = ArgE.getAs<Expr>(); 5919 } else { 5920 assert(Param && "can't use default arguments without a known callee"); 5921 5922 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5923 if (ArgExpr.isInvalid()) 5924 return true; 5925 5926 Arg = ArgExpr.getAs<Expr>(); 5927 } 5928 5929 // Check for array bounds violations for each argument to the call. This 5930 // check only triggers warnings when the argument isn't a more complex Expr 5931 // with its own checking, such as a BinaryOperator. 5932 CheckArrayAccess(Arg); 5933 5934 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5935 CheckStaticArrayArgument(CallLoc, Param, Arg); 5936 5937 AllArgs.push_back(Arg); 5938 } 5939 5940 // If this is a variadic call, handle args passed through "...". 5941 if (CallType != VariadicDoesNotApply) { 5942 // Assume that extern "C" functions with variadic arguments that 5943 // return __unknown_anytype aren't *really* variadic. 5944 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5945 FDecl->isExternC()) { 5946 for (Expr *A : Args.slice(ArgIx)) { 5947 QualType paramType; // ignored 5948 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5949 Invalid |= arg.isInvalid(); 5950 AllArgs.push_back(arg.get()); 5951 } 5952 5953 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5954 } else { 5955 for (Expr *A : Args.slice(ArgIx)) { 5956 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5957 Invalid |= Arg.isInvalid(); 5958 AllArgs.push_back(Arg.get()); 5959 } 5960 } 5961 5962 // Check for array bounds violations. 5963 for (Expr *A : Args.slice(ArgIx)) 5964 CheckArrayAccess(A); 5965 } 5966 return Invalid; 5967 } 5968 5969 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5970 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5971 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5972 TL = DTL.getOriginalLoc(); 5973 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5974 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5975 << ATL.getLocalSourceRange(); 5976 } 5977 5978 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5979 /// array parameter, check that it is non-null, and that if it is formed by 5980 /// array-to-pointer decay, the underlying array is sufficiently large. 5981 /// 5982 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5983 /// array type derivation, then for each call to the function, the value of the 5984 /// corresponding actual argument shall provide access to the first element of 5985 /// an array with at least as many elements as specified by the size expression. 5986 void 5987 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5988 ParmVarDecl *Param, 5989 const Expr *ArgExpr) { 5990 // Static array parameters are not supported in C++. 5991 if (!Param || getLangOpts().CPlusPlus) 5992 return; 5993 5994 QualType OrigTy = Param->getOriginalType(); 5995 5996 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5997 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5998 return; 5999 6000 if (ArgExpr->isNullPointerConstant(Context, 6001 Expr::NPC_NeverValueDependent)) { 6002 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6003 DiagnoseCalleeStaticArrayParam(*this, Param); 6004 return; 6005 } 6006 6007 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6008 if (!CAT) 6009 return; 6010 6011 const ConstantArrayType *ArgCAT = 6012 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6013 if (!ArgCAT) 6014 return; 6015 6016 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6017 ArgCAT->getElementType())) { 6018 if (ArgCAT->getSize().ult(CAT->getSize())) { 6019 Diag(CallLoc, diag::warn_static_array_too_small) 6020 << ArgExpr->getSourceRange() 6021 << (unsigned)ArgCAT->getSize().getZExtValue() 6022 << (unsigned)CAT->getSize().getZExtValue() << 0; 6023 DiagnoseCalleeStaticArrayParam(*this, Param); 6024 } 6025 return; 6026 } 6027 6028 Optional<CharUnits> ArgSize = 6029 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6030 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6031 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6032 Diag(CallLoc, diag::warn_static_array_too_small) 6033 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6034 << (unsigned)ParmSize->getQuantity() << 1; 6035 DiagnoseCalleeStaticArrayParam(*this, Param); 6036 } 6037 } 6038 6039 /// Given a function expression of unknown-any type, try to rebuild it 6040 /// to have a function type. 6041 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6042 6043 /// Is the given type a placeholder that we need to lower out 6044 /// immediately during argument processing? 6045 static bool isPlaceholderToRemoveAsArg(QualType type) { 6046 // Placeholders are never sugared. 6047 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6048 if (!placeholder) return false; 6049 6050 switch (placeholder->getKind()) { 6051 // Ignore all the non-placeholder types. 6052 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6053 case BuiltinType::Id: 6054 #include "clang/Basic/OpenCLImageTypes.def" 6055 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6056 case BuiltinType::Id: 6057 #include "clang/Basic/OpenCLExtensionTypes.def" 6058 // In practice we'll never use this, since all SVE types are sugared 6059 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6060 #define SVE_TYPE(Name, Id, SingletonId) \ 6061 case BuiltinType::Id: 6062 #include "clang/Basic/AArch64SVEACLETypes.def" 6063 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6064 case BuiltinType::Id: 6065 #include "clang/Basic/PPCTypes.def" 6066 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6067 #include "clang/Basic/RISCVVTypes.def" 6068 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6069 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6070 #include "clang/AST/BuiltinTypes.def" 6071 return false; 6072 6073 // We cannot lower out overload sets; they might validly be resolved 6074 // by the call machinery. 6075 case BuiltinType::Overload: 6076 return false; 6077 6078 // Unbridged casts in ARC can be handled in some call positions and 6079 // should be left in place. 6080 case BuiltinType::ARCUnbridgedCast: 6081 return false; 6082 6083 // Pseudo-objects should be converted as soon as possible. 6084 case BuiltinType::PseudoObject: 6085 return true; 6086 6087 // The debugger mode could theoretically but currently does not try 6088 // to resolve unknown-typed arguments based on known parameter types. 6089 case BuiltinType::UnknownAny: 6090 return true; 6091 6092 // These are always invalid as call arguments and should be reported. 6093 case BuiltinType::BoundMember: 6094 case BuiltinType::BuiltinFn: 6095 case BuiltinType::IncompleteMatrixIdx: 6096 case BuiltinType::OMPArraySection: 6097 case BuiltinType::OMPArrayShaping: 6098 case BuiltinType::OMPIterator: 6099 return true; 6100 6101 } 6102 llvm_unreachable("bad builtin type kind"); 6103 } 6104 6105 /// Check an argument list for placeholders that we won't try to 6106 /// handle later. 6107 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6108 // Apply this processing to all the arguments at once instead of 6109 // dying at the first failure. 6110 bool hasInvalid = false; 6111 for (size_t i = 0, e = args.size(); i != e; i++) { 6112 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6113 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6114 if (result.isInvalid()) hasInvalid = true; 6115 else args[i] = result.get(); 6116 } 6117 } 6118 return hasInvalid; 6119 } 6120 6121 /// If a builtin function has a pointer argument with no explicit address 6122 /// space, then it should be able to accept a pointer to any address 6123 /// space as input. In order to do this, we need to replace the 6124 /// standard builtin declaration with one that uses the same address space 6125 /// as the call. 6126 /// 6127 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6128 /// it does not contain any pointer arguments without 6129 /// an address space qualifer. Otherwise the rewritten 6130 /// FunctionDecl is returned. 6131 /// TODO: Handle pointer return types. 6132 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6133 FunctionDecl *FDecl, 6134 MultiExprArg ArgExprs) { 6135 6136 QualType DeclType = FDecl->getType(); 6137 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6138 6139 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6140 ArgExprs.size() < FT->getNumParams()) 6141 return nullptr; 6142 6143 bool NeedsNewDecl = false; 6144 unsigned i = 0; 6145 SmallVector<QualType, 8> OverloadParams; 6146 6147 for (QualType ParamType : FT->param_types()) { 6148 6149 // Convert array arguments to pointer to simplify type lookup. 6150 ExprResult ArgRes = 6151 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6152 if (ArgRes.isInvalid()) 6153 return nullptr; 6154 Expr *Arg = ArgRes.get(); 6155 QualType ArgType = Arg->getType(); 6156 if (!ParamType->isPointerType() || 6157 ParamType.hasAddressSpace() || 6158 !ArgType->isPointerType() || 6159 !ArgType->getPointeeType().hasAddressSpace()) { 6160 OverloadParams.push_back(ParamType); 6161 continue; 6162 } 6163 6164 QualType PointeeType = ParamType->getPointeeType(); 6165 if (PointeeType.hasAddressSpace()) 6166 continue; 6167 6168 NeedsNewDecl = true; 6169 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6170 6171 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6172 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6173 } 6174 6175 if (!NeedsNewDecl) 6176 return nullptr; 6177 6178 FunctionProtoType::ExtProtoInfo EPI; 6179 EPI.Variadic = FT->isVariadic(); 6180 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6181 OverloadParams, EPI); 6182 DeclContext *Parent = FDecl->getParent(); 6183 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6184 FDecl->getLocation(), 6185 FDecl->getLocation(), 6186 FDecl->getIdentifier(), 6187 OverloadTy, 6188 /*TInfo=*/nullptr, 6189 SC_Extern, false, 6190 /*hasPrototype=*/true); 6191 SmallVector<ParmVarDecl*, 16> Params; 6192 FT = cast<FunctionProtoType>(OverloadTy); 6193 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6194 QualType ParamType = FT->getParamType(i); 6195 ParmVarDecl *Parm = 6196 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6197 SourceLocation(), nullptr, ParamType, 6198 /*TInfo=*/nullptr, SC_None, nullptr); 6199 Parm->setScopeInfo(0, i); 6200 Params.push_back(Parm); 6201 } 6202 OverloadDecl->setParams(Params); 6203 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6204 return OverloadDecl; 6205 } 6206 6207 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6208 FunctionDecl *Callee, 6209 MultiExprArg ArgExprs) { 6210 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6211 // similar attributes) really don't like it when functions are called with an 6212 // invalid number of args. 6213 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6214 /*PartialOverloading=*/false) && 6215 !Callee->isVariadic()) 6216 return; 6217 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6218 return; 6219 6220 if (const EnableIfAttr *Attr = 6221 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6222 S.Diag(Fn->getBeginLoc(), 6223 isa<CXXMethodDecl>(Callee) 6224 ? diag::err_ovl_no_viable_member_function_in_call 6225 : diag::err_ovl_no_viable_function_in_call) 6226 << Callee << Callee->getSourceRange(); 6227 S.Diag(Callee->getLocation(), 6228 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6229 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6230 return; 6231 } 6232 } 6233 6234 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6235 const UnresolvedMemberExpr *const UME, Sema &S) { 6236 6237 const auto GetFunctionLevelDCIfCXXClass = 6238 [](Sema &S) -> const CXXRecordDecl * { 6239 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6240 if (!DC || !DC->getParent()) 6241 return nullptr; 6242 6243 // If the call to some member function was made from within a member 6244 // function body 'M' return return 'M's parent. 6245 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6246 return MD->getParent()->getCanonicalDecl(); 6247 // else the call was made from within a default member initializer of a 6248 // class, so return the class. 6249 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6250 return RD->getCanonicalDecl(); 6251 return nullptr; 6252 }; 6253 // If our DeclContext is neither a member function nor a class (in the 6254 // case of a lambda in a default member initializer), we can't have an 6255 // enclosing 'this'. 6256 6257 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6258 if (!CurParentClass) 6259 return false; 6260 6261 // The naming class for implicit member functions call is the class in which 6262 // name lookup starts. 6263 const CXXRecordDecl *const NamingClass = 6264 UME->getNamingClass()->getCanonicalDecl(); 6265 assert(NamingClass && "Must have naming class even for implicit access"); 6266 6267 // If the unresolved member functions were found in a 'naming class' that is 6268 // related (either the same or derived from) to the class that contains the 6269 // member function that itself contained the implicit member access. 6270 6271 return CurParentClass == NamingClass || 6272 CurParentClass->isDerivedFrom(NamingClass); 6273 } 6274 6275 static void 6276 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6277 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6278 6279 if (!UME) 6280 return; 6281 6282 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6283 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6284 // already been captured, or if this is an implicit member function call (if 6285 // it isn't, an attempt to capture 'this' should already have been made). 6286 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6287 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6288 return; 6289 6290 // Check if the naming class in which the unresolved members were found is 6291 // related (same as or is a base of) to the enclosing class. 6292 6293 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6294 return; 6295 6296 6297 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6298 // If the enclosing function is not dependent, then this lambda is 6299 // capture ready, so if we can capture this, do so. 6300 if (!EnclosingFunctionCtx->isDependentContext()) { 6301 // If the current lambda and all enclosing lambdas can capture 'this' - 6302 // then go ahead and capture 'this' (since our unresolved overload set 6303 // contains at least one non-static member function). 6304 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6305 S.CheckCXXThisCapture(CallLoc); 6306 } else if (S.CurContext->isDependentContext()) { 6307 // ... since this is an implicit member reference, that might potentially 6308 // involve a 'this' capture, mark 'this' for potential capture in 6309 // enclosing lambdas. 6310 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6311 CurLSI->addPotentialThisCapture(CallLoc); 6312 } 6313 } 6314 6315 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6316 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6317 Expr *ExecConfig) { 6318 ExprResult Call = 6319 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6320 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6321 if (Call.isInvalid()) 6322 return Call; 6323 6324 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6325 // language modes. 6326 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6327 if (ULE->hasExplicitTemplateArgs() && 6328 ULE->decls_begin() == ULE->decls_end()) { 6329 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6330 ? diag::warn_cxx17_compat_adl_only_template_id 6331 : diag::ext_adl_only_template_id) 6332 << ULE->getName(); 6333 } 6334 } 6335 6336 if (LangOpts.OpenMP) 6337 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6338 ExecConfig); 6339 6340 return Call; 6341 } 6342 6343 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6344 /// This provides the location of the left/right parens and a list of comma 6345 /// locations. 6346 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6347 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6348 Expr *ExecConfig, bool IsExecConfig, 6349 bool AllowRecovery) { 6350 // Since this might be a postfix expression, get rid of ParenListExprs. 6351 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6352 if (Result.isInvalid()) return ExprError(); 6353 Fn = Result.get(); 6354 6355 if (checkArgsForPlaceholders(*this, ArgExprs)) 6356 return ExprError(); 6357 6358 if (getLangOpts().CPlusPlus) { 6359 // If this is a pseudo-destructor expression, build the call immediately. 6360 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6361 if (!ArgExprs.empty()) { 6362 // Pseudo-destructor calls should not have any arguments. 6363 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6364 << FixItHint::CreateRemoval( 6365 SourceRange(ArgExprs.front()->getBeginLoc(), 6366 ArgExprs.back()->getEndLoc())); 6367 } 6368 6369 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6370 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6371 } 6372 if (Fn->getType() == Context.PseudoObjectTy) { 6373 ExprResult result = CheckPlaceholderExpr(Fn); 6374 if (result.isInvalid()) return ExprError(); 6375 Fn = result.get(); 6376 } 6377 6378 // Determine whether this is a dependent call inside a C++ template, 6379 // in which case we won't do any semantic analysis now. 6380 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6381 if (ExecConfig) { 6382 return CUDAKernelCallExpr::Create( 6383 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6384 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6385 } else { 6386 6387 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6388 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6389 Fn->getBeginLoc()); 6390 6391 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6392 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6393 } 6394 } 6395 6396 // Determine whether this is a call to an object (C++ [over.call.object]). 6397 if (Fn->getType()->isRecordType()) 6398 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6399 RParenLoc); 6400 6401 if (Fn->getType() == Context.UnknownAnyTy) { 6402 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6403 if (result.isInvalid()) return ExprError(); 6404 Fn = result.get(); 6405 } 6406 6407 if (Fn->getType() == Context.BoundMemberTy) { 6408 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6409 RParenLoc, AllowRecovery); 6410 } 6411 } 6412 6413 // Check for overloaded calls. This can happen even in C due to extensions. 6414 if (Fn->getType() == Context.OverloadTy) { 6415 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6416 6417 // We aren't supposed to apply this logic if there's an '&' involved. 6418 if (!find.HasFormOfMemberPointer) { 6419 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6420 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6421 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6422 OverloadExpr *ovl = find.Expression; 6423 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6424 return BuildOverloadedCallExpr( 6425 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6426 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6427 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6428 RParenLoc, AllowRecovery); 6429 } 6430 } 6431 6432 // If we're directly calling a function, get the appropriate declaration. 6433 if (Fn->getType() == Context.UnknownAnyTy) { 6434 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6435 if (result.isInvalid()) return ExprError(); 6436 Fn = result.get(); 6437 } 6438 6439 Expr *NakedFn = Fn->IgnoreParens(); 6440 6441 bool CallingNDeclIndirectly = false; 6442 NamedDecl *NDecl = nullptr; 6443 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6444 if (UnOp->getOpcode() == UO_AddrOf) { 6445 CallingNDeclIndirectly = true; 6446 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6447 } 6448 } 6449 6450 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6451 NDecl = DRE->getDecl(); 6452 6453 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6454 if (FDecl && FDecl->getBuiltinID()) { 6455 // Rewrite the function decl for this builtin by replacing parameters 6456 // with no explicit address space with the address space of the arguments 6457 // in ArgExprs. 6458 if ((FDecl = 6459 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6460 NDecl = FDecl; 6461 Fn = DeclRefExpr::Create( 6462 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6463 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6464 nullptr, DRE->isNonOdrUse()); 6465 } 6466 } 6467 } else if (isa<MemberExpr>(NakedFn)) 6468 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6469 6470 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6471 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6472 FD, /*Complain=*/true, Fn->getBeginLoc())) 6473 return ExprError(); 6474 6475 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6476 return ExprError(); 6477 6478 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6479 } 6480 6481 if (Context.isDependenceAllowed() && 6482 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6483 assert(!getLangOpts().CPlusPlus); 6484 assert((Fn->containsErrors() || 6485 llvm::any_of(ArgExprs, 6486 [](clang::Expr *E) { return E->containsErrors(); })) && 6487 "should only occur in error-recovery path."); 6488 QualType ReturnType = 6489 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6490 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6491 : Context.DependentTy; 6492 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6493 Expr::getValueKindForType(ReturnType), RParenLoc, 6494 CurFPFeatureOverrides()); 6495 } 6496 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6497 ExecConfig, IsExecConfig); 6498 } 6499 6500 /// Parse a __builtin_astype expression. 6501 /// 6502 /// __builtin_astype( value, dst type ) 6503 /// 6504 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6505 SourceLocation BuiltinLoc, 6506 SourceLocation RParenLoc) { 6507 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6508 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6509 } 6510 6511 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6512 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6513 SourceLocation BuiltinLoc, 6514 SourceLocation RParenLoc) { 6515 ExprValueKind VK = VK_RValue; 6516 ExprObjectKind OK = OK_Ordinary; 6517 QualType SrcTy = E->getType(); 6518 if (!SrcTy->isDependentType() && 6519 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6520 return ExprError( 6521 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6522 << DestTy << SrcTy << E->getSourceRange()); 6523 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6524 } 6525 6526 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6527 /// provided arguments. 6528 /// 6529 /// __builtin_convertvector( value, dst type ) 6530 /// 6531 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6532 SourceLocation BuiltinLoc, 6533 SourceLocation RParenLoc) { 6534 TypeSourceInfo *TInfo; 6535 GetTypeFromParser(ParsedDestTy, &TInfo); 6536 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6537 } 6538 6539 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6540 /// i.e. an expression not of \p OverloadTy. The expression should 6541 /// unary-convert to an expression of function-pointer or 6542 /// block-pointer type. 6543 /// 6544 /// \param NDecl the declaration being called, if available 6545 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6546 SourceLocation LParenLoc, 6547 ArrayRef<Expr *> Args, 6548 SourceLocation RParenLoc, Expr *Config, 6549 bool IsExecConfig, ADLCallKind UsesADL) { 6550 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6551 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6552 6553 // Functions with 'interrupt' attribute cannot be called directly. 6554 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6555 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6556 return ExprError(); 6557 } 6558 6559 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6560 // so there's some risk when calling out to non-interrupt handler functions 6561 // that the callee might not preserve them. This is easy to diagnose here, 6562 // but can be very challenging to debug. 6563 // Likewise, X86 interrupt handlers may only call routines with attribute 6564 // no_caller_saved_registers since there is no efficient way to 6565 // save and restore the non-GPR state. 6566 if (auto *Caller = getCurFunctionDecl()) { 6567 if (Caller->hasAttr<ARMInterruptAttr>()) { 6568 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6569 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6570 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6571 if (FDecl) 6572 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6573 } 6574 } 6575 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6576 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6577 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_regsave); 6578 if (FDecl) 6579 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6580 } 6581 } 6582 6583 // Promote the function operand. 6584 // We special-case function promotion here because we only allow promoting 6585 // builtin functions to function pointers in the callee of a call. 6586 ExprResult Result; 6587 QualType ResultTy; 6588 if (BuiltinID && 6589 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6590 // Extract the return type from the (builtin) function pointer type. 6591 // FIXME Several builtins still have setType in 6592 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6593 // Builtins.def to ensure they are correct before removing setType calls. 6594 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6595 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6596 ResultTy = FDecl->getCallResultType(); 6597 } else { 6598 Result = CallExprUnaryConversions(Fn); 6599 ResultTy = Context.BoolTy; 6600 } 6601 if (Result.isInvalid()) 6602 return ExprError(); 6603 Fn = Result.get(); 6604 6605 // Check for a valid function type, but only if it is not a builtin which 6606 // requires custom type checking. These will be handled by 6607 // CheckBuiltinFunctionCall below just after creation of the call expression. 6608 const FunctionType *FuncT = nullptr; 6609 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6610 retry: 6611 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6612 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6613 // have type pointer to function". 6614 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6615 if (!FuncT) 6616 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6617 << Fn->getType() << Fn->getSourceRange()); 6618 } else if (const BlockPointerType *BPT = 6619 Fn->getType()->getAs<BlockPointerType>()) { 6620 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6621 } else { 6622 // Handle calls to expressions of unknown-any type. 6623 if (Fn->getType() == Context.UnknownAnyTy) { 6624 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6625 if (rewrite.isInvalid()) 6626 return ExprError(); 6627 Fn = rewrite.get(); 6628 goto retry; 6629 } 6630 6631 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6632 << Fn->getType() << Fn->getSourceRange()); 6633 } 6634 } 6635 6636 // Get the number of parameters in the function prototype, if any. 6637 // We will allocate space for max(Args.size(), NumParams) arguments 6638 // in the call expression. 6639 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6640 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6641 6642 CallExpr *TheCall; 6643 if (Config) { 6644 assert(UsesADL == ADLCallKind::NotADL && 6645 "CUDAKernelCallExpr should not use ADL"); 6646 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6647 Args, ResultTy, VK_RValue, RParenLoc, 6648 CurFPFeatureOverrides(), NumParams); 6649 } else { 6650 TheCall = 6651 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6652 CurFPFeatureOverrides(), NumParams, UsesADL); 6653 } 6654 6655 if (!Context.isDependenceAllowed()) { 6656 // Forget about the nulled arguments since typo correction 6657 // do not handle them well. 6658 TheCall->shrinkNumArgs(Args.size()); 6659 // C cannot always handle TypoExpr nodes in builtin calls and direct 6660 // function calls as their argument checking don't necessarily handle 6661 // dependent types properly, so make sure any TypoExprs have been 6662 // dealt with. 6663 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6664 if (!Result.isUsable()) return ExprError(); 6665 CallExpr *TheOldCall = TheCall; 6666 TheCall = dyn_cast<CallExpr>(Result.get()); 6667 bool CorrectedTypos = TheCall != TheOldCall; 6668 if (!TheCall) return Result; 6669 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6670 6671 // A new call expression node was created if some typos were corrected. 6672 // However it may not have been constructed with enough storage. In this 6673 // case, rebuild the node with enough storage. The waste of space is 6674 // immaterial since this only happens when some typos were corrected. 6675 if (CorrectedTypos && Args.size() < NumParams) { 6676 if (Config) 6677 TheCall = CUDAKernelCallExpr::Create( 6678 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6679 RParenLoc, CurFPFeatureOverrides(), NumParams); 6680 else 6681 TheCall = 6682 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6683 CurFPFeatureOverrides(), NumParams, UsesADL); 6684 } 6685 // We can now handle the nulled arguments for the default arguments. 6686 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6687 } 6688 6689 // Bail out early if calling a builtin with custom type checking. 6690 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6691 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6692 6693 if (getLangOpts().CUDA) { 6694 if (Config) { 6695 // CUDA: Kernel calls must be to global functions 6696 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6697 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6698 << FDecl << Fn->getSourceRange()); 6699 6700 // CUDA: Kernel function must have 'void' return type 6701 if (!FuncT->getReturnType()->isVoidType() && 6702 !FuncT->getReturnType()->getAs<AutoType>() && 6703 !FuncT->getReturnType()->isInstantiationDependentType()) 6704 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6705 << Fn->getType() << Fn->getSourceRange()); 6706 } else { 6707 // CUDA: Calls to global functions must be configured 6708 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6709 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6710 << FDecl << Fn->getSourceRange()); 6711 } 6712 } 6713 6714 // Check for a valid return type 6715 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6716 FDecl)) 6717 return ExprError(); 6718 6719 // We know the result type of the call, set it. 6720 TheCall->setType(FuncT->getCallResultType(Context)); 6721 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6722 6723 if (Proto) { 6724 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6725 IsExecConfig)) 6726 return ExprError(); 6727 } else { 6728 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6729 6730 if (FDecl) { 6731 // Check if we have too few/too many template arguments, based 6732 // on our knowledge of the function definition. 6733 const FunctionDecl *Def = nullptr; 6734 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6735 Proto = Def->getType()->getAs<FunctionProtoType>(); 6736 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6737 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6738 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6739 } 6740 6741 // If the function we're calling isn't a function prototype, but we have 6742 // a function prototype from a prior declaratiom, use that prototype. 6743 if (!FDecl->hasPrototype()) 6744 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6745 } 6746 6747 // Promote the arguments (C99 6.5.2.2p6). 6748 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6749 Expr *Arg = Args[i]; 6750 6751 if (Proto && i < Proto->getNumParams()) { 6752 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6753 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6754 ExprResult ArgE = 6755 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6756 if (ArgE.isInvalid()) 6757 return true; 6758 6759 Arg = ArgE.getAs<Expr>(); 6760 6761 } else { 6762 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6763 6764 if (ArgE.isInvalid()) 6765 return true; 6766 6767 Arg = ArgE.getAs<Expr>(); 6768 } 6769 6770 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6771 diag::err_call_incomplete_argument, Arg)) 6772 return ExprError(); 6773 6774 TheCall->setArg(i, Arg); 6775 } 6776 } 6777 6778 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6779 if (!Method->isStatic()) 6780 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6781 << Fn->getSourceRange()); 6782 6783 // Check for sentinels 6784 if (NDecl) 6785 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6786 6787 // Warn for unions passing across security boundary (CMSE). 6788 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6789 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6790 if (const auto *RT = 6791 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6792 if (RT->getDecl()->isOrContainsUnion()) 6793 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6794 << 0 << i; 6795 } 6796 } 6797 } 6798 6799 // Do special checking on direct calls to functions. 6800 if (FDecl) { 6801 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6802 return ExprError(); 6803 6804 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6805 6806 if (BuiltinID) 6807 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6808 } else if (NDecl) { 6809 if (CheckPointerCall(NDecl, TheCall, Proto)) 6810 return ExprError(); 6811 } else { 6812 if (CheckOtherCall(TheCall, Proto)) 6813 return ExprError(); 6814 } 6815 6816 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6817 } 6818 6819 ExprResult 6820 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6821 SourceLocation RParenLoc, Expr *InitExpr) { 6822 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6823 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6824 6825 TypeSourceInfo *TInfo; 6826 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6827 if (!TInfo) 6828 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6829 6830 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6831 } 6832 6833 ExprResult 6834 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6835 SourceLocation RParenLoc, Expr *LiteralExpr) { 6836 QualType literalType = TInfo->getType(); 6837 6838 if (literalType->isArrayType()) { 6839 if (RequireCompleteSizedType( 6840 LParenLoc, Context.getBaseElementType(literalType), 6841 diag::err_array_incomplete_or_sizeless_type, 6842 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6843 return ExprError(); 6844 if (literalType->isVariableArrayType()) 6845 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6846 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6847 } else if (!literalType->isDependentType() && 6848 RequireCompleteType(LParenLoc, literalType, 6849 diag::err_typecheck_decl_incomplete_type, 6850 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6851 return ExprError(); 6852 6853 InitializedEntity Entity 6854 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6855 InitializationKind Kind 6856 = InitializationKind::CreateCStyleCast(LParenLoc, 6857 SourceRange(LParenLoc, RParenLoc), 6858 /*InitList=*/true); 6859 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6860 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6861 &literalType); 6862 if (Result.isInvalid()) 6863 return ExprError(); 6864 LiteralExpr = Result.get(); 6865 6866 bool isFileScope = !CurContext->isFunctionOrMethod(); 6867 6868 // In C, compound literals are l-values for some reason. 6869 // For GCC compatibility, in C++, file-scope array compound literals with 6870 // constant initializers are also l-values, and compound literals are 6871 // otherwise prvalues. 6872 // 6873 // (GCC also treats C++ list-initialized file-scope array prvalues with 6874 // constant initializers as l-values, but that's non-conforming, so we don't 6875 // follow it there.) 6876 // 6877 // FIXME: It would be better to handle the lvalue cases as materializing and 6878 // lifetime-extending a temporary object, but our materialized temporaries 6879 // representation only supports lifetime extension from a variable, not "out 6880 // of thin air". 6881 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6882 // is bound to the result of applying array-to-pointer decay to the compound 6883 // literal. 6884 // FIXME: GCC supports compound literals of reference type, which should 6885 // obviously have a value kind derived from the kind of reference involved. 6886 ExprValueKind VK = 6887 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6888 ? VK_RValue 6889 : VK_LValue; 6890 6891 if (isFileScope) 6892 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6893 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6894 Expr *Init = ILE->getInit(i); 6895 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6896 } 6897 6898 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6899 VK, LiteralExpr, isFileScope); 6900 if (isFileScope) { 6901 if (!LiteralExpr->isTypeDependent() && 6902 !LiteralExpr->isValueDependent() && 6903 !literalType->isDependentType()) // C99 6.5.2.5p3 6904 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6905 return ExprError(); 6906 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6907 literalType.getAddressSpace() != LangAS::Default) { 6908 // Embedded-C extensions to C99 6.5.2.5: 6909 // "If the compound literal occurs inside the body of a function, the 6910 // type name shall not be qualified by an address-space qualifier." 6911 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6912 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6913 return ExprError(); 6914 } 6915 6916 if (!isFileScope && !getLangOpts().CPlusPlus) { 6917 // Compound literals that have automatic storage duration are destroyed at 6918 // the end of the scope in C; in C++, they're just temporaries. 6919 6920 // Emit diagnostics if it is or contains a C union type that is non-trivial 6921 // to destruct. 6922 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6923 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6924 NTCUC_CompoundLiteral, NTCUK_Destruct); 6925 6926 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6927 if (literalType.isDestructedType()) { 6928 Cleanup.setExprNeedsCleanups(true); 6929 ExprCleanupObjects.push_back(E); 6930 getCurFunction()->setHasBranchProtectedScope(); 6931 } 6932 } 6933 6934 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6935 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6936 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6937 E->getInitializer()->getExprLoc()); 6938 6939 return MaybeBindToTemporary(E); 6940 } 6941 6942 ExprResult 6943 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6944 SourceLocation RBraceLoc) { 6945 // Only produce each kind of designated initialization diagnostic once. 6946 SourceLocation FirstDesignator; 6947 bool DiagnosedArrayDesignator = false; 6948 bool DiagnosedNestedDesignator = false; 6949 bool DiagnosedMixedDesignator = false; 6950 6951 // Check that any designated initializers are syntactically valid in the 6952 // current language mode. 6953 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6954 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6955 if (FirstDesignator.isInvalid()) 6956 FirstDesignator = DIE->getBeginLoc(); 6957 6958 if (!getLangOpts().CPlusPlus) 6959 break; 6960 6961 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6962 DiagnosedNestedDesignator = true; 6963 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6964 << DIE->getDesignatorsSourceRange(); 6965 } 6966 6967 for (auto &Desig : DIE->designators()) { 6968 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6969 DiagnosedArrayDesignator = true; 6970 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6971 << Desig.getSourceRange(); 6972 } 6973 } 6974 6975 if (!DiagnosedMixedDesignator && 6976 !isa<DesignatedInitExpr>(InitArgList[0])) { 6977 DiagnosedMixedDesignator = true; 6978 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6979 << DIE->getSourceRange(); 6980 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6981 << InitArgList[0]->getSourceRange(); 6982 } 6983 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6984 isa<DesignatedInitExpr>(InitArgList[0])) { 6985 DiagnosedMixedDesignator = true; 6986 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6987 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6988 << DIE->getSourceRange(); 6989 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6990 << InitArgList[I]->getSourceRange(); 6991 } 6992 } 6993 6994 if (FirstDesignator.isValid()) { 6995 // Only diagnose designated initiaization as a C++20 extension if we didn't 6996 // already diagnose use of (non-C++20) C99 designator syntax. 6997 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6998 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6999 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7000 ? diag::warn_cxx17_compat_designated_init 7001 : diag::ext_cxx_designated_init); 7002 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7003 Diag(FirstDesignator, diag::ext_designated_init); 7004 } 7005 } 7006 7007 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7008 } 7009 7010 ExprResult 7011 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7012 SourceLocation RBraceLoc) { 7013 // Semantic analysis for initializers is done by ActOnDeclarator() and 7014 // CheckInitializer() - it requires knowledge of the object being initialized. 7015 7016 // Immediately handle non-overload placeholders. Overloads can be 7017 // resolved contextually, but everything else here can't. 7018 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7019 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7020 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7021 7022 // Ignore failures; dropping the entire initializer list because 7023 // of one failure would be terrible for indexing/etc. 7024 if (result.isInvalid()) continue; 7025 7026 InitArgList[I] = result.get(); 7027 } 7028 } 7029 7030 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7031 RBraceLoc); 7032 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7033 return E; 7034 } 7035 7036 /// Do an explicit extend of the given block pointer if we're in ARC. 7037 void Sema::maybeExtendBlockObject(ExprResult &E) { 7038 assert(E.get()->getType()->isBlockPointerType()); 7039 assert(E.get()->isRValue()); 7040 7041 // Only do this in an r-value context. 7042 if (!getLangOpts().ObjCAutoRefCount) return; 7043 7044 E = ImplicitCastExpr::Create( 7045 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7046 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7047 Cleanup.setExprNeedsCleanups(true); 7048 } 7049 7050 /// Prepare a conversion of the given expression to an ObjC object 7051 /// pointer type. 7052 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7053 QualType type = E.get()->getType(); 7054 if (type->isObjCObjectPointerType()) { 7055 return CK_BitCast; 7056 } else if (type->isBlockPointerType()) { 7057 maybeExtendBlockObject(E); 7058 return CK_BlockPointerToObjCPointerCast; 7059 } else { 7060 assert(type->isPointerType()); 7061 return CK_CPointerToObjCPointerCast; 7062 } 7063 } 7064 7065 /// Prepares for a scalar cast, performing all the necessary stages 7066 /// except the final cast and returning the kind required. 7067 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7068 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7069 // Also, callers should have filtered out the invalid cases with 7070 // pointers. Everything else should be possible. 7071 7072 QualType SrcTy = Src.get()->getType(); 7073 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7074 return CK_NoOp; 7075 7076 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7077 case Type::STK_MemberPointer: 7078 llvm_unreachable("member pointer type in C"); 7079 7080 case Type::STK_CPointer: 7081 case Type::STK_BlockPointer: 7082 case Type::STK_ObjCObjectPointer: 7083 switch (DestTy->getScalarTypeKind()) { 7084 case Type::STK_CPointer: { 7085 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7086 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7087 if (SrcAS != DestAS) 7088 return CK_AddressSpaceConversion; 7089 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7090 return CK_NoOp; 7091 return CK_BitCast; 7092 } 7093 case Type::STK_BlockPointer: 7094 return (SrcKind == Type::STK_BlockPointer 7095 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7096 case Type::STK_ObjCObjectPointer: 7097 if (SrcKind == Type::STK_ObjCObjectPointer) 7098 return CK_BitCast; 7099 if (SrcKind == Type::STK_CPointer) 7100 return CK_CPointerToObjCPointerCast; 7101 maybeExtendBlockObject(Src); 7102 return CK_BlockPointerToObjCPointerCast; 7103 case Type::STK_Bool: 7104 return CK_PointerToBoolean; 7105 case Type::STK_Integral: 7106 return CK_PointerToIntegral; 7107 case Type::STK_Floating: 7108 case Type::STK_FloatingComplex: 7109 case Type::STK_IntegralComplex: 7110 case Type::STK_MemberPointer: 7111 case Type::STK_FixedPoint: 7112 llvm_unreachable("illegal cast from pointer"); 7113 } 7114 llvm_unreachable("Should have returned before this"); 7115 7116 case Type::STK_FixedPoint: 7117 switch (DestTy->getScalarTypeKind()) { 7118 case Type::STK_FixedPoint: 7119 return CK_FixedPointCast; 7120 case Type::STK_Bool: 7121 return CK_FixedPointToBoolean; 7122 case Type::STK_Integral: 7123 return CK_FixedPointToIntegral; 7124 case Type::STK_Floating: 7125 return CK_FixedPointToFloating; 7126 case Type::STK_IntegralComplex: 7127 case Type::STK_FloatingComplex: 7128 Diag(Src.get()->getExprLoc(), 7129 diag::err_unimplemented_conversion_with_fixed_point_type) 7130 << DestTy; 7131 return CK_IntegralCast; 7132 case Type::STK_CPointer: 7133 case Type::STK_ObjCObjectPointer: 7134 case Type::STK_BlockPointer: 7135 case Type::STK_MemberPointer: 7136 llvm_unreachable("illegal cast to pointer type"); 7137 } 7138 llvm_unreachable("Should have returned before this"); 7139 7140 case Type::STK_Bool: // casting from bool is like casting from an integer 7141 case Type::STK_Integral: 7142 switch (DestTy->getScalarTypeKind()) { 7143 case Type::STK_CPointer: 7144 case Type::STK_ObjCObjectPointer: 7145 case Type::STK_BlockPointer: 7146 if (Src.get()->isNullPointerConstant(Context, 7147 Expr::NPC_ValueDependentIsNull)) 7148 return CK_NullToPointer; 7149 return CK_IntegralToPointer; 7150 case Type::STK_Bool: 7151 return CK_IntegralToBoolean; 7152 case Type::STK_Integral: 7153 return CK_IntegralCast; 7154 case Type::STK_Floating: 7155 return CK_IntegralToFloating; 7156 case Type::STK_IntegralComplex: 7157 Src = ImpCastExprToType(Src.get(), 7158 DestTy->castAs<ComplexType>()->getElementType(), 7159 CK_IntegralCast); 7160 return CK_IntegralRealToComplex; 7161 case Type::STK_FloatingComplex: 7162 Src = ImpCastExprToType(Src.get(), 7163 DestTy->castAs<ComplexType>()->getElementType(), 7164 CK_IntegralToFloating); 7165 return CK_FloatingRealToComplex; 7166 case Type::STK_MemberPointer: 7167 llvm_unreachable("member pointer type in C"); 7168 case Type::STK_FixedPoint: 7169 return CK_IntegralToFixedPoint; 7170 } 7171 llvm_unreachable("Should have returned before this"); 7172 7173 case Type::STK_Floating: 7174 switch (DestTy->getScalarTypeKind()) { 7175 case Type::STK_Floating: 7176 return CK_FloatingCast; 7177 case Type::STK_Bool: 7178 return CK_FloatingToBoolean; 7179 case Type::STK_Integral: 7180 return CK_FloatingToIntegral; 7181 case Type::STK_FloatingComplex: 7182 Src = ImpCastExprToType(Src.get(), 7183 DestTy->castAs<ComplexType>()->getElementType(), 7184 CK_FloatingCast); 7185 return CK_FloatingRealToComplex; 7186 case Type::STK_IntegralComplex: 7187 Src = ImpCastExprToType(Src.get(), 7188 DestTy->castAs<ComplexType>()->getElementType(), 7189 CK_FloatingToIntegral); 7190 return CK_IntegralRealToComplex; 7191 case Type::STK_CPointer: 7192 case Type::STK_ObjCObjectPointer: 7193 case Type::STK_BlockPointer: 7194 llvm_unreachable("valid float->pointer cast?"); 7195 case Type::STK_MemberPointer: 7196 llvm_unreachable("member pointer type in C"); 7197 case Type::STK_FixedPoint: 7198 return CK_FloatingToFixedPoint; 7199 } 7200 llvm_unreachable("Should have returned before this"); 7201 7202 case Type::STK_FloatingComplex: 7203 switch (DestTy->getScalarTypeKind()) { 7204 case Type::STK_FloatingComplex: 7205 return CK_FloatingComplexCast; 7206 case Type::STK_IntegralComplex: 7207 return CK_FloatingComplexToIntegralComplex; 7208 case Type::STK_Floating: { 7209 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7210 if (Context.hasSameType(ET, DestTy)) 7211 return CK_FloatingComplexToReal; 7212 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7213 return CK_FloatingCast; 7214 } 7215 case Type::STK_Bool: 7216 return CK_FloatingComplexToBoolean; 7217 case Type::STK_Integral: 7218 Src = ImpCastExprToType(Src.get(), 7219 SrcTy->castAs<ComplexType>()->getElementType(), 7220 CK_FloatingComplexToReal); 7221 return CK_FloatingToIntegral; 7222 case Type::STK_CPointer: 7223 case Type::STK_ObjCObjectPointer: 7224 case Type::STK_BlockPointer: 7225 llvm_unreachable("valid complex float->pointer cast?"); 7226 case Type::STK_MemberPointer: 7227 llvm_unreachable("member pointer type in C"); 7228 case Type::STK_FixedPoint: 7229 Diag(Src.get()->getExprLoc(), 7230 diag::err_unimplemented_conversion_with_fixed_point_type) 7231 << SrcTy; 7232 return CK_IntegralCast; 7233 } 7234 llvm_unreachable("Should have returned before this"); 7235 7236 case Type::STK_IntegralComplex: 7237 switch (DestTy->getScalarTypeKind()) { 7238 case Type::STK_FloatingComplex: 7239 return CK_IntegralComplexToFloatingComplex; 7240 case Type::STK_IntegralComplex: 7241 return CK_IntegralComplexCast; 7242 case Type::STK_Integral: { 7243 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7244 if (Context.hasSameType(ET, DestTy)) 7245 return CK_IntegralComplexToReal; 7246 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7247 return CK_IntegralCast; 7248 } 7249 case Type::STK_Bool: 7250 return CK_IntegralComplexToBoolean; 7251 case Type::STK_Floating: 7252 Src = ImpCastExprToType(Src.get(), 7253 SrcTy->castAs<ComplexType>()->getElementType(), 7254 CK_IntegralComplexToReal); 7255 return CK_IntegralToFloating; 7256 case Type::STK_CPointer: 7257 case Type::STK_ObjCObjectPointer: 7258 case Type::STK_BlockPointer: 7259 llvm_unreachable("valid complex int->pointer cast?"); 7260 case Type::STK_MemberPointer: 7261 llvm_unreachable("member pointer type in C"); 7262 case Type::STK_FixedPoint: 7263 Diag(Src.get()->getExprLoc(), 7264 diag::err_unimplemented_conversion_with_fixed_point_type) 7265 << SrcTy; 7266 return CK_IntegralCast; 7267 } 7268 llvm_unreachable("Should have returned before this"); 7269 } 7270 7271 llvm_unreachable("Unhandled scalar cast"); 7272 } 7273 7274 static bool breakDownVectorType(QualType type, uint64_t &len, 7275 QualType &eltType) { 7276 // Vectors are simple. 7277 if (const VectorType *vecType = type->getAs<VectorType>()) { 7278 len = vecType->getNumElements(); 7279 eltType = vecType->getElementType(); 7280 assert(eltType->isScalarType()); 7281 return true; 7282 } 7283 7284 // We allow lax conversion to and from non-vector types, but only if 7285 // they're real types (i.e. non-complex, non-pointer scalar types). 7286 if (!type->isRealType()) return false; 7287 7288 len = 1; 7289 eltType = type; 7290 return true; 7291 } 7292 7293 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7294 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7295 /// allowed? 7296 /// 7297 /// This will also return false if the two given types do not make sense from 7298 /// the perspective of SVE bitcasts. 7299 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7300 assert(srcTy->isVectorType() || destTy->isVectorType()); 7301 7302 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7303 if (!FirstType->isSizelessBuiltinType()) 7304 return false; 7305 7306 const auto *VecTy = SecondType->getAs<VectorType>(); 7307 return VecTy && 7308 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7309 }; 7310 7311 return ValidScalableConversion(srcTy, destTy) || 7312 ValidScalableConversion(destTy, srcTy); 7313 } 7314 7315 /// Are the two types lax-compatible vector types? That is, given 7316 /// that one of them is a vector, do they have equal storage sizes, 7317 /// where the storage size is the number of elements times the element 7318 /// size? 7319 /// 7320 /// This will also return false if either of the types is neither a 7321 /// vector nor a real type. 7322 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7323 assert(destTy->isVectorType() || srcTy->isVectorType()); 7324 7325 // Disallow lax conversions between scalars and ExtVectors (these 7326 // conversions are allowed for other vector types because common headers 7327 // depend on them). Most scalar OP ExtVector cases are handled by the 7328 // splat path anyway, which does what we want (convert, not bitcast). 7329 // What this rules out for ExtVectors is crazy things like char4*float. 7330 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7331 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7332 7333 uint64_t srcLen, destLen; 7334 QualType srcEltTy, destEltTy; 7335 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7336 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7337 7338 // ASTContext::getTypeSize will return the size rounded up to a 7339 // power of 2, so instead of using that, we need to use the raw 7340 // element size multiplied by the element count. 7341 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7342 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7343 7344 return (srcLen * srcEltSize == destLen * destEltSize); 7345 } 7346 7347 /// Is this a legal conversion between two types, one of which is 7348 /// known to be a vector type? 7349 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7350 assert(destTy->isVectorType() || srcTy->isVectorType()); 7351 7352 switch (Context.getLangOpts().getLaxVectorConversions()) { 7353 case LangOptions::LaxVectorConversionKind::None: 7354 return false; 7355 7356 case LangOptions::LaxVectorConversionKind::Integer: 7357 if (!srcTy->isIntegralOrEnumerationType()) { 7358 auto *Vec = srcTy->getAs<VectorType>(); 7359 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7360 return false; 7361 } 7362 if (!destTy->isIntegralOrEnumerationType()) { 7363 auto *Vec = destTy->getAs<VectorType>(); 7364 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7365 return false; 7366 } 7367 // OK, integer (vector) -> integer (vector) bitcast. 7368 break; 7369 7370 case LangOptions::LaxVectorConversionKind::All: 7371 break; 7372 } 7373 7374 return areLaxCompatibleVectorTypes(srcTy, destTy); 7375 } 7376 7377 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7378 CastKind &Kind) { 7379 assert(VectorTy->isVectorType() && "Not a vector type!"); 7380 7381 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7382 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7383 return Diag(R.getBegin(), 7384 Ty->isVectorType() ? 7385 diag::err_invalid_conversion_between_vectors : 7386 diag::err_invalid_conversion_between_vector_and_integer) 7387 << VectorTy << Ty << R; 7388 } else 7389 return Diag(R.getBegin(), 7390 diag::err_invalid_conversion_between_vector_and_scalar) 7391 << VectorTy << Ty << R; 7392 7393 Kind = CK_BitCast; 7394 return false; 7395 } 7396 7397 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7398 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7399 7400 if (DestElemTy == SplattedExpr->getType()) 7401 return SplattedExpr; 7402 7403 assert(DestElemTy->isFloatingType() || 7404 DestElemTy->isIntegralOrEnumerationType()); 7405 7406 CastKind CK; 7407 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7408 // OpenCL requires that we convert `true` boolean expressions to -1, but 7409 // only when splatting vectors. 7410 if (DestElemTy->isFloatingType()) { 7411 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7412 // in two steps: boolean to signed integral, then to floating. 7413 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7414 CK_BooleanToSignedIntegral); 7415 SplattedExpr = CastExprRes.get(); 7416 CK = CK_IntegralToFloating; 7417 } else { 7418 CK = CK_BooleanToSignedIntegral; 7419 } 7420 } else { 7421 ExprResult CastExprRes = SplattedExpr; 7422 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7423 if (CastExprRes.isInvalid()) 7424 return ExprError(); 7425 SplattedExpr = CastExprRes.get(); 7426 } 7427 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7428 } 7429 7430 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7431 Expr *CastExpr, CastKind &Kind) { 7432 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7433 7434 QualType SrcTy = CastExpr->getType(); 7435 7436 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7437 // an ExtVectorType. 7438 // In OpenCL, casts between vectors of different types are not allowed. 7439 // (See OpenCL 6.2). 7440 if (SrcTy->isVectorType()) { 7441 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7442 (getLangOpts().OpenCL && 7443 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7444 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7445 << DestTy << SrcTy << R; 7446 return ExprError(); 7447 } 7448 Kind = CK_BitCast; 7449 return CastExpr; 7450 } 7451 7452 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7453 // conversion will take place first from scalar to elt type, and then 7454 // splat from elt type to vector. 7455 if (SrcTy->isPointerType()) 7456 return Diag(R.getBegin(), 7457 diag::err_invalid_conversion_between_vector_and_scalar) 7458 << DestTy << SrcTy << R; 7459 7460 Kind = CK_VectorSplat; 7461 return prepareVectorSplat(DestTy, CastExpr); 7462 } 7463 7464 ExprResult 7465 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7466 Declarator &D, ParsedType &Ty, 7467 SourceLocation RParenLoc, Expr *CastExpr) { 7468 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7469 "ActOnCastExpr(): missing type or expr"); 7470 7471 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7472 if (D.isInvalidType()) 7473 return ExprError(); 7474 7475 if (getLangOpts().CPlusPlus) { 7476 // Check that there are no default arguments (C++ only). 7477 CheckExtraCXXDefaultArguments(D); 7478 } else { 7479 // Make sure any TypoExprs have been dealt with. 7480 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7481 if (!Res.isUsable()) 7482 return ExprError(); 7483 CastExpr = Res.get(); 7484 } 7485 7486 checkUnusedDeclAttributes(D); 7487 7488 QualType castType = castTInfo->getType(); 7489 Ty = CreateParsedType(castType, castTInfo); 7490 7491 bool isVectorLiteral = false; 7492 7493 // Check for an altivec or OpenCL literal, 7494 // i.e. all the elements are integer constants. 7495 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7496 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7497 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7498 && castType->isVectorType() && (PE || PLE)) { 7499 if (PLE && PLE->getNumExprs() == 0) { 7500 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7501 return ExprError(); 7502 } 7503 if (PE || PLE->getNumExprs() == 1) { 7504 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7505 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7506 isVectorLiteral = true; 7507 } 7508 else 7509 isVectorLiteral = true; 7510 } 7511 7512 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7513 // then handle it as such. 7514 if (isVectorLiteral) 7515 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7516 7517 // If the Expr being casted is a ParenListExpr, handle it specially. 7518 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7519 // sequence of BinOp comma operators. 7520 if (isa<ParenListExpr>(CastExpr)) { 7521 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7522 if (Result.isInvalid()) return ExprError(); 7523 CastExpr = Result.get(); 7524 } 7525 7526 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7527 !getSourceManager().isInSystemMacro(LParenLoc)) 7528 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7529 7530 CheckTollFreeBridgeCast(castType, CastExpr); 7531 7532 CheckObjCBridgeRelatedCast(castType, CastExpr); 7533 7534 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7535 7536 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7537 } 7538 7539 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7540 SourceLocation RParenLoc, Expr *E, 7541 TypeSourceInfo *TInfo) { 7542 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7543 "Expected paren or paren list expression"); 7544 7545 Expr **exprs; 7546 unsigned numExprs; 7547 Expr *subExpr; 7548 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7549 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7550 LiteralLParenLoc = PE->getLParenLoc(); 7551 LiteralRParenLoc = PE->getRParenLoc(); 7552 exprs = PE->getExprs(); 7553 numExprs = PE->getNumExprs(); 7554 } else { // isa<ParenExpr> by assertion at function entrance 7555 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7556 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7557 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7558 exprs = &subExpr; 7559 numExprs = 1; 7560 } 7561 7562 QualType Ty = TInfo->getType(); 7563 assert(Ty->isVectorType() && "Expected vector type"); 7564 7565 SmallVector<Expr *, 8> initExprs; 7566 const VectorType *VTy = Ty->castAs<VectorType>(); 7567 unsigned numElems = VTy->getNumElements(); 7568 7569 // '(...)' form of vector initialization in AltiVec: the number of 7570 // initializers must be one or must match the size of the vector. 7571 // If a single value is specified in the initializer then it will be 7572 // replicated to all the components of the vector 7573 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7574 // The number of initializers must be one or must match the size of the 7575 // vector. If a single value is specified in the initializer then it will 7576 // be replicated to all the components of the vector 7577 if (numExprs == 1) { 7578 QualType ElemTy = VTy->getElementType(); 7579 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7580 if (Literal.isInvalid()) 7581 return ExprError(); 7582 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7583 PrepareScalarCast(Literal, ElemTy)); 7584 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7585 } 7586 else if (numExprs < numElems) { 7587 Diag(E->getExprLoc(), 7588 diag::err_incorrect_number_of_vector_initializers); 7589 return ExprError(); 7590 } 7591 else 7592 initExprs.append(exprs, exprs + numExprs); 7593 } 7594 else { 7595 // For OpenCL, when the number of initializers is a single value, 7596 // it will be replicated to all components of the vector. 7597 if (getLangOpts().OpenCL && 7598 VTy->getVectorKind() == VectorType::GenericVector && 7599 numExprs == 1) { 7600 QualType ElemTy = VTy->getElementType(); 7601 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7602 if (Literal.isInvalid()) 7603 return ExprError(); 7604 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7605 PrepareScalarCast(Literal, ElemTy)); 7606 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7607 } 7608 7609 initExprs.append(exprs, exprs + numExprs); 7610 } 7611 // FIXME: This means that pretty-printing the final AST will produce curly 7612 // braces instead of the original commas. 7613 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7614 initExprs, LiteralRParenLoc); 7615 initE->setType(Ty); 7616 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7617 } 7618 7619 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7620 /// the ParenListExpr into a sequence of comma binary operators. 7621 ExprResult 7622 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7623 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7624 if (!E) 7625 return OrigExpr; 7626 7627 ExprResult Result(E->getExpr(0)); 7628 7629 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7630 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7631 E->getExpr(i)); 7632 7633 if (Result.isInvalid()) return ExprError(); 7634 7635 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7636 } 7637 7638 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7639 SourceLocation R, 7640 MultiExprArg Val) { 7641 return ParenListExpr::Create(Context, L, Val, R); 7642 } 7643 7644 /// Emit a specialized diagnostic when one expression is a null pointer 7645 /// constant and the other is not a pointer. Returns true if a diagnostic is 7646 /// emitted. 7647 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7648 SourceLocation QuestionLoc) { 7649 Expr *NullExpr = LHSExpr; 7650 Expr *NonPointerExpr = RHSExpr; 7651 Expr::NullPointerConstantKind NullKind = 7652 NullExpr->isNullPointerConstant(Context, 7653 Expr::NPC_ValueDependentIsNotNull); 7654 7655 if (NullKind == Expr::NPCK_NotNull) { 7656 NullExpr = RHSExpr; 7657 NonPointerExpr = LHSExpr; 7658 NullKind = 7659 NullExpr->isNullPointerConstant(Context, 7660 Expr::NPC_ValueDependentIsNotNull); 7661 } 7662 7663 if (NullKind == Expr::NPCK_NotNull) 7664 return false; 7665 7666 if (NullKind == Expr::NPCK_ZeroExpression) 7667 return false; 7668 7669 if (NullKind == Expr::NPCK_ZeroLiteral) { 7670 // In this case, check to make sure that we got here from a "NULL" 7671 // string in the source code. 7672 NullExpr = NullExpr->IgnoreParenImpCasts(); 7673 SourceLocation loc = NullExpr->getExprLoc(); 7674 if (!findMacroSpelling(loc, "NULL")) 7675 return false; 7676 } 7677 7678 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7679 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7680 << NonPointerExpr->getType() << DiagType 7681 << NonPointerExpr->getSourceRange(); 7682 return true; 7683 } 7684 7685 /// Return false if the condition expression is valid, true otherwise. 7686 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7687 QualType CondTy = Cond->getType(); 7688 7689 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7690 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7691 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7692 << CondTy << Cond->getSourceRange(); 7693 return true; 7694 } 7695 7696 // C99 6.5.15p2 7697 if (CondTy->isScalarType()) return false; 7698 7699 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7700 << CondTy << Cond->getSourceRange(); 7701 return true; 7702 } 7703 7704 /// Handle when one or both operands are void type. 7705 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7706 ExprResult &RHS) { 7707 Expr *LHSExpr = LHS.get(); 7708 Expr *RHSExpr = RHS.get(); 7709 7710 if (!LHSExpr->getType()->isVoidType()) 7711 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7712 << RHSExpr->getSourceRange(); 7713 if (!RHSExpr->getType()->isVoidType()) 7714 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7715 << LHSExpr->getSourceRange(); 7716 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7717 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7718 return S.Context.VoidTy; 7719 } 7720 7721 /// Return false if the NullExpr can be promoted to PointerTy, 7722 /// true otherwise. 7723 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7724 QualType PointerTy) { 7725 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7726 !NullExpr.get()->isNullPointerConstant(S.Context, 7727 Expr::NPC_ValueDependentIsNull)) 7728 return true; 7729 7730 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7731 return false; 7732 } 7733 7734 /// Checks compatibility between two pointers and return the resulting 7735 /// type. 7736 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7737 ExprResult &RHS, 7738 SourceLocation Loc) { 7739 QualType LHSTy = LHS.get()->getType(); 7740 QualType RHSTy = RHS.get()->getType(); 7741 7742 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7743 // Two identical pointers types are always compatible. 7744 return LHSTy; 7745 } 7746 7747 QualType lhptee, rhptee; 7748 7749 // Get the pointee types. 7750 bool IsBlockPointer = false; 7751 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7752 lhptee = LHSBTy->getPointeeType(); 7753 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7754 IsBlockPointer = true; 7755 } else { 7756 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7757 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7758 } 7759 7760 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7761 // differently qualified versions of compatible types, the result type is 7762 // a pointer to an appropriately qualified version of the composite 7763 // type. 7764 7765 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7766 // clause doesn't make sense for our extensions. E.g. address space 2 should 7767 // be incompatible with address space 3: they may live on different devices or 7768 // anything. 7769 Qualifiers lhQual = lhptee.getQualifiers(); 7770 Qualifiers rhQual = rhptee.getQualifiers(); 7771 7772 LangAS ResultAddrSpace = LangAS::Default; 7773 LangAS LAddrSpace = lhQual.getAddressSpace(); 7774 LangAS RAddrSpace = rhQual.getAddressSpace(); 7775 7776 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7777 // spaces is disallowed. 7778 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7779 ResultAddrSpace = LAddrSpace; 7780 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7781 ResultAddrSpace = RAddrSpace; 7782 else { 7783 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7784 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7785 << RHS.get()->getSourceRange(); 7786 return QualType(); 7787 } 7788 7789 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7790 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7791 lhQual.removeCVRQualifiers(); 7792 rhQual.removeCVRQualifiers(); 7793 7794 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7795 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7796 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7797 // qual types are compatible iff 7798 // * corresponded types are compatible 7799 // * CVR qualifiers are equal 7800 // * address spaces are equal 7801 // Thus for conditional operator we merge CVR and address space unqualified 7802 // pointees and if there is a composite type we return a pointer to it with 7803 // merged qualifiers. 7804 LHSCastKind = 7805 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7806 RHSCastKind = 7807 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7808 lhQual.removeAddressSpace(); 7809 rhQual.removeAddressSpace(); 7810 7811 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7812 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7813 7814 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7815 7816 if (CompositeTy.isNull()) { 7817 // In this situation, we assume void* type. No especially good 7818 // reason, but this is what gcc does, and we do have to pick 7819 // to get a consistent AST. 7820 QualType incompatTy; 7821 incompatTy = S.Context.getPointerType( 7822 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7823 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7824 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7825 7826 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7827 // for casts between types with incompatible address space qualifiers. 7828 // For the following code the compiler produces casts between global and 7829 // local address spaces of the corresponded innermost pointees: 7830 // local int *global *a; 7831 // global int *global *b; 7832 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7833 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7834 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7835 << RHS.get()->getSourceRange(); 7836 7837 return incompatTy; 7838 } 7839 7840 // The pointer types are compatible. 7841 // In case of OpenCL ResultTy should have the address space qualifier 7842 // which is a superset of address spaces of both the 2nd and the 3rd 7843 // operands of the conditional operator. 7844 QualType ResultTy = [&, ResultAddrSpace]() { 7845 if (S.getLangOpts().OpenCL) { 7846 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7847 CompositeQuals.setAddressSpace(ResultAddrSpace); 7848 return S.Context 7849 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7850 .withCVRQualifiers(MergedCVRQual); 7851 } 7852 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7853 }(); 7854 if (IsBlockPointer) 7855 ResultTy = S.Context.getBlockPointerType(ResultTy); 7856 else 7857 ResultTy = S.Context.getPointerType(ResultTy); 7858 7859 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7860 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7861 return ResultTy; 7862 } 7863 7864 /// Return the resulting type when the operands are both block pointers. 7865 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7866 ExprResult &LHS, 7867 ExprResult &RHS, 7868 SourceLocation Loc) { 7869 QualType LHSTy = LHS.get()->getType(); 7870 QualType RHSTy = RHS.get()->getType(); 7871 7872 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7873 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7874 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7875 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7876 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7877 return destType; 7878 } 7879 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7880 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7881 << RHS.get()->getSourceRange(); 7882 return QualType(); 7883 } 7884 7885 // We have 2 block pointer types. 7886 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7887 } 7888 7889 /// Return the resulting type when the operands are both pointers. 7890 static QualType 7891 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7892 ExprResult &RHS, 7893 SourceLocation Loc) { 7894 // get the pointer types 7895 QualType LHSTy = LHS.get()->getType(); 7896 QualType RHSTy = RHS.get()->getType(); 7897 7898 // get the "pointed to" types 7899 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7900 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7901 7902 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7903 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7904 // Figure out necessary qualifiers (C99 6.5.15p6) 7905 QualType destPointee 7906 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7907 QualType destType = S.Context.getPointerType(destPointee); 7908 // Add qualifiers if necessary. 7909 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7910 // Promote to void*. 7911 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7912 return destType; 7913 } 7914 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7915 QualType destPointee 7916 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7917 QualType destType = S.Context.getPointerType(destPointee); 7918 // Add qualifiers if necessary. 7919 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7920 // Promote to void*. 7921 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7922 return destType; 7923 } 7924 7925 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7926 } 7927 7928 /// Return false if the first expression is not an integer and the second 7929 /// expression is not a pointer, true otherwise. 7930 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7931 Expr* PointerExpr, SourceLocation Loc, 7932 bool IsIntFirstExpr) { 7933 if (!PointerExpr->getType()->isPointerType() || 7934 !Int.get()->getType()->isIntegerType()) 7935 return false; 7936 7937 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7938 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7939 7940 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7941 << Expr1->getType() << Expr2->getType() 7942 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7943 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7944 CK_IntegralToPointer); 7945 return true; 7946 } 7947 7948 /// Simple conversion between integer and floating point types. 7949 /// 7950 /// Used when handling the OpenCL conditional operator where the 7951 /// condition is a vector while the other operands are scalar. 7952 /// 7953 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7954 /// types are either integer or floating type. Between the two 7955 /// operands, the type with the higher rank is defined as the "result 7956 /// type". The other operand needs to be promoted to the same type. No 7957 /// other type promotion is allowed. We cannot use 7958 /// UsualArithmeticConversions() for this purpose, since it always 7959 /// promotes promotable types. 7960 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7961 ExprResult &RHS, 7962 SourceLocation QuestionLoc) { 7963 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7964 if (LHS.isInvalid()) 7965 return QualType(); 7966 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7967 if (RHS.isInvalid()) 7968 return QualType(); 7969 7970 // For conversion purposes, we ignore any qualifiers. 7971 // For example, "const float" and "float" are equivalent. 7972 QualType LHSType = 7973 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7974 QualType RHSType = 7975 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7976 7977 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7978 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7979 << LHSType << LHS.get()->getSourceRange(); 7980 return QualType(); 7981 } 7982 7983 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7984 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7985 << RHSType << RHS.get()->getSourceRange(); 7986 return QualType(); 7987 } 7988 7989 // If both types are identical, no conversion is needed. 7990 if (LHSType == RHSType) 7991 return LHSType; 7992 7993 // Now handle "real" floating types (i.e. float, double, long double). 7994 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7995 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7996 /*IsCompAssign = */ false); 7997 7998 // Finally, we have two differing integer types. 7999 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8000 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8001 } 8002 8003 /// Convert scalar operands to a vector that matches the 8004 /// condition in length. 8005 /// 8006 /// Used when handling the OpenCL conditional operator where the 8007 /// condition is a vector while the other operands are scalar. 8008 /// 8009 /// We first compute the "result type" for the scalar operands 8010 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8011 /// into a vector of that type where the length matches the condition 8012 /// vector type. s6.11.6 requires that the element types of the result 8013 /// and the condition must have the same number of bits. 8014 static QualType 8015 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8016 QualType CondTy, SourceLocation QuestionLoc) { 8017 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8018 if (ResTy.isNull()) return QualType(); 8019 8020 const VectorType *CV = CondTy->getAs<VectorType>(); 8021 assert(CV); 8022 8023 // Determine the vector result type 8024 unsigned NumElements = CV->getNumElements(); 8025 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8026 8027 // Ensure that all types have the same number of bits 8028 if (S.Context.getTypeSize(CV->getElementType()) 8029 != S.Context.getTypeSize(ResTy)) { 8030 // Since VectorTy is created internally, it does not pretty print 8031 // with an OpenCL name. Instead, we just print a description. 8032 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8033 SmallString<64> Str; 8034 llvm::raw_svector_ostream OS(Str); 8035 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8036 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8037 << CondTy << OS.str(); 8038 return QualType(); 8039 } 8040 8041 // Convert operands to the vector result type 8042 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8043 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8044 8045 return VectorTy; 8046 } 8047 8048 /// Return false if this is a valid OpenCL condition vector 8049 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8050 SourceLocation QuestionLoc) { 8051 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8052 // integral type. 8053 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8054 assert(CondTy); 8055 QualType EleTy = CondTy->getElementType(); 8056 if (EleTy->isIntegerType()) return false; 8057 8058 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8059 << Cond->getType() << Cond->getSourceRange(); 8060 return true; 8061 } 8062 8063 /// Return false if the vector condition type and the vector 8064 /// result type are compatible. 8065 /// 8066 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8067 /// number of elements, and their element types have the same number 8068 /// of bits. 8069 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8070 SourceLocation QuestionLoc) { 8071 const VectorType *CV = CondTy->getAs<VectorType>(); 8072 const VectorType *RV = VecResTy->getAs<VectorType>(); 8073 assert(CV && RV); 8074 8075 if (CV->getNumElements() != RV->getNumElements()) { 8076 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8077 << CondTy << VecResTy; 8078 return true; 8079 } 8080 8081 QualType CVE = CV->getElementType(); 8082 QualType RVE = RV->getElementType(); 8083 8084 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8085 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8086 << CondTy << VecResTy; 8087 return true; 8088 } 8089 8090 return false; 8091 } 8092 8093 /// Return the resulting type for the conditional operator in 8094 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8095 /// s6.3.i) when the condition is a vector type. 8096 static QualType 8097 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8098 ExprResult &LHS, ExprResult &RHS, 8099 SourceLocation QuestionLoc) { 8100 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8101 if (Cond.isInvalid()) 8102 return QualType(); 8103 QualType CondTy = Cond.get()->getType(); 8104 8105 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8106 return QualType(); 8107 8108 // If either operand is a vector then find the vector type of the 8109 // result as specified in OpenCL v1.1 s6.3.i. 8110 if (LHS.get()->getType()->isVectorType() || 8111 RHS.get()->getType()->isVectorType()) { 8112 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8113 /*isCompAssign*/false, 8114 /*AllowBothBool*/true, 8115 /*AllowBoolConversions*/false); 8116 if (VecResTy.isNull()) return QualType(); 8117 // The result type must match the condition type as specified in 8118 // OpenCL v1.1 s6.11.6. 8119 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8120 return QualType(); 8121 return VecResTy; 8122 } 8123 8124 // Both operands are scalar. 8125 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8126 } 8127 8128 /// Return true if the Expr is block type 8129 static bool checkBlockType(Sema &S, const Expr *E) { 8130 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8131 QualType Ty = CE->getCallee()->getType(); 8132 if (Ty->isBlockPointerType()) { 8133 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8134 return true; 8135 } 8136 } 8137 return false; 8138 } 8139 8140 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8141 /// In that case, LHS = cond. 8142 /// C99 6.5.15 8143 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8144 ExprResult &RHS, ExprValueKind &VK, 8145 ExprObjectKind &OK, 8146 SourceLocation QuestionLoc) { 8147 8148 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8149 if (!LHSResult.isUsable()) return QualType(); 8150 LHS = LHSResult; 8151 8152 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8153 if (!RHSResult.isUsable()) return QualType(); 8154 RHS = RHSResult; 8155 8156 // C++ is sufficiently different to merit its own checker. 8157 if (getLangOpts().CPlusPlus) 8158 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8159 8160 VK = VK_RValue; 8161 OK = OK_Ordinary; 8162 8163 if (Context.isDependenceAllowed() && 8164 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8165 RHS.get()->isTypeDependent())) { 8166 assert(!getLangOpts().CPlusPlus); 8167 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8168 RHS.get()->containsErrors()) && 8169 "should only occur in error-recovery path."); 8170 return Context.DependentTy; 8171 } 8172 8173 // The OpenCL operator with a vector condition is sufficiently 8174 // different to merit its own checker. 8175 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8176 Cond.get()->getType()->isExtVectorType()) 8177 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8178 8179 // First, check the condition. 8180 Cond = UsualUnaryConversions(Cond.get()); 8181 if (Cond.isInvalid()) 8182 return QualType(); 8183 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8184 return QualType(); 8185 8186 // Now check the two expressions. 8187 if (LHS.get()->getType()->isVectorType() || 8188 RHS.get()->getType()->isVectorType()) 8189 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8190 /*AllowBothBool*/true, 8191 /*AllowBoolConversions*/false); 8192 8193 QualType ResTy = 8194 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8195 if (LHS.isInvalid() || RHS.isInvalid()) 8196 return QualType(); 8197 8198 QualType LHSTy = LHS.get()->getType(); 8199 QualType RHSTy = RHS.get()->getType(); 8200 8201 // Diagnose attempts to convert between __float128 and long double where 8202 // such conversions currently can't be handled. 8203 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8204 Diag(QuestionLoc, 8205 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8206 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8207 return QualType(); 8208 } 8209 8210 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8211 // selection operator (?:). 8212 if (getLangOpts().OpenCL && 8213 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8214 return QualType(); 8215 } 8216 8217 // If both operands have arithmetic type, do the usual arithmetic conversions 8218 // to find a common type: C99 6.5.15p3,5. 8219 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8220 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8221 // different sizes, or between ExtInts and other types. 8222 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8223 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8224 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8225 << RHS.get()->getSourceRange(); 8226 return QualType(); 8227 } 8228 8229 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8230 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8231 8232 return ResTy; 8233 } 8234 8235 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8236 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8237 return LHSTy; 8238 } 8239 8240 // If both operands are the same structure or union type, the result is that 8241 // type. 8242 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8243 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8244 if (LHSRT->getDecl() == RHSRT->getDecl()) 8245 // "If both the operands have structure or union type, the result has 8246 // that type." This implies that CV qualifiers are dropped. 8247 return LHSTy.getUnqualifiedType(); 8248 // FIXME: Type of conditional expression must be complete in C mode. 8249 } 8250 8251 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8252 // The following || allows only one side to be void (a GCC-ism). 8253 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8254 return checkConditionalVoidType(*this, LHS, RHS); 8255 } 8256 8257 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8258 // the type of the other operand." 8259 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8260 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8261 8262 // All objective-c pointer type analysis is done here. 8263 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8264 QuestionLoc); 8265 if (LHS.isInvalid() || RHS.isInvalid()) 8266 return QualType(); 8267 if (!compositeType.isNull()) 8268 return compositeType; 8269 8270 8271 // Handle block pointer types. 8272 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8273 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8274 QuestionLoc); 8275 8276 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8277 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8278 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8279 QuestionLoc); 8280 8281 // GCC compatibility: soften pointer/integer mismatch. Note that 8282 // null pointers have been filtered out by this point. 8283 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8284 /*IsIntFirstExpr=*/true)) 8285 return RHSTy; 8286 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8287 /*IsIntFirstExpr=*/false)) 8288 return LHSTy; 8289 8290 // Allow ?: operations in which both operands have the same 8291 // built-in sizeless type. 8292 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8293 return LHSTy; 8294 8295 // Emit a better diagnostic if one of the expressions is a null pointer 8296 // constant and the other is not a pointer type. In this case, the user most 8297 // likely forgot to take the address of the other expression. 8298 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8299 return QualType(); 8300 8301 // Otherwise, the operands are not compatible. 8302 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8303 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8304 << RHS.get()->getSourceRange(); 8305 return QualType(); 8306 } 8307 8308 /// FindCompositeObjCPointerType - Helper method to find composite type of 8309 /// two objective-c pointer types of the two input expressions. 8310 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8311 SourceLocation QuestionLoc) { 8312 QualType LHSTy = LHS.get()->getType(); 8313 QualType RHSTy = RHS.get()->getType(); 8314 8315 // Handle things like Class and struct objc_class*. Here we case the result 8316 // to the pseudo-builtin, because that will be implicitly cast back to the 8317 // redefinition type if an attempt is made to access its fields. 8318 if (LHSTy->isObjCClassType() && 8319 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8320 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8321 return LHSTy; 8322 } 8323 if (RHSTy->isObjCClassType() && 8324 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8325 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8326 return RHSTy; 8327 } 8328 // And the same for struct objc_object* / id 8329 if (LHSTy->isObjCIdType() && 8330 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8331 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8332 return LHSTy; 8333 } 8334 if (RHSTy->isObjCIdType() && 8335 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8336 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8337 return RHSTy; 8338 } 8339 // And the same for struct objc_selector* / SEL 8340 if (Context.isObjCSelType(LHSTy) && 8341 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8342 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8343 return LHSTy; 8344 } 8345 if (Context.isObjCSelType(RHSTy) && 8346 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8347 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8348 return RHSTy; 8349 } 8350 // Check constraints for Objective-C object pointers types. 8351 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8352 8353 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8354 // Two identical object pointer types are always compatible. 8355 return LHSTy; 8356 } 8357 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8358 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8359 QualType compositeType = LHSTy; 8360 8361 // If both operands are interfaces and either operand can be 8362 // assigned to the other, use that type as the composite 8363 // type. This allows 8364 // xxx ? (A*) a : (B*) b 8365 // where B is a subclass of A. 8366 // 8367 // Additionally, as for assignment, if either type is 'id' 8368 // allow silent coercion. Finally, if the types are 8369 // incompatible then make sure to use 'id' as the composite 8370 // type so the result is acceptable for sending messages to. 8371 8372 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8373 // It could return the composite type. 8374 if (!(compositeType = 8375 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8376 // Nothing more to do. 8377 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8378 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8379 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8380 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8381 } else if ((LHSOPT->isObjCQualifiedIdType() || 8382 RHSOPT->isObjCQualifiedIdType()) && 8383 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8384 true)) { 8385 // Need to handle "id<xx>" explicitly. 8386 // GCC allows qualified id and any Objective-C type to devolve to 8387 // id. Currently localizing to here until clear this should be 8388 // part of ObjCQualifiedIdTypesAreCompatible. 8389 compositeType = Context.getObjCIdType(); 8390 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8391 compositeType = Context.getObjCIdType(); 8392 } else { 8393 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8394 << LHSTy << RHSTy 8395 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8396 QualType incompatTy = Context.getObjCIdType(); 8397 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8398 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8399 return incompatTy; 8400 } 8401 // The object pointer types are compatible. 8402 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8403 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8404 return compositeType; 8405 } 8406 // Check Objective-C object pointer types and 'void *' 8407 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8408 if (getLangOpts().ObjCAutoRefCount) { 8409 // ARC forbids the implicit conversion of object pointers to 'void *', 8410 // so these types are not compatible. 8411 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8412 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8413 LHS = RHS = true; 8414 return QualType(); 8415 } 8416 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8417 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8418 QualType destPointee 8419 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8420 QualType destType = Context.getPointerType(destPointee); 8421 // Add qualifiers if necessary. 8422 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8423 // Promote to void*. 8424 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8425 return destType; 8426 } 8427 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8428 if (getLangOpts().ObjCAutoRefCount) { 8429 // ARC forbids the implicit conversion of object pointers to 'void *', 8430 // so these types are not compatible. 8431 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8432 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8433 LHS = RHS = true; 8434 return QualType(); 8435 } 8436 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8437 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8438 QualType destPointee 8439 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8440 QualType destType = Context.getPointerType(destPointee); 8441 // Add qualifiers if necessary. 8442 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8443 // Promote to void*. 8444 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8445 return destType; 8446 } 8447 return QualType(); 8448 } 8449 8450 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8451 /// ParenRange in parentheses. 8452 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8453 const PartialDiagnostic &Note, 8454 SourceRange ParenRange) { 8455 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8456 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8457 EndLoc.isValid()) { 8458 Self.Diag(Loc, Note) 8459 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8460 << FixItHint::CreateInsertion(EndLoc, ")"); 8461 } else { 8462 // We can't display the parentheses, so just show the bare note. 8463 Self.Diag(Loc, Note) << ParenRange; 8464 } 8465 } 8466 8467 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8468 return BinaryOperator::isAdditiveOp(Opc) || 8469 BinaryOperator::isMultiplicativeOp(Opc) || 8470 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8471 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8472 // not any of the logical operators. Bitwise-xor is commonly used as a 8473 // logical-xor because there is no logical-xor operator. The logical 8474 // operators, including uses of xor, have a high false positive rate for 8475 // precedence warnings. 8476 } 8477 8478 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8479 /// expression, either using a built-in or overloaded operator, 8480 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8481 /// expression. 8482 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8483 Expr **RHSExprs) { 8484 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8485 E = E->IgnoreImpCasts(); 8486 E = E->IgnoreConversionOperatorSingleStep(); 8487 E = E->IgnoreImpCasts(); 8488 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8489 E = MTE->getSubExpr(); 8490 E = E->IgnoreImpCasts(); 8491 } 8492 8493 // Built-in binary operator. 8494 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8495 if (IsArithmeticOp(OP->getOpcode())) { 8496 *Opcode = OP->getOpcode(); 8497 *RHSExprs = OP->getRHS(); 8498 return true; 8499 } 8500 } 8501 8502 // Overloaded operator. 8503 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8504 if (Call->getNumArgs() != 2) 8505 return false; 8506 8507 // Make sure this is really a binary operator that is safe to pass into 8508 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8509 OverloadedOperatorKind OO = Call->getOperator(); 8510 if (OO < OO_Plus || OO > OO_Arrow || 8511 OO == OO_PlusPlus || OO == OO_MinusMinus) 8512 return false; 8513 8514 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8515 if (IsArithmeticOp(OpKind)) { 8516 *Opcode = OpKind; 8517 *RHSExprs = Call->getArg(1); 8518 return true; 8519 } 8520 } 8521 8522 return false; 8523 } 8524 8525 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8526 /// or is a logical expression such as (x==y) which has int type, but is 8527 /// commonly interpreted as boolean. 8528 static bool ExprLooksBoolean(Expr *E) { 8529 E = E->IgnoreParenImpCasts(); 8530 8531 if (E->getType()->isBooleanType()) 8532 return true; 8533 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8534 return OP->isComparisonOp() || OP->isLogicalOp(); 8535 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8536 return OP->getOpcode() == UO_LNot; 8537 if (E->getType()->isPointerType()) 8538 return true; 8539 // FIXME: What about overloaded operator calls returning "unspecified boolean 8540 // type"s (commonly pointer-to-members)? 8541 8542 return false; 8543 } 8544 8545 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8546 /// and binary operator are mixed in a way that suggests the programmer assumed 8547 /// the conditional operator has higher precedence, for example: 8548 /// "int x = a + someBinaryCondition ? 1 : 2". 8549 static void DiagnoseConditionalPrecedence(Sema &Self, 8550 SourceLocation OpLoc, 8551 Expr *Condition, 8552 Expr *LHSExpr, 8553 Expr *RHSExpr) { 8554 BinaryOperatorKind CondOpcode; 8555 Expr *CondRHS; 8556 8557 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8558 return; 8559 if (!ExprLooksBoolean(CondRHS)) 8560 return; 8561 8562 // The condition is an arithmetic binary expression, with a right- 8563 // hand side that looks boolean, so warn. 8564 8565 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8566 ? diag::warn_precedence_bitwise_conditional 8567 : diag::warn_precedence_conditional; 8568 8569 Self.Diag(OpLoc, DiagID) 8570 << Condition->getSourceRange() 8571 << BinaryOperator::getOpcodeStr(CondOpcode); 8572 8573 SuggestParentheses( 8574 Self, OpLoc, 8575 Self.PDiag(diag::note_precedence_silence) 8576 << BinaryOperator::getOpcodeStr(CondOpcode), 8577 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8578 8579 SuggestParentheses(Self, OpLoc, 8580 Self.PDiag(diag::note_precedence_conditional_first), 8581 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8582 } 8583 8584 /// Compute the nullability of a conditional expression. 8585 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8586 QualType LHSTy, QualType RHSTy, 8587 ASTContext &Ctx) { 8588 if (!ResTy->isAnyPointerType()) 8589 return ResTy; 8590 8591 auto GetNullability = [&Ctx](QualType Ty) { 8592 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8593 if (Kind) { 8594 // For our purposes, treat _Nullable_result as _Nullable. 8595 if (*Kind == NullabilityKind::NullableResult) 8596 return NullabilityKind::Nullable; 8597 return *Kind; 8598 } 8599 return NullabilityKind::Unspecified; 8600 }; 8601 8602 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8603 NullabilityKind MergedKind; 8604 8605 // Compute nullability of a binary conditional expression. 8606 if (IsBin) { 8607 if (LHSKind == NullabilityKind::NonNull) 8608 MergedKind = NullabilityKind::NonNull; 8609 else 8610 MergedKind = RHSKind; 8611 // Compute nullability of a normal conditional expression. 8612 } else { 8613 if (LHSKind == NullabilityKind::Nullable || 8614 RHSKind == NullabilityKind::Nullable) 8615 MergedKind = NullabilityKind::Nullable; 8616 else if (LHSKind == NullabilityKind::NonNull) 8617 MergedKind = RHSKind; 8618 else if (RHSKind == NullabilityKind::NonNull) 8619 MergedKind = LHSKind; 8620 else 8621 MergedKind = NullabilityKind::Unspecified; 8622 } 8623 8624 // Return if ResTy already has the correct nullability. 8625 if (GetNullability(ResTy) == MergedKind) 8626 return ResTy; 8627 8628 // Strip all nullability from ResTy. 8629 while (ResTy->getNullability(Ctx)) 8630 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8631 8632 // Create a new AttributedType with the new nullability kind. 8633 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8634 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8635 } 8636 8637 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8638 /// in the case of a the GNU conditional expr extension. 8639 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8640 SourceLocation ColonLoc, 8641 Expr *CondExpr, Expr *LHSExpr, 8642 Expr *RHSExpr) { 8643 if (!Context.isDependenceAllowed()) { 8644 // C cannot handle TypoExpr nodes in the condition because it 8645 // doesn't handle dependent types properly, so make sure any TypoExprs have 8646 // been dealt with before checking the operands. 8647 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8648 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8649 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8650 8651 if (!CondResult.isUsable()) 8652 return ExprError(); 8653 8654 if (LHSExpr) { 8655 if (!LHSResult.isUsable()) 8656 return ExprError(); 8657 } 8658 8659 if (!RHSResult.isUsable()) 8660 return ExprError(); 8661 8662 CondExpr = CondResult.get(); 8663 LHSExpr = LHSResult.get(); 8664 RHSExpr = RHSResult.get(); 8665 } 8666 8667 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8668 // was the condition. 8669 OpaqueValueExpr *opaqueValue = nullptr; 8670 Expr *commonExpr = nullptr; 8671 if (!LHSExpr) { 8672 commonExpr = CondExpr; 8673 // Lower out placeholder types first. This is important so that we don't 8674 // try to capture a placeholder. This happens in few cases in C++; such 8675 // as Objective-C++'s dictionary subscripting syntax. 8676 if (commonExpr->hasPlaceholderType()) { 8677 ExprResult result = CheckPlaceholderExpr(commonExpr); 8678 if (!result.isUsable()) return ExprError(); 8679 commonExpr = result.get(); 8680 } 8681 // We usually want to apply unary conversions *before* saving, except 8682 // in the special case of a C++ l-value conditional. 8683 if (!(getLangOpts().CPlusPlus 8684 && !commonExpr->isTypeDependent() 8685 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8686 && commonExpr->isGLValue() 8687 && commonExpr->isOrdinaryOrBitFieldObject() 8688 && RHSExpr->isOrdinaryOrBitFieldObject() 8689 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8690 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8691 if (commonRes.isInvalid()) 8692 return ExprError(); 8693 commonExpr = commonRes.get(); 8694 } 8695 8696 // If the common expression is a class or array prvalue, materialize it 8697 // so that we can safely refer to it multiple times. 8698 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8699 commonExpr->getType()->isArrayType())) { 8700 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8701 if (MatExpr.isInvalid()) 8702 return ExprError(); 8703 commonExpr = MatExpr.get(); 8704 } 8705 8706 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8707 commonExpr->getType(), 8708 commonExpr->getValueKind(), 8709 commonExpr->getObjectKind(), 8710 commonExpr); 8711 LHSExpr = CondExpr = opaqueValue; 8712 } 8713 8714 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8715 ExprValueKind VK = VK_RValue; 8716 ExprObjectKind OK = OK_Ordinary; 8717 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8718 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8719 VK, OK, QuestionLoc); 8720 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8721 RHS.isInvalid()) 8722 return ExprError(); 8723 8724 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8725 RHS.get()); 8726 8727 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8728 8729 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8730 Context); 8731 8732 if (!commonExpr) 8733 return new (Context) 8734 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8735 RHS.get(), result, VK, OK); 8736 8737 return new (Context) BinaryConditionalOperator( 8738 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8739 ColonLoc, result, VK, OK); 8740 } 8741 8742 // Check if we have a conversion between incompatible cmse function pointer 8743 // types, that is, a conversion between a function pointer with the 8744 // cmse_nonsecure_call attribute and one without. 8745 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8746 QualType ToType) { 8747 if (const auto *ToFn = 8748 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8749 if (const auto *FromFn = 8750 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8751 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8752 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8753 8754 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8755 } 8756 } 8757 return false; 8758 } 8759 8760 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8761 // being closely modeled after the C99 spec:-). The odd characteristic of this 8762 // routine is it effectively iqnores the qualifiers on the top level pointee. 8763 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8764 // FIXME: add a couple examples in this comment. 8765 static Sema::AssignConvertType 8766 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8767 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8768 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8769 8770 // get the "pointed to" type (ignoring qualifiers at the top level) 8771 const Type *lhptee, *rhptee; 8772 Qualifiers lhq, rhq; 8773 std::tie(lhptee, lhq) = 8774 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8775 std::tie(rhptee, rhq) = 8776 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8777 8778 Sema::AssignConvertType ConvTy = Sema::Compatible; 8779 8780 // C99 6.5.16.1p1: This following citation is common to constraints 8781 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8782 // qualifiers of the type *pointed to* by the right; 8783 8784 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8785 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8786 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8787 // Ignore lifetime for further calculation. 8788 lhq.removeObjCLifetime(); 8789 rhq.removeObjCLifetime(); 8790 } 8791 8792 if (!lhq.compatiblyIncludes(rhq)) { 8793 // Treat address-space mismatches as fatal. 8794 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8795 return Sema::IncompatiblePointerDiscardsQualifiers; 8796 8797 // It's okay to add or remove GC or lifetime qualifiers when converting to 8798 // and from void*. 8799 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8800 .compatiblyIncludes( 8801 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8802 && (lhptee->isVoidType() || rhptee->isVoidType())) 8803 ; // keep old 8804 8805 // Treat lifetime mismatches as fatal. 8806 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8807 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8808 8809 // For GCC/MS compatibility, other qualifier mismatches are treated 8810 // as still compatible in C. 8811 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8812 } 8813 8814 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8815 // incomplete type and the other is a pointer to a qualified or unqualified 8816 // version of void... 8817 if (lhptee->isVoidType()) { 8818 if (rhptee->isIncompleteOrObjectType()) 8819 return ConvTy; 8820 8821 // As an extension, we allow cast to/from void* to function pointer. 8822 assert(rhptee->isFunctionType()); 8823 return Sema::FunctionVoidPointer; 8824 } 8825 8826 if (rhptee->isVoidType()) { 8827 if (lhptee->isIncompleteOrObjectType()) 8828 return ConvTy; 8829 8830 // As an extension, we allow cast to/from void* to function pointer. 8831 assert(lhptee->isFunctionType()); 8832 return Sema::FunctionVoidPointer; 8833 } 8834 8835 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8836 // unqualified versions of compatible types, ... 8837 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8838 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8839 // Check if the pointee types are compatible ignoring the sign. 8840 // We explicitly check for char so that we catch "char" vs 8841 // "unsigned char" on systems where "char" is unsigned. 8842 if (lhptee->isCharType()) 8843 ltrans = S.Context.UnsignedCharTy; 8844 else if (lhptee->hasSignedIntegerRepresentation()) 8845 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8846 8847 if (rhptee->isCharType()) 8848 rtrans = S.Context.UnsignedCharTy; 8849 else if (rhptee->hasSignedIntegerRepresentation()) 8850 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8851 8852 if (ltrans == rtrans) { 8853 // Types are compatible ignoring the sign. Qualifier incompatibility 8854 // takes priority over sign incompatibility because the sign 8855 // warning can be disabled. 8856 if (ConvTy != Sema::Compatible) 8857 return ConvTy; 8858 8859 return Sema::IncompatiblePointerSign; 8860 } 8861 8862 // If we are a multi-level pointer, it's possible that our issue is simply 8863 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8864 // the eventual target type is the same and the pointers have the same 8865 // level of indirection, this must be the issue. 8866 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8867 do { 8868 std::tie(lhptee, lhq) = 8869 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8870 std::tie(rhptee, rhq) = 8871 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8872 8873 // Inconsistent address spaces at this point is invalid, even if the 8874 // address spaces would be compatible. 8875 // FIXME: This doesn't catch address space mismatches for pointers of 8876 // different nesting levels, like: 8877 // __local int *** a; 8878 // int ** b = a; 8879 // It's not clear how to actually determine when such pointers are 8880 // invalidly incompatible. 8881 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8882 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8883 8884 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8885 8886 if (lhptee == rhptee) 8887 return Sema::IncompatibleNestedPointerQualifiers; 8888 } 8889 8890 // General pointer incompatibility takes priority over qualifiers. 8891 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8892 return Sema::IncompatibleFunctionPointer; 8893 return Sema::IncompatiblePointer; 8894 } 8895 if (!S.getLangOpts().CPlusPlus && 8896 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8897 return Sema::IncompatibleFunctionPointer; 8898 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8899 return Sema::IncompatibleFunctionPointer; 8900 return ConvTy; 8901 } 8902 8903 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8904 /// block pointer types are compatible or whether a block and normal pointer 8905 /// are compatible. It is more restrict than comparing two function pointer 8906 // types. 8907 static Sema::AssignConvertType 8908 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8909 QualType RHSType) { 8910 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8911 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8912 8913 QualType lhptee, rhptee; 8914 8915 // get the "pointed to" type (ignoring qualifiers at the top level) 8916 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8917 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8918 8919 // In C++, the types have to match exactly. 8920 if (S.getLangOpts().CPlusPlus) 8921 return Sema::IncompatibleBlockPointer; 8922 8923 Sema::AssignConvertType ConvTy = Sema::Compatible; 8924 8925 // For blocks we enforce that qualifiers are identical. 8926 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8927 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8928 if (S.getLangOpts().OpenCL) { 8929 LQuals.removeAddressSpace(); 8930 RQuals.removeAddressSpace(); 8931 } 8932 if (LQuals != RQuals) 8933 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8934 8935 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8936 // assignment. 8937 // The current behavior is similar to C++ lambdas. A block might be 8938 // assigned to a variable iff its return type and parameters are compatible 8939 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8940 // an assignment. Presumably it should behave in way that a function pointer 8941 // assignment does in C, so for each parameter and return type: 8942 // * CVR and address space of LHS should be a superset of CVR and address 8943 // space of RHS. 8944 // * unqualified types should be compatible. 8945 if (S.getLangOpts().OpenCL) { 8946 if (!S.Context.typesAreBlockPointerCompatible( 8947 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8948 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8949 return Sema::IncompatibleBlockPointer; 8950 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8951 return Sema::IncompatibleBlockPointer; 8952 8953 return ConvTy; 8954 } 8955 8956 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8957 /// for assignment compatibility. 8958 static Sema::AssignConvertType 8959 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8960 QualType RHSType) { 8961 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8962 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8963 8964 if (LHSType->isObjCBuiltinType()) { 8965 // Class is not compatible with ObjC object pointers. 8966 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8967 !RHSType->isObjCQualifiedClassType()) 8968 return Sema::IncompatiblePointer; 8969 return Sema::Compatible; 8970 } 8971 if (RHSType->isObjCBuiltinType()) { 8972 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8973 !LHSType->isObjCQualifiedClassType()) 8974 return Sema::IncompatiblePointer; 8975 return Sema::Compatible; 8976 } 8977 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8978 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8979 8980 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8981 // make an exception for id<P> 8982 !LHSType->isObjCQualifiedIdType()) 8983 return Sema::CompatiblePointerDiscardsQualifiers; 8984 8985 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8986 return Sema::Compatible; 8987 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8988 return Sema::IncompatibleObjCQualifiedId; 8989 return Sema::IncompatiblePointer; 8990 } 8991 8992 Sema::AssignConvertType 8993 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8994 QualType LHSType, QualType RHSType) { 8995 // Fake up an opaque expression. We don't actually care about what 8996 // cast operations are required, so if CheckAssignmentConstraints 8997 // adds casts to this they'll be wasted, but fortunately that doesn't 8998 // usually happen on valid code. 8999 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 9000 ExprResult RHSPtr = &RHSExpr; 9001 CastKind K; 9002 9003 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9004 } 9005 9006 /// This helper function returns true if QT is a vector type that has element 9007 /// type ElementType. 9008 static bool isVector(QualType QT, QualType ElementType) { 9009 if (const VectorType *VT = QT->getAs<VectorType>()) 9010 return VT->getElementType().getCanonicalType() == ElementType; 9011 return false; 9012 } 9013 9014 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9015 /// has code to accommodate several GCC extensions when type checking 9016 /// pointers. Here are some objectionable examples that GCC considers warnings: 9017 /// 9018 /// int a, *pint; 9019 /// short *pshort; 9020 /// struct foo *pfoo; 9021 /// 9022 /// pint = pshort; // warning: assignment from incompatible pointer type 9023 /// a = pint; // warning: assignment makes integer from pointer without a cast 9024 /// pint = a; // warning: assignment makes pointer from integer without a cast 9025 /// pint = pfoo; // warning: assignment from incompatible pointer type 9026 /// 9027 /// As a result, the code for dealing with pointers is more complex than the 9028 /// C99 spec dictates. 9029 /// 9030 /// Sets 'Kind' for any result kind except Incompatible. 9031 Sema::AssignConvertType 9032 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9033 CastKind &Kind, bool ConvertRHS) { 9034 QualType RHSType = RHS.get()->getType(); 9035 QualType OrigLHSType = LHSType; 9036 9037 // Get canonical types. We're not formatting these types, just comparing 9038 // them. 9039 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9040 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9041 9042 // Common case: no conversion required. 9043 if (LHSType == RHSType) { 9044 Kind = CK_NoOp; 9045 return Compatible; 9046 } 9047 9048 // If we have an atomic type, try a non-atomic assignment, then just add an 9049 // atomic qualification step. 9050 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9051 Sema::AssignConvertType result = 9052 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9053 if (result != Compatible) 9054 return result; 9055 if (Kind != CK_NoOp && ConvertRHS) 9056 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9057 Kind = CK_NonAtomicToAtomic; 9058 return Compatible; 9059 } 9060 9061 // If the left-hand side is a reference type, then we are in a 9062 // (rare!) case where we've allowed the use of references in C, 9063 // e.g., as a parameter type in a built-in function. In this case, 9064 // just make sure that the type referenced is compatible with the 9065 // right-hand side type. The caller is responsible for adjusting 9066 // LHSType so that the resulting expression does not have reference 9067 // type. 9068 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9069 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9070 Kind = CK_LValueBitCast; 9071 return Compatible; 9072 } 9073 return Incompatible; 9074 } 9075 9076 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9077 // to the same ExtVector type. 9078 if (LHSType->isExtVectorType()) { 9079 if (RHSType->isExtVectorType()) 9080 return Incompatible; 9081 if (RHSType->isArithmeticType()) { 9082 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9083 if (ConvertRHS) 9084 RHS = prepareVectorSplat(LHSType, RHS.get()); 9085 Kind = CK_VectorSplat; 9086 return Compatible; 9087 } 9088 } 9089 9090 // Conversions to or from vector type. 9091 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9092 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9093 // Allow assignments of an AltiVec vector type to an equivalent GCC 9094 // vector type and vice versa 9095 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9096 Kind = CK_BitCast; 9097 return Compatible; 9098 } 9099 9100 // If we are allowing lax vector conversions, and LHS and RHS are both 9101 // vectors, the total size only needs to be the same. This is a bitcast; 9102 // no bits are changed but the result type is different. 9103 if (isLaxVectorConversion(RHSType, LHSType)) { 9104 Kind = CK_BitCast; 9105 return IncompatibleVectors; 9106 } 9107 } 9108 9109 // When the RHS comes from another lax conversion (e.g. binops between 9110 // scalars and vectors) the result is canonicalized as a vector. When the 9111 // LHS is also a vector, the lax is allowed by the condition above. Handle 9112 // the case where LHS is a scalar. 9113 if (LHSType->isScalarType()) { 9114 const VectorType *VecType = RHSType->getAs<VectorType>(); 9115 if (VecType && VecType->getNumElements() == 1 && 9116 isLaxVectorConversion(RHSType, LHSType)) { 9117 ExprResult *VecExpr = &RHS; 9118 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9119 Kind = CK_BitCast; 9120 return Compatible; 9121 } 9122 } 9123 9124 // Allow assignments between fixed-length and sizeless SVE vectors. 9125 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9126 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9127 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9128 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9129 Kind = CK_BitCast; 9130 return Compatible; 9131 } 9132 9133 return Incompatible; 9134 } 9135 9136 // Diagnose attempts to convert between __float128 and long double where 9137 // such conversions currently can't be handled. 9138 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9139 return Incompatible; 9140 9141 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9142 // discards the imaginary part. 9143 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9144 !LHSType->getAs<ComplexType>()) 9145 return Incompatible; 9146 9147 // Arithmetic conversions. 9148 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9149 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9150 if (ConvertRHS) 9151 Kind = PrepareScalarCast(RHS, LHSType); 9152 return Compatible; 9153 } 9154 9155 // Conversions to normal pointers. 9156 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9157 // U* -> T* 9158 if (isa<PointerType>(RHSType)) { 9159 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9160 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9161 if (AddrSpaceL != AddrSpaceR) 9162 Kind = CK_AddressSpaceConversion; 9163 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9164 Kind = CK_NoOp; 9165 else 9166 Kind = CK_BitCast; 9167 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9168 } 9169 9170 // int -> T* 9171 if (RHSType->isIntegerType()) { 9172 Kind = CK_IntegralToPointer; // FIXME: null? 9173 return IntToPointer; 9174 } 9175 9176 // C pointers are not compatible with ObjC object pointers, 9177 // with two exceptions: 9178 if (isa<ObjCObjectPointerType>(RHSType)) { 9179 // - conversions to void* 9180 if (LHSPointer->getPointeeType()->isVoidType()) { 9181 Kind = CK_BitCast; 9182 return Compatible; 9183 } 9184 9185 // - conversions from 'Class' to the redefinition type 9186 if (RHSType->isObjCClassType() && 9187 Context.hasSameType(LHSType, 9188 Context.getObjCClassRedefinitionType())) { 9189 Kind = CK_BitCast; 9190 return Compatible; 9191 } 9192 9193 Kind = CK_BitCast; 9194 return IncompatiblePointer; 9195 } 9196 9197 // U^ -> void* 9198 if (RHSType->getAs<BlockPointerType>()) { 9199 if (LHSPointer->getPointeeType()->isVoidType()) { 9200 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9201 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9202 ->getPointeeType() 9203 .getAddressSpace(); 9204 Kind = 9205 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9206 return Compatible; 9207 } 9208 } 9209 9210 return Incompatible; 9211 } 9212 9213 // Conversions to block pointers. 9214 if (isa<BlockPointerType>(LHSType)) { 9215 // U^ -> T^ 9216 if (RHSType->isBlockPointerType()) { 9217 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9218 ->getPointeeType() 9219 .getAddressSpace(); 9220 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9221 ->getPointeeType() 9222 .getAddressSpace(); 9223 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9224 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9225 } 9226 9227 // int or null -> T^ 9228 if (RHSType->isIntegerType()) { 9229 Kind = CK_IntegralToPointer; // FIXME: null 9230 return IntToBlockPointer; 9231 } 9232 9233 // id -> T^ 9234 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9235 Kind = CK_AnyPointerToBlockPointerCast; 9236 return Compatible; 9237 } 9238 9239 // void* -> T^ 9240 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9241 if (RHSPT->getPointeeType()->isVoidType()) { 9242 Kind = CK_AnyPointerToBlockPointerCast; 9243 return Compatible; 9244 } 9245 9246 return Incompatible; 9247 } 9248 9249 // Conversions to Objective-C pointers. 9250 if (isa<ObjCObjectPointerType>(LHSType)) { 9251 // A* -> B* 9252 if (RHSType->isObjCObjectPointerType()) { 9253 Kind = CK_BitCast; 9254 Sema::AssignConvertType result = 9255 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9256 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9257 result == Compatible && 9258 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9259 result = IncompatibleObjCWeakRef; 9260 return result; 9261 } 9262 9263 // int or null -> A* 9264 if (RHSType->isIntegerType()) { 9265 Kind = CK_IntegralToPointer; // FIXME: null 9266 return IntToPointer; 9267 } 9268 9269 // In general, C pointers are not compatible with ObjC object pointers, 9270 // with two exceptions: 9271 if (isa<PointerType>(RHSType)) { 9272 Kind = CK_CPointerToObjCPointerCast; 9273 9274 // - conversions from 'void*' 9275 if (RHSType->isVoidPointerType()) { 9276 return Compatible; 9277 } 9278 9279 // - conversions to 'Class' from its redefinition type 9280 if (LHSType->isObjCClassType() && 9281 Context.hasSameType(RHSType, 9282 Context.getObjCClassRedefinitionType())) { 9283 return Compatible; 9284 } 9285 9286 return IncompatiblePointer; 9287 } 9288 9289 // Only under strict condition T^ is compatible with an Objective-C pointer. 9290 if (RHSType->isBlockPointerType() && 9291 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9292 if (ConvertRHS) 9293 maybeExtendBlockObject(RHS); 9294 Kind = CK_BlockPointerToObjCPointerCast; 9295 return Compatible; 9296 } 9297 9298 return Incompatible; 9299 } 9300 9301 // Conversions from pointers that are not covered by the above. 9302 if (isa<PointerType>(RHSType)) { 9303 // T* -> _Bool 9304 if (LHSType == Context.BoolTy) { 9305 Kind = CK_PointerToBoolean; 9306 return Compatible; 9307 } 9308 9309 // T* -> int 9310 if (LHSType->isIntegerType()) { 9311 Kind = CK_PointerToIntegral; 9312 return PointerToInt; 9313 } 9314 9315 return Incompatible; 9316 } 9317 9318 // Conversions from Objective-C pointers that are not covered by the above. 9319 if (isa<ObjCObjectPointerType>(RHSType)) { 9320 // T* -> _Bool 9321 if (LHSType == Context.BoolTy) { 9322 Kind = CK_PointerToBoolean; 9323 return Compatible; 9324 } 9325 9326 // T* -> int 9327 if (LHSType->isIntegerType()) { 9328 Kind = CK_PointerToIntegral; 9329 return PointerToInt; 9330 } 9331 9332 return Incompatible; 9333 } 9334 9335 // struct A -> struct B 9336 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9337 if (Context.typesAreCompatible(LHSType, RHSType)) { 9338 Kind = CK_NoOp; 9339 return Compatible; 9340 } 9341 } 9342 9343 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9344 Kind = CK_IntToOCLSampler; 9345 return Compatible; 9346 } 9347 9348 return Incompatible; 9349 } 9350 9351 /// Constructs a transparent union from an expression that is 9352 /// used to initialize the transparent union. 9353 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9354 ExprResult &EResult, QualType UnionType, 9355 FieldDecl *Field) { 9356 // Build an initializer list that designates the appropriate member 9357 // of the transparent union. 9358 Expr *E = EResult.get(); 9359 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9360 E, SourceLocation()); 9361 Initializer->setType(UnionType); 9362 Initializer->setInitializedFieldInUnion(Field); 9363 9364 // Build a compound literal constructing a value of the transparent 9365 // union type from this initializer list. 9366 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9367 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9368 VK_RValue, Initializer, false); 9369 } 9370 9371 Sema::AssignConvertType 9372 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9373 ExprResult &RHS) { 9374 QualType RHSType = RHS.get()->getType(); 9375 9376 // If the ArgType is a Union type, we want to handle a potential 9377 // transparent_union GCC extension. 9378 const RecordType *UT = ArgType->getAsUnionType(); 9379 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9380 return Incompatible; 9381 9382 // The field to initialize within the transparent union. 9383 RecordDecl *UD = UT->getDecl(); 9384 FieldDecl *InitField = nullptr; 9385 // It's compatible if the expression matches any of the fields. 9386 for (auto *it : UD->fields()) { 9387 if (it->getType()->isPointerType()) { 9388 // If the transparent union contains a pointer type, we allow: 9389 // 1) void pointer 9390 // 2) null pointer constant 9391 if (RHSType->isPointerType()) 9392 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9393 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9394 InitField = it; 9395 break; 9396 } 9397 9398 if (RHS.get()->isNullPointerConstant(Context, 9399 Expr::NPC_ValueDependentIsNull)) { 9400 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9401 CK_NullToPointer); 9402 InitField = it; 9403 break; 9404 } 9405 } 9406 9407 CastKind Kind; 9408 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9409 == Compatible) { 9410 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9411 InitField = it; 9412 break; 9413 } 9414 } 9415 9416 if (!InitField) 9417 return Incompatible; 9418 9419 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9420 return Compatible; 9421 } 9422 9423 Sema::AssignConvertType 9424 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9425 bool Diagnose, 9426 bool DiagnoseCFAudited, 9427 bool ConvertRHS) { 9428 // We need to be able to tell the caller whether we diagnosed a problem, if 9429 // they ask us to issue diagnostics. 9430 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9431 9432 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9433 // we can't avoid *all* modifications at the moment, so we need some somewhere 9434 // to put the updated value. 9435 ExprResult LocalRHS = CallerRHS; 9436 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9437 9438 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9439 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9440 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9441 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9442 Diag(RHS.get()->getExprLoc(), 9443 diag::warn_noderef_to_dereferenceable_pointer) 9444 << RHS.get()->getSourceRange(); 9445 } 9446 } 9447 } 9448 9449 if (getLangOpts().CPlusPlus) { 9450 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9451 // C++ 5.17p3: If the left operand is not of class type, the 9452 // expression is implicitly converted (C++ 4) to the 9453 // cv-unqualified type of the left operand. 9454 QualType RHSType = RHS.get()->getType(); 9455 if (Diagnose) { 9456 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9457 AA_Assigning); 9458 } else { 9459 ImplicitConversionSequence ICS = 9460 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9461 /*SuppressUserConversions=*/false, 9462 AllowedExplicit::None, 9463 /*InOverloadResolution=*/false, 9464 /*CStyle=*/false, 9465 /*AllowObjCWritebackConversion=*/false); 9466 if (ICS.isFailure()) 9467 return Incompatible; 9468 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9469 ICS, AA_Assigning); 9470 } 9471 if (RHS.isInvalid()) 9472 return Incompatible; 9473 Sema::AssignConvertType result = Compatible; 9474 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9475 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9476 result = IncompatibleObjCWeakRef; 9477 return result; 9478 } 9479 9480 // FIXME: Currently, we fall through and treat C++ classes like C 9481 // structures. 9482 // FIXME: We also fall through for atomics; not sure what should 9483 // happen there, though. 9484 } else if (RHS.get()->getType() == Context.OverloadTy) { 9485 // As a set of extensions to C, we support overloading on functions. These 9486 // functions need to be resolved here. 9487 DeclAccessPair DAP; 9488 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9489 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9490 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9491 else 9492 return Incompatible; 9493 } 9494 9495 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9496 // a null pointer constant. 9497 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9498 LHSType->isBlockPointerType()) && 9499 RHS.get()->isNullPointerConstant(Context, 9500 Expr::NPC_ValueDependentIsNull)) { 9501 if (Diagnose || ConvertRHS) { 9502 CastKind Kind; 9503 CXXCastPath Path; 9504 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9505 /*IgnoreBaseAccess=*/false, Diagnose); 9506 if (ConvertRHS) 9507 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9508 } 9509 return Compatible; 9510 } 9511 9512 // OpenCL queue_t type assignment. 9513 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9514 Context, Expr::NPC_ValueDependentIsNull)) { 9515 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9516 return Compatible; 9517 } 9518 9519 // This check seems unnatural, however it is necessary to ensure the proper 9520 // conversion of functions/arrays. If the conversion were done for all 9521 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9522 // expressions that suppress this implicit conversion (&, sizeof). 9523 // 9524 // Suppress this for references: C++ 8.5.3p5. 9525 if (!LHSType->isReferenceType()) { 9526 // FIXME: We potentially allocate here even if ConvertRHS is false. 9527 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9528 if (RHS.isInvalid()) 9529 return Incompatible; 9530 } 9531 CastKind Kind; 9532 Sema::AssignConvertType result = 9533 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9534 9535 // C99 6.5.16.1p2: The value of the right operand is converted to the 9536 // type of the assignment expression. 9537 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9538 // so that we can use references in built-in functions even in C. 9539 // The getNonReferenceType() call makes sure that the resulting expression 9540 // does not have reference type. 9541 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9542 QualType Ty = LHSType.getNonLValueExprType(Context); 9543 Expr *E = RHS.get(); 9544 9545 // Check for various Objective-C errors. If we are not reporting 9546 // diagnostics and just checking for errors, e.g., during overload 9547 // resolution, return Incompatible to indicate the failure. 9548 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9549 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9550 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9551 if (!Diagnose) 9552 return Incompatible; 9553 } 9554 if (getLangOpts().ObjC && 9555 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9556 E->getType(), E, Diagnose) || 9557 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9558 if (!Diagnose) 9559 return Incompatible; 9560 // Replace the expression with a corrected version and continue so we 9561 // can find further errors. 9562 RHS = E; 9563 return Compatible; 9564 } 9565 9566 if (ConvertRHS) 9567 RHS = ImpCastExprToType(E, Ty, Kind); 9568 } 9569 9570 return result; 9571 } 9572 9573 namespace { 9574 /// The original operand to an operator, prior to the application of the usual 9575 /// arithmetic conversions and converting the arguments of a builtin operator 9576 /// candidate. 9577 struct OriginalOperand { 9578 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9579 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9580 Op = MTE->getSubExpr(); 9581 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9582 Op = BTE->getSubExpr(); 9583 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9584 Orig = ICE->getSubExprAsWritten(); 9585 Conversion = ICE->getConversionFunction(); 9586 } 9587 } 9588 9589 QualType getType() const { return Orig->getType(); } 9590 9591 Expr *Orig; 9592 NamedDecl *Conversion; 9593 }; 9594 } 9595 9596 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9597 ExprResult &RHS) { 9598 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9599 9600 Diag(Loc, diag::err_typecheck_invalid_operands) 9601 << OrigLHS.getType() << OrigRHS.getType() 9602 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9603 9604 // If a user-defined conversion was applied to either of the operands prior 9605 // to applying the built-in operator rules, tell the user about it. 9606 if (OrigLHS.Conversion) { 9607 Diag(OrigLHS.Conversion->getLocation(), 9608 diag::note_typecheck_invalid_operands_converted) 9609 << 0 << LHS.get()->getType(); 9610 } 9611 if (OrigRHS.Conversion) { 9612 Diag(OrigRHS.Conversion->getLocation(), 9613 diag::note_typecheck_invalid_operands_converted) 9614 << 1 << RHS.get()->getType(); 9615 } 9616 9617 return QualType(); 9618 } 9619 9620 // Diagnose cases where a scalar was implicitly converted to a vector and 9621 // diagnose the underlying types. Otherwise, diagnose the error 9622 // as invalid vector logical operands for non-C++ cases. 9623 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9624 ExprResult &RHS) { 9625 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9626 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9627 9628 bool LHSNatVec = LHSType->isVectorType(); 9629 bool RHSNatVec = RHSType->isVectorType(); 9630 9631 if (!(LHSNatVec && RHSNatVec)) { 9632 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9633 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9634 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9635 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9636 << Vector->getSourceRange(); 9637 return QualType(); 9638 } 9639 9640 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9641 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9642 << RHS.get()->getSourceRange(); 9643 9644 return QualType(); 9645 } 9646 9647 /// Try to convert a value of non-vector type to a vector type by converting 9648 /// the type to the element type of the vector and then performing a splat. 9649 /// If the language is OpenCL, we only use conversions that promote scalar 9650 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9651 /// for float->int. 9652 /// 9653 /// OpenCL V2.0 6.2.6.p2: 9654 /// An error shall occur if any scalar operand type has greater rank 9655 /// than the type of the vector element. 9656 /// 9657 /// \param scalar - if non-null, actually perform the conversions 9658 /// \return true if the operation fails (but without diagnosing the failure) 9659 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9660 QualType scalarTy, 9661 QualType vectorEltTy, 9662 QualType vectorTy, 9663 unsigned &DiagID) { 9664 // The conversion to apply to the scalar before splatting it, 9665 // if necessary. 9666 CastKind scalarCast = CK_NoOp; 9667 9668 if (vectorEltTy->isIntegralType(S.Context)) { 9669 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9670 (scalarTy->isIntegerType() && 9671 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9672 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9673 return true; 9674 } 9675 if (!scalarTy->isIntegralType(S.Context)) 9676 return true; 9677 scalarCast = CK_IntegralCast; 9678 } else if (vectorEltTy->isRealFloatingType()) { 9679 if (scalarTy->isRealFloatingType()) { 9680 if (S.getLangOpts().OpenCL && 9681 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9682 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9683 return true; 9684 } 9685 scalarCast = CK_FloatingCast; 9686 } 9687 else if (scalarTy->isIntegralType(S.Context)) 9688 scalarCast = CK_IntegralToFloating; 9689 else 9690 return true; 9691 } else { 9692 return true; 9693 } 9694 9695 // Adjust scalar if desired. 9696 if (scalar) { 9697 if (scalarCast != CK_NoOp) 9698 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9699 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9700 } 9701 return false; 9702 } 9703 9704 /// Convert vector E to a vector with the same number of elements but different 9705 /// element type. 9706 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9707 const auto *VecTy = E->getType()->getAs<VectorType>(); 9708 assert(VecTy && "Expression E must be a vector"); 9709 QualType NewVecTy = S.Context.getVectorType(ElementType, 9710 VecTy->getNumElements(), 9711 VecTy->getVectorKind()); 9712 9713 // Look through the implicit cast. Return the subexpression if its type is 9714 // NewVecTy. 9715 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9716 if (ICE->getSubExpr()->getType() == NewVecTy) 9717 return ICE->getSubExpr(); 9718 9719 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9720 return S.ImpCastExprToType(E, NewVecTy, Cast); 9721 } 9722 9723 /// Test if a (constant) integer Int can be casted to another integer type 9724 /// IntTy without losing precision. 9725 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9726 QualType OtherIntTy) { 9727 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9728 9729 // Reject cases where the value of the Int is unknown as that would 9730 // possibly cause truncation, but accept cases where the scalar can be 9731 // demoted without loss of precision. 9732 Expr::EvalResult EVResult; 9733 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9734 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9735 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9736 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9737 9738 if (CstInt) { 9739 // If the scalar is constant and is of a higher order and has more active 9740 // bits that the vector element type, reject it. 9741 llvm::APSInt Result = EVResult.Val.getInt(); 9742 unsigned NumBits = IntSigned 9743 ? (Result.isNegative() ? Result.getMinSignedBits() 9744 : Result.getActiveBits()) 9745 : Result.getActiveBits(); 9746 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9747 return true; 9748 9749 // If the signedness of the scalar type and the vector element type 9750 // differs and the number of bits is greater than that of the vector 9751 // element reject it. 9752 return (IntSigned != OtherIntSigned && 9753 NumBits > S.Context.getIntWidth(OtherIntTy)); 9754 } 9755 9756 // Reject cases where the value of the scalar is not constant and it's 9757 // order is greater than that of the vector element type. 9758 return (Order < 0); 9759 } 9760 9761 /// Test if a (constant) integer Int can be casted to floating point type 9762 /// FloatTy without losing precision. 9763 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9764 QualType FloatTy) { 9765 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9766 9767 // Determine if the integer constant can be expressed as a floating point 9768 // number of the appropriate type. 9769 Expr::EvalResult EVResult; 9770 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9771 9772 uint64_t Bits = 0; 9773 if (CstInt) { 9774 // Reject constants that would be truncated if they were converted to 9775 // the floating point type. Test by simple to/from conversion. 9776 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9777 // could be avoided if there was a convertFromAPInt method 9778 // which could signal back if implicit truncation occurred. 9779 llvm::APSInt Result = EVResult.Val.getInt(); 9780 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9781 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9782 llvm::APFloat::rmTowardZero); 9783 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9784 !IntTy->hasSignedIntegerRepresentation()); 9785 bool Ignored = false; 9786 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9787 &Ignored); 9788 if (Result != ConvertBack) 9789 return true; 9790 } else { 9791 // Reject types that cannot be fully encoded into the mantissa of 9792 // the float. 9793 Bits = S.Context.getTypeSize(IntTy); 9794 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9795 S.Context.getFloatTypeSemantics(FloatTy)); 9796 if (Bits > FloatPrec) 9797 return true; 9798 } 9799 9800 return false; 9801 } 9802 9803 /// Attempt to convert and splat Scalar into a vector whose types matches 9804 /// Vector following GCC conversion rules. The rule is that implicit 9805 /// conversion can occur when Scalar can be casted to match Vector's element 9806 /// type without causing truncation of Scalar. 9807 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9808 ExprResult *Vector) { 9809 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9810 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9811 const VectorType *VT = VectorTy->getAs<VectorType>(); 9812 9813 assert(!isa<ExtVectorType>(VT) && 9814 "ExtVectorTypes should not be handled here!"); 9815 9816 QualType VectorEltTy = VT->getElementType(); 9817 9818 // Reject cases where the vector element type or the scalar element type are 9819 // not integral or floating point types. 9820 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9821 return true; 9822 9823 // The conversion to apply to the scalar before splatting it, 9824 // if necessary. 9825 CastKind ScalarCast = CK_NoOp; 9826 9827 // Accept cases where the vector elements are integers and the scalar is 9828 // an integer. 9829 // FIXME: Notionally if the scalar was a floating point value with a precise 9830 // integral representation, we could cast it to an appropriate integer 9831 // type and then perform the rest of the checks here. GCC will perform 9832 // this conversion in some cases as determined by the input language. 9833 // We should accept it on a language independent basis. 9834 if (VectorEltTy->isIntegralType(S.Context) && 9835 ScalarTy->isIntegralType(S.Context) && 9836 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9837 9838 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9839 return true; 9840 9841 ScalarCast = CK_IntegralCast; 9842 } else if (VectorEltTy->isIntegralType(S.Context) && 9843 ScalarTy->isRealFloatingType()) { 9844 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9845 ScalarCast = CK_FloatingToIntegral; 9846 else 9847 return true; 9848 } else if (VectorEltTy->isRealFloatingType()) { 9849 if (ScalarTy->isRealFloatingType()) { 9850 9851 // Reject cases where the scalar type is not a constant and has a higher 9852 // Order than the vector element type. 9853 llvm::APFloat Result(0.0); 9854 9855 // Determine whether this is a constant scalar. In the event that the 9856 // value is dependent (and thus cannot be evaluated by the constant 9857 // evaluator), skip the evaluation. This will then diagnose once the 9858 // expression is instantiated. 9859 bool CstScalar = Scalar->get()->isValueDependent() || 9860 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9861 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9862 if (!CstScalar && Order < 0) 9863 return true; 9864 9865 // If the scalar cannot be safely casted to the vector element type, 9866 // reject it. 9867 if (CstScalar) { 9868 bool Truncated = false; 9869 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9870 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9871 if (Truncated) 9872 return true; 9873 } 9874 9875 ScalarCast = CK_FloatingCast; 9876 } else if (ScalarTy->isIntegralType(S.Context)) { 9877 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9878 return true; 9879 9880 ScalarCast = CK_IntegralToFloating; 9881 } else 9882 return true; 9883 } else if (ScalarTy->isEnumeralType()) 9884 return true; 9885 9886 // Adjust scalar if desired. 9887 if (Scalar) { 9888 if (ScalarCast != CK_NoOp) 9889 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9890 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9891 } 9892 return false; 9893 } 9894 9895 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9896 SourceLocation Loc, bool IsCompAssign, 9897 bool AllowBothBool, 9898 bool AllowBoolConversions) { 9899 if (!IsCompAssign) { 9900 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9901 if (LHS.isInvalid()) 9902 return QualType(); 9903 } 9904 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9905 if (RHS.isInvalid()) 9906 return QualType(); 9907 9908 // For conversion purposes, we ignore any qualifiers. 9909 // For example, "const float" and "float" are equivalent. 9910 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9911 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9912 9913 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9914 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9915 assert(LHSVecType || RHSVecType); 9916 9917 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9918 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9919 return InvalidOperands(Loc, LHS, RHS); 9920 9921 // AltiVec-style "vector bool op vector bool" combinations are allowed 9922 // for some operators but not others. 9923 if (!AllowBothBool && 9924 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9925 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9926 return InvalidOperands(Loc, LHS, RHS); 9927 9928 // If the vector types are identical, return. 9929 if (Context.hasSameType(LHSType, RHSType)) 9930 return LHSType; 9931 9932 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9933 if (LHSVecType && RHSVecType && 9934 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9935 if (isa<ExtVectorType>(LHSVecType)) { 9936 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9937 return LHSType; 9938 } 9939 9940 if (!IsCompAssign) 9941 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9942 return RHSType; 9943 } 9944 9945 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9946 // can be mixed, with the result being the non-bool type. The non-bool 9947 // operand must have integer element type. 9948 if (AllowBoolConversions && LHSVecType && RHSVecType && 9949 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9950 (Context.getTypeSize(LHSVecType->getElementType()) == 9951 Context.getTypeSize(RHSVecType->getElementType()))) { 9952 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9953 LHSVecType->getElementType()->isIntegerType() && 9954 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9955 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9956 return LHSType; 9957 } 9958 if (!IsCompAssign && 9959 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9960 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9961 RHSVecType->getElementType()->isIntegerType()) { 9962 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9963 return RHSType; 9964 } 9965 } 9966 9967 // Expressions containing fixed-length and sizeless SVE vectors are invalid 9968 // since the ambiguity can affect the ABI. 9969 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 9970 const VectorType *VecType = SecondType->getAs<VectorType>(); 9971 return FirstType->isSizelessBuiltinType() && VecType && 9972 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 9973 VecType->getVectorKind() == 9974 VectorType::SveFixedLengthPredicateVector); 9975 }; 9976 9977 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 9978 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 9979 return QualType(); 9980 } 9981 9982 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 9983 // since the ambiguity can affect the ABI. 9984 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 9985 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 9986 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 9987 9988 if (FirstVecType && SecondVecType) 9989 return FirstVecType->getVectorKind() == VectorType::GenericVector && 9990 (SecondVecType->getVectorKind() == 9991 VectorType::SveFixedLengthDataVector || 9992 SecondVecType->getVectorKind() == 9993 VectorType::SveFixedLengthPredicateVector); 9994 9995 return FirstType->isSizelessBuiltinType() && SecondVecType && 9996 SecondVecType->getVectorKind() == VectorType::GenericVector; 9997 }; 9998 9999 if (IsSveGnuConversion(LHSType, RHSType) || 10000 IsSveGnuConversion(RHSType, LHSType)) { 10001 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10002 return QualType(); 10003 } 10004 10005 // If there's a vector type and a scalar, try to convert the scalar to 10006 // the vector element type and splat. 10007 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10008 if (!RHSVecType) { 10009 if (isa<ExtVectorType>(LHSVecType)) { 10010 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10011 LHSVecType->getElementType(), LHSType, 10012 DiagID)) 10013 return LHSType; 10014 } else { 10015 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10016 return LHSType; 10017 } 10018 } 10019 if (!LHSVecType) { 10020 if (isa<ExtVectorType>(RHSVecType)) { 10021 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10022 LHSType, RHSVecType->getElementType(), 10023 RHSType, DiagID)) 10024 return RHSType; 10025 } else { 10026 if (LHS.get()->getValueKind() == VK_LValue || 10027 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10028 return RHSType; 10029 } 10030 } 10031 10032 // FIXME: The code below also handles conversion between vectors and 10033 // non-scalars, we should break this down into fine grained specific checks 10034 // and emit proper diagnostics. 10035 QualType VecType = LHSVecType ? LHSType : RHSType; 10036 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10037 QualType OtherType = LHSVecType ? RHSType : LHSType; 10038 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10039 if (isLaxVectorConversion(OtherType, VecType)) { 10040 // If we're allowing lax vector conversions, only the total (data) size 10041 // needs to be the same. For non compound assignment, if one of the types is 10042 // scalar, the result is always the vector type. 10043 if (!IsCompAssign) { 10044 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10045 return VecType; 10046 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10047 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10048 // type. Note that this is already done by non-compound assignments in 10049 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10050 // <1 x T> -> T. The result is also a vector type. 10051 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10052 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10053 ExprResult *RHSExpr = &RHS; 10054 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10055 return VecType; 10056 } 10057 } 10058 10059 // Okay, the expression is invalid. 10060 10061 // If there's a non-vector, non-real operand, diagnose that. 10062 if ((!RHSVecType && !RHSType->isRealType()) || 10063 (!LHSVecType && !LHSType->isRealType())) { 10064 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10065 << LHSType << RHSType 10066 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10067 return QualType(); 10068 } 10069 10070 // OpenCL V1.1 6.2.6.p1: 10071 // If the operands are of more than one vector type, then an error shall 10072 // occur. Implicit conversions between vector types are not permitted, per 10073 // section 6.2.1. 10074 if (getLangOpts().OpenCL && 10075 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10076 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10077 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10078 << RHSType; 10079 return QualType(); 10080 } 10081 10082 10083 // If there is a vector type that is not a ExtVector and a scalar, we reach 10084 // this point if scalar could not be converted to the vector's element type 10085 // without truncation. 10086 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10087 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10088 QualType Scalar = LHSVecType ? RHSType : LHSType; 10089 QualType Vector = LHSVecType ? LHSType : RHSType; 10090 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10091 Diag(Loc, 10092 diag::err_typecheck_vector_not_convertable_implict_truncation) 10093 << ScalarOrVector << Scalar << Vector; 10094 10095 return QualType(); 10096 } 10097 10098 // Otherwise, use the generic diagnostic. 10099 Diag(Loc, DiagID) 10100 << LHSType << RHSType 10101 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10102 return QualType(); 10103 } 10104 10105 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10106 // expression. These are mainly cases where the null pointer is used as an 10107 // integer instead of a pointer. 10108 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10109 SourceLocation Loc, bool IsCompare) { 10110 // The canonical way to check for a GNU null is with isNullPointerConstant, 10111 // but we use a bit of a hack here for speed; this is a relatively 10112 // hot path, and isNullPointerConstant is slow. 10113 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10114 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10115 10116 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10117 10118 // Avoid analyzing cases where the result will either be invalid (and 10119 // diagnosed as such) or entirely valid and not something to warn about. 10120 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10121 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10122 return; 10123 10124 // Comparison operations would not make sense with a null pointer no matter 10125 // what the other expression is. 10126 if (!IsCompare) { 10127 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10128 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10129 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10130 return; 10131 } 10132 10133 // The rest of the operations only make sense with a null pointer 10134 // if the other expression is a pointer. 10135 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10136 NonNullType->canDecayToPointerType()) 10137 return; 10138 10139 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10140 << LHSNull /* LHS is NULL */ << NonNullType 10141 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10142 } 10143 10144 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10145 SourceLocation Loc) { 10146 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10147 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10148 if (!LUE || !RUE) 10149 return; 10150 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10151 RUE->getKind() != UETT_SizeOf) 10152 return; 10153 10154 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10155 QualType LHSTy = LHSArg->getType(); 10156 QualType RHSTy; 10157 10158 if (RUE->isArgumentType()) 10159 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10160 else 10161 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10162 10163 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10164 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10165 return; 10166 10167 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10168 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10169 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10170 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10171 << LHSArgDecl; 10172 } 10173 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10174 QualType ArrayElemTy = ArrayTy->getElementType(); 10175 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10176 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10177 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10178 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10179 return; 10180 S.Diag(Loc, diag::warn_division_sizeof_array) 10181 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10182 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10183 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10184 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10185 << LHSArgDecl; 10186 } 10187 10188 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10189 } 10190 } 10191 10192 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10193 ExprResult &RHS, 10194 SourceLocation Loc, bool IsDiv) { 10195 // Check for division/remainder by zero. 10196 Expr::EvalResult RHSValue; 10197 if (!RHS.get()->isValueDependent() && 10198 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10199 RHSValue.Val.getInt() == 0) 10200 S.DiagRuntimeBehavior(Loc, RHS.get(), 10201 S.PDiag(diag::warn_remainder_division_by_zero) 10202 << IsDiv << RHS.get()->getSourceRange()); 10203 } 10204 10205 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10206 SourceLocation Loc, 10207 bool IsCompAssign, bool IsDiv) { 10208 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10209 10210 QualType LHSTy = LHS.get()->getType(); 10211 QualType RHSTy = RHS.get()->getType(); 10212 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10213 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10214 /*AllowBothBool*/getLangOpts().AltiVec, 10215 /*AllowBoolConversions*/false); 10216 if (!IsDiv && 10217 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10218 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10219 // For division, only matrix-by-scalar is supported. Other combinations with 10220 // matrix types are invalid. 10221 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10222 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10223 10224 QualType compType = UsualArithmeticConversions( 10225 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10226 if (LHS.isInvalid() || RHS.isInvalid()) 10227 return QualType(); 10228 10229 10230 if (compType.isNull() || !compType->isArithmeticType()) 10231 return InvalidOperands(Loc, LHS, RHS); 10232 if (IsDiv) { 10233 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10234 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10235 } 10236 return compType; 10237 } 10238 10239 QualType Sema::CheckRemainderOperands( 10240 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10241 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10242 10243 if (LHS.get()->getType()->isVectorType() || 10244 RHS.get()->getType()->isVectorType()) { 10245 if (LHS.get()->getType()->hasIntegerRepresentation() && 10246 RHS.get()->getType()->hasIntegerRepresentation()) 10247 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10248 /*AllowBothBool*/getLangOpts().AltiVec, 10249 /*AllowBoolConversions*/false); 10250 return InvalidOperands(Loc, LHS, RHS); 10251 } 10252 10253 QualType compType = UsualArithmeticConversions( 10254 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10255 if (LHS.isInvalid() || RHS.isInvalid()) 10256 return QualType(); 10257 10258 if (compType.isNull() || !compType->isIntegerType()) 10259 return InvalidOperands(Loc, LHS, RHS); 10260 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10261 return compType; 10262 } 10263 10264 /// Diagnose invalid arithmetic on two void pointers. 10265 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10266 Expr *LHSExpr, Expr *RHSExpr) { 10267 S.Diag(Loc, S.getLangOpts().CPlusPlus 10268 ? diag::err_typecheck_pointer_arith_void_type 10269 : diag::ext_gnu_void_ptr) 10270 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10271 << RHSExpr->getSourceRange(); 10272 } 10273 10274 /// Diagnose invalid arithmetic on a void pointer. 10275 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10276 Expr *Pointer) { 10277 S.Diag(Loc, S.getLangOpts().CPlusPlus 10278 ? diag::err_typecheck_pointer_arith_void_type 10279 : diag::ext_gnu_void_ptr) 10280 << 0 /* one pointer */ << Pointer->getSourceRange(); 10281 } 10282 10283 /// Diagnose invalid arithmetic on a null pointer. 10284 /// 10285 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10286 /// idiom, which we recognize as a GNU extension. 10287 /// 10288 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10289 Expr *Pointer, bool IsGNUIdiom) { 10290 if (IsGNUIdiom) 10291 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10292 << Pointer->getSourceRange(); 10293 else 10294 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10295 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10296 } 10297 10298 /// Diagnose invalid arithmetic on two function pointers. 10299 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10300 Expr *LHS, Expr *RHS) { 10301 assert(LHS->getType()->isAnyPointerType()); 10302 assert(RHS->getType()->isAnyPointerType()); 10303 S.Diag(Loc, S.getLangOpts().CPlusPlus 10304 ? diag::err_typecheck_pointer_arith_function_type 10305 : diag::ext_gnu_ptr_func_arith) 10306 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10307 // We only show the second type if it differs from the first. 10308 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10309 RHS->getType()) 10310 << RHS->getType()->getPointeeType() 10311 << LHS->getSourceRange() << RHS->getSourceRange(); 10312 } 10313 10314 /// Diagnose invalid arithmetic on a function pointer. 10315 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10316 Expr *Pointer) { 10317 assert(Pointer->getType()->isAnyPointerType()); 10318 S.Diag(Loc, S.getLangOpts().CPlusPlus 10319 ? diag::err_typecheck_pointer_arith_function_type 10320 : diag::ext_gnu_ptr_func_arith) 10321 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10322 << 0 /* one pointer, so only one type */ 10323 << Pointer->getSourceRange(); 10324 } 10325 10326 /// Emit error if Operand is incomplete pointer type 10327 /// 10328 /// \returns True if pointer has incomplete type 10329 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10330 Expr *Operand) { 10331 QualType ResType = Operand->getType(); 10332 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10333 ResType = ResAtomicType->getValueType(); 10334 10335 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10336 QualType PointeeTy = ResType->getPointeeType(); 10337 return S.RequireCompleteSizedType( 10338 Loc, PointeeTy, 10339 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10340 Operand->getSourceRange()); 10341 } 10342 10343 /// Check the validity of an arithmetic pointer operand. 10344 /// 10345 /// If the operand has pointer type, this code will check for pointer types 10346 /// which are invalid in arithmetic operations. These will be diagnosed 10347 /// appropriately, including whether or not the use is supported as an 10348 /// extension. 10349 /// 10350 /// \returns True when the operand is valid to use (even if as an extension). 10351 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10352 Expr *Operand) { 10353 QualType ResType = Operand->getType(); 10354 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10355 ResType = ResAtomicType->getValueType(); 10356 10357 if (!ResType->isAnyPointerType()) return true; 10358 10359 QualType PointeeTy = ResType->getPointeeType(); 10360 if (PointeeTy->isVoidType()) { 10361 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10362 return !S.getLangOpts().CPlusPlus; 10363 } 10364 if (PointeeTy->isFunctionType()) { 10365 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10366 return !S.getLangOpts().CPlusPlus; 10367 } 10368 10369 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10370 10371 return true; 10372 } 10373 10374 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10375 /// operands. 10376 /// 10377 /// This routine will diagnose any invalid arithmetic on pointer operands much 10378 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10379 /// for emitting a single diagnostic even for operations where both LHS and RHS 10380 /// are (potentially problematic) pointers. 10381 /// 10382 /// \returns True when the operand is valid to use (even if as an extension). 10383 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10384 Expr *LHSExpr, Expr *RHSExpr) { 10385 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10386 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10387 if (!isLHSPointer && !isRHSPointer) return true; 10388 10389 QualType LHSPointeeTy, RHSPointeeTy; 10390 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10391 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10392 10393 // if both are pointers check if operation is valid wrt address spaces 10394 if (isLHSPointer && isRHSPointer) { 10395 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10396 S.Diag(Loc, 10397 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10398 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10399 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10400 return false; 10401 } 10402 } 10403 10404 // Check for arithmetic on pointers to incomplete types. 10405 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10406 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10407 if (isLHSVoidPtr || isRHSVoidPtr) { 10408 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10409 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10410 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10411 10412 return !S.getLangOpts().CPlusPlus; 10413 } 10414 10415 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10416 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10417 if (isLHSFuncPtr || isRHSFuncPtr) { 10418 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10419 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10420 RHSExpr); 10421 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10422 10423 return !S.getLangOpts().CPlusPlus; 10424 } 10425 10426 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10427 return false; 10428 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10429 return false; 10430 10431 return true; 10432 } 10433 10434 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10435 /// literal. 10436 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10437 Expr *LHSExpr, Expr *RHSExpr) { 10438 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10439 Expr* IndexExpr = RHSExpr; 10440 if (!StrExpr) { 10441 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10442 IndexExpr = LHSExpr; 10443 } 10444 10445 bool IsStringPlusInt = StrExpr && 10446 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10447 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10448 return; 10449 10450 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10451 Self.Diag(OpLoc, diag::warn_string_plus_int) 10452 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10453 10454 // Only print a fixit for "str" + int, not for int + "str". 10455 if (IndexExpr == RHSExpr) { 10456 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10457 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10458 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10459 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10460 << FixItHint::CreateInsertion(EndLoc, "]"); 10461 } else 10462 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10463 } 10464 10465 /// Emit a warning when adding a char literal to a string. 10466 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10467 Expr *LHSExpr, Expr *RHSExpr) { 10468 const Expr *StringRefExpr = LHSExpr; 10469 const CharacterLiteral *CharExpr = 10470 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10471 10472 if (!CharExpr) { 10473 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10474 StringRefExpr = RHSExpr; 10475 } 10476 10477 if (!CharExpr || !StringRefExpr) 10478 return; 10479 10480 const QualType StringType = StringRefExpr->getType(); 10481 10482 // Return if not a PointerType. 10483 if (!StringType->isAnyPointerType()) 10484 return; 10485 10486 // Return if not a CharacterType. 10487 if (!StringType->getPointeeType()->isAnyCharacterType()) 10488 return; 10489 10490 ASTContext &Ctx = Self.getASTContext(); 10491 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10492 10493 const QualType CharType = CharExpr->getType(); 10494 if (!CharType->isAnyCharacterType() && 10495 CharType->isIntegerType() && 10496 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10497 Self.Diag(OpLoc, diag::warn_string_plus_char) 10498 << DiagRange << Ctx.CharTy; 10499 } else { 10500 Self.Diag(OpLoc, diag::warn_string_plus_char) 10501 << DiagRange << CharExpr->getType(); 10502 } 10503 10504 // Only print a fixit for str + char, not for char + str. 10505 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10506 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10507 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10508 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10509 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10510 << FixItHint::CreateInsertion(EndLoc, "]"); 10511 } else { 10512 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10513 } 10514 } 10515 10516 /// Emit error when two pointers are incompatible. 10517 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10518 Expr *LHSExpr, Expr *RHSExpr) { 10519 assert(LHSExpr->getType()->isAnyPointerType()); 10520 assert(RHSExpr->getType()->isAnyPointerType()); 10521 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10522 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10523 << RHSExpr->getSourceRange(); 10524 } 10525 10526 // C99 6.5.6 10527 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10528 SourceLocation Loc, BinaryOperatorKind Opc, 10529 QualType* CompLHSTy) { 10530 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10531 10532 if (LHS.get()->getType()->isVectorType() || 10533 RHS.get()->getType()->isVectorType()) { 10534 QualType compType = CheckVectorOperands( 10535 LHS, RHS, Loc, CompLHSTy, 10536 /*AllowBothBool*/getLangOpts().AltiVec, 10537 /*AllowBoolConversions*/getLangOpts().ZVector); 10538 if (CompLHSTy) *CompLHSTy = compType; 10539 return compType; 10540 } 10541 10542 if (LHS.get()->getType()->isConstantMatrixType() || 10543 RHS.get()->getType()->isConstantMatrixType()) { 10544 QualType compType = 10545 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10546 if (CompLHSTy) 10547 *CompLHSTy = compType; 10548 return compType; 10549 } 10550 10551 QualType compType = UsualArithmeticConversions( 10552 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10553 if (LHS.isInvalid() || RHS.isInvalid()) 10554 return QualType(); 10555 10556 // Diagnose "string literal" '+' int and string '+' "char literal". 10557 if (Opc == BO_Add) { 10558 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10559 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10560 } 10561 10562 // handle the common case first (both operands are arithmetic). 10563 if (!compType.isNull() && compType->isArithmeticType()) { 10564 if (CompLHSTy) *CompLHSTy = compType; 10565 return compType; 10566 } 10567 10568 // Type-checking. Ultimately the pointer's going to be in PExp; 10569 // note that we bias towards the LHS being the pointer. 10570 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10571 10572 bool isObjCPointer; 10573 if (PExp->getType()->isPointerType()) { 10574 isObjCPointer = false; 10575 } else if (PExp->getType()->isObjCObjectPointerType()) { 10576 isObjCPointer = true; 10577 } else { 10578 std::swap(PExp, IExp); 10579 if (PExp->getType()->isPointerType()) { 10580 isObjCPointer = false; 10581 } else if (PExp->getType()->isObjCObjectPointerType()) { 10582 isObjCPointer = true; 10583 } else { 10584 return InvalidOperands(Loc, LHS, RHS); 10585 } 10586 } 10587 assert(PExp->getType()->isAnyPointerType()); 10588 10589 if (!IExp->getType()->isIntegerType()) 10590 return InvalidOperands(Loc, LHS, RHS); 10591 10592 // Adding to a null pointer results in undefined behavior. 10593 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10594 Context, Expr::NPC_ValueDependentIsNotNull)) { 10595 // In C++ adding zero to a null pointer is defined. 10596 Expr::EvalResult KnownVal; 10597 if (!getLangOpts().CPlusPlus || 10598 (!IExp->isValueDependent() && 10599 (!IExp->EvaluateAsInt(KnownVal, Context) || 10600 KnownVal.Val.getInt() != 0))) { 10601 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10602 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10603 Context, BO_Add, PExp, IExp); 10604 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10605 } 10606 } 10607 10608 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10609 return QualType(); 10610 10611 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10612 return QualType(); 10613 10614 // Check array bounds for pointer arithemtic 10615 CheckArrayAccess(PExp, IExp); 10616 10617 if (CompLHSTy) { 10618 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10619 if (LHSTy.isNull()) { 10620 LHSTy = LHS.get()->getType(); 10621 if (LHSTy->isPromotableIntegerType()) 10622 LHSTy = Context.getPromotedIntegerType(LHSTy); 10623 } 10624 *CompLHSTy = LHSTy; 10625 } 10626 10627 return PExp->getType(); 10628 } 10629 10630 // C99 6.5.6 10631 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10632 SourceLocation Loc, 10633 QualType* CompLHSTy) { 10634 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10635 10636 if (LHS.get()->getType()->isVectorType() || 10637 RHS.get()->getType()->isVectorType()) { 10638 QualType compType = CheckVectorOperands( 10639 LHS, RHS, Loc, CompLHSTy, 10640 /*AllowBothBool*/getLangOpts().AltiVec, 10641 /*AllowBoolConversions*/getLangOpts().ZVector); 10642 if (CompLHSTy) *CompLHSTy = compType; 10643 return compType; 10644 } 10645 10646 if (LHS.get()->getType()->isConstantMatrixType() || 10647 RHS.get()->getType()->isConstantMatrixType()) { 10648 QualType compType = 10649 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10650 if (CompLHSTy) 10651 *CompLHSTy = compType; 10652 return compType; 10653 } 10654 10655 QualType compType = UsualArithmeticConversions( 10656 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10657 if (LHS.isInvalid() || RHS.isInvalid()) 10658 return QualType(); 10659 10660 // Enforce type constraints: C99 6.5.6p3. 10661 10662 // Handle the common case first (both operands are arithmetic). 10663 if (!compType.isNull() && compType->isArithmeticType()) { 10664 if (CompLHSTy) *CompLHSTy = compType; 10665 return compType; 10666 } 10667 10668 // Either ptr - int or ptr - ptr. 10669 if (LHS.get()->getType()->isAnyPointerType()) { 10670 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10671 10672 // Diagnose bad cases where we step over interface counts. 10673 if (LHS.get()->getType()->isObjCObjectPointerType() && 10674 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10675 return QualType(); 10676 10677 // The result type of a pointer-int computation is the pointer type. 10678 if (RHS.get()->getType()->isIntegerType()) { 10679 // Subtracting from a null pointer should produce a warning. 10680 // The last argument to the diagnose call says this doesn't match the 10681 // GNU int-to-pointer idiom. 10682 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10683 Expr::NPC_ValueDependentIsNotNull)) { 10684 // In C++ adding zero to a null pointer is defined. 10685 Expr::EvalResult KnownVal; 10686 if (!getLangOpts().CPlusPlus || 10687 (!RHS.get()->isValueDependent() && 10688 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10689 KnownVal.Val.getInt() != 0))) { 10690 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10691 } 10692 } 10693 10694 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10695 return QualType(); 10696 10697 // Check array bounds for pointer arithemtic 10698 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10699 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10700 10701 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10702 return LHS.get()->getType(); 10703 } 10704 10705 // Handle pointer-pointer subtractions. 10706 if (const PointerType *RHSPTy 10707 = RHS.get()->getType()->getAs<PointerType>()) { 10708 QualType rpointee = RHSPTy->getPointeeType(); 10709 10710 if (getLangOpts().CPlusPlus) { 10711 // Pointee types must be the same: C++ [expr.add] 10712 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10713 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10714 } 10715 } else { 10716 // Pointee types must be compatible C99 6.5.6p3 10717 if (!Context.typesAreCompatible( 10718 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10719 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10720 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10721 return QualType(); 10722 } 10723 } 10724 10725 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10726 LHS.get(), RHS.get())) 10727 return QualType(); 10728 10729 // FIXME: Add warnings for nullptr - ptr. 10730 10731 // The pointee type may have zero size. As an extension, a structure or 10732 // union may have zero size or an array may have zero length. In this 10733 // case subtraction does not make sense. 10734 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10735 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10736 if (ElementSize.isZero()) { 10737 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10738 << rpointee.getUnqualifiedType() 10739 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10740 } 10741 } 10742 10743 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10744 return Context.getPointerDiffType(); 10745 } 10746 } 10747 10748 return InvalidOperands(Loc, LHS, RHS); 10749 } 10750 10751 static bool isScopedEnumerationType(QualType T) { 10752 if (const EnumType *ET = T->getAs<EnumType>()) 10753 return ET->getDecl()->isScoped(); 10754 return false; 10755 } 10756 10757 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10758 SourceLocation Loc, BinaryOperatorKind Opc, 10759 QualType LHSType) { 10760 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10761 // so skip remaining warnings as we don't want to modify values within Sema. 10762 if (S.getLangOpts().OpenCL) 10763 return; 10764 10765 // Check right/shifter operand 10766 Expr::EvalResult RHSResult; 10767 if (RHS.get()->isValueDependent() || 10768 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10769 return; 10770 llvm::APSInt Right = RHSResult.Val.getInt(); 10771 10772 if (Right.isNegative()) { 10773 S.DiagRuntimeBehavior(Loc, RHS.get(), 10774 S.PDiag(diag::warn_shift_negative) 10775 << RHS.get()->getSourceRange()); 10776 return; 10777 } 10778 10779 QualType LHSExprType = LHS.get()->getType(); 10780 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10781 if (LHSExprType->isExtIntType()) 10782 LeftSize = S.Context.getIntWidth(LHSExprType); 10783 else if (LHSExprType->isFixedPointType()) { 10784 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10785 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10786 } 10787 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10788 if (Right.uge(LeftBits)) { 10789 S.DiagRuntimeBehavior(Loc, RHS.get(), 10790 S.PDiag(diag::warn_shift_gt_typewidth) 10791 << RHS.get()->getSourceRange()); 10792 return; 10793 } 10794 10795 // FIXME: We probably need to handle fixed point types specially here. 10796 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10797 return; 10798 10799 // When left shifting an ICE which is signed, we can check for overflow which 10800 // according to C++ standards prior to C++2a has undefined behavior 10801 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10802 // more than the maximum value representable in the result type, so never 10803 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10804 // expression is still probably a bug.) 10805 Expr::EvalResult LHSResult; 10806 if (LHS.get()->isValueDependent() || 10807 LHSType->hasUnsignedIntegerRepresentation() || 10808 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10809 return; 10810 llvm::APSInt Left = LHSResult.Val.getInt(); 10811 10812 // If LHS does not have a signed type and non-negative value 10813 // then, the behavior is undefined before C++2a. Warn about it. 10814 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10815 !S.getLangOpts().CPlusPlus20) { 10816 S.DiagRuntimeBehavior(Loc, LHS.get(), 10817 S.PDiag(diag::warn_shift_lhs_negative) 10818 << LHS.get()->getSourceRange()); 10819 return; 10820 } 10821 10822 llvm::APInt ResultBits = 10823 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10824 if (LeftBits.uge(ResultBits)) 10825 return; 10826 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10827 Result = Result.shl(Right); 10828 10829 // Print the bit representation of the signed integer as an unsigned 10830 // hexadecimal number. 10831 SmallString<40> HexResult; 10832 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10833 10834 // If we are only missing a sign bit, this is less likely to result in actual 10835 // bugs -- if the result is cast back to an unsigned type, it will have the 10836 // expected value. Thus we place this behind a different warning that can be 10837 // turned off separately if needed. 10838 if (LeftBits == ResultBits - 1) { 10839 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10840 << HexResult << LHSType 10841 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10842 return; 10843 } 10844 10845 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10846 << HexResult.str() << Result.getMinSignedBits() << LHSType 10847 << Left.getBitWidth() << LHS.get()->getSourceRange() 10848 << RHS.get()->getSourceRange(); 10849 } 10850 10851 /// Return the resulting type when a vector is shifted 10852 /// by a scalar or vector shift amount. 10853 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10854 SourceLocation Loc, bool IsCompAssign) { 10855 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10856 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10857 !LHS.get()->getType()->isVectorType()) { 10858 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10859 << RHS.get()->getType() << LHS.get()->getType() 10860 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10861 return QualType(); 10862 } 10863 10864 if (!IsCompAssign) { 10865 LHS = S.UsualUnaryConversions(LHS.get()); 10866 if (LHS.isInvalid()) return QualType(); 10867 } 10868 10869 RHS = S.UsualUnaryConversions(RHS.get()); 10870 if (RHS.isInvalid()) return QualType(); 10871 10872 QualType LHSType = LHS.get()->getType(); 10873 // Note that LHS might be a scalar because the routine calls not only in 10874 // OpenCL case. 10875 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10876 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10877 10878 // Note that RHS might not be a vector. 10879 QualType RHSType = RHS.get()->getType(); 10880 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10881 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10882 10883 // The operands need to be integers. 10884 if (!LHSEleType->isIntegerType()) { 10885 S.Diag(Loc, diag::err_typecheck_expect_int) 10886 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10887 return QualType(); 10888 } 10889 10890 if (!RHSEleType->isIntegerType()) { 10891 S.Diag(Loc, diag::err_typecheck_expect_int) 10892 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10893 return QualType(); 10894 } 10895 10896 if (!LHSVecTy) { 10897 assert(RHSVecTy); 10898 if (IsCompAssign) 10899 return RHSType; 10900 if (LHSEleType != RHSEleType) { 10901 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10902 LHSEleType = RHSEleType; 10903 } 10904 QualType VecTy = 10905 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10906 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10907 LHSType = VecTy; 10908 } else if (RHSVecTy) { 10909 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10910 // are applied component-wise. So if RHS is a vector, then ensure 10911 // that the number of elements is the same as LHS... 10912 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10913 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10914 << LHS.get()->getType() << RHS.get()->getType() 10915 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10916 return QualType(); 10917 } 10918 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10919 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10920 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10921 if (LHSBT != RHSBT && 10922 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10923 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10924 << LHS.get()->getType() << RHS.get()->getType() 10925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10926 } 10927 } 10928 } else { 10929 // ...else expand RHS to match the number of elements in LHS. 10930 QualType VecTy = 10931 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10932 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10933 } 10934 10935 return LHSType; 10936 } 10937 10938 // C99 6.5.7 10939 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10940 SourceLocation Loc, BinaryOperatorKind Opc, 10941 bool IsCompAssign) { 10942 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10943 10944 // Vector shifts promote their scalar inputs to vector type. 10945 if (LHS.get()->getType()->isVectorType() || 10946 RHS.get()->getType()->isVectorType()) { 10947 if (LangOpts.ZVector) { 10948 // The shift operators for the z vector extensions work basically 10949 // like general shifts, except that neither the LHS nor the RHS is 10950 // allowed to be a "vector bool". 10951 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10952 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10953 return InvalidOperands(Loc, LHS, RHS); 10954 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10955 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10956 return InvalidOperands(Loc, LHS, RHS); 10957 } 10958 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10959 } 10960 10961 // Shifts don't perform usual arithmetic conversions, they just do integer 10962 // promotions on each operand. C99 6.5.7p3 10963 10964 // For the LHS, do usual unary conversions, but then reset them away 10965 // if this is a compound assignment. 10966 ExprResult OldLHS = LHS; 10967 LHS = UsualUnaryConversions(LHS.get()); 10968 if (LHS.isInvalid()) 10969 return QualType(); 10970 QualType LHSType = LHS.get()->getType(); 10971 if (IsCompAssign) LHS = OldLHS; 10972 10973 // The RHS is simpler. 10974 RHS = UsualUnaryConversions(RHS.get()); 10975 if (RHS.isInvalid()) 10976 return QualType(); 10977 QualType RHSType = RHS.get()->getType(); 10978 10979 // C99 6.5.7p2: Each of the operands shall have integer type. 10980 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 10981 if ((!LHSType->isFixedPointOrIntegerType() && 10982 !LHSType->hasIntegerRepresentation()) || 10983 !RHSType->hasIntegerRepresentation()) 10984 return InvalidOperands(Loc, LHS, RHS); 10985 10986 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10987 // hasIntegerRepresentation() above instead of this. 10988 if (isScopedEnumerationType(LHSType) || 10989 isScopedEnumerationType(RHSType)) { 10990 return InvalidOperands(Loc, LHS, RHS); 10991 } 10992 // Sanity-check shift operands 10993 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10994 10995 // "The type of the result is that of the promoted left operand." 10996 return LHSType; 10997 } 10998 10999 /// Diagnose bad pointer comparisons. 11000 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11001 ExprResult &LHS, ExprResult &RHS, 11002 bool IsError) { 11003 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11004 : diag::ext_typecheck_comparison_of_distinct_pointers) 11005 << LHS.get()->getType() << RHS.get()->getType() 11006 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11007 } 11008 11009 /// Returns false if the pointers are converted to a composite type, 11010 /// true otherwise. 11011 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11012 ExprResult &LHS, ExprResult &RHS) { 11013 // C++ [expr.rel]p2: 11014 // [...] Pointer conversions (4.10) and qualification 11015 // conversions (4.4) are performed on pointer operands (or on 11016 // a pointer operand and a null pointer constant) to bring 11017 // them to their composite pointer type. [...] 11018 // 11019 // C++ [expr.eq]p1 uses the same notion for (in)equality 11020 // comparisons of pointers. 11021 11022 QualType LHSType = LHS.get()->getType(); 11023 QualType RHSType = RHS.get()->getType(); 11024 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11025 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11026 11027 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11028 if (T.isNull()) { 11029 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11030 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11031 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11032 else 11033 S.InvalidOperands(Loc, LHS, RHS); 11034 return true; 11035 } 11036 11037 return false; 11038 } 11039 11040 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11041 ExprResult &LHS, 11042 ExprResult &RHS, 11043 bool IsError) { 11044 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11045 : diag::ext_typecheck_comparison_of_fptr_to_void) 11046 << LHS.get()->getType() << RHS.get()->getType() 11047 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11048 } 11049 11050 static bool isObjCObjectLiteral(ExprResult &E) { 11051 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11052 case Stmt::ObjCArrayLiteralClass: 11053 case Stmt::ObjCDictionaryLiteralClass: 11054 case Stmt::ObjCStringLiteralClass: 11055 case Stmt::ObjCBoxedExprClass: 11056 return true; 11057 default: 11058 // Note that ObjCBoolLiteral is NOT an object literal! 11059 return false; 11060 } 11061 } 11062 11063 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11064 const ObjCObjectPointerType *Type = 11065 LHS->getType()->getAs<ObjCObjectPointerType>(); 11066 11067 // If this is not actually an Objective-C object, bail out. 11068 if (!Type) 11069 return false; 11070 11071 // Get the LHS object's interface type. 11072 QualType InterfaceType = Type->getPointeeType(); 11073 11074 // If the RHS isn't an Objective-C object, bail out. 11075 if (!RHS->getType()->isObjCObjectPointerType()) 11076 return false; 11077 11078 // Try to find the -isEqual: method. 11079 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11080 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11081 InterfaceType, 11082 /*IsInstance=*/true); 11083 if (!Method) { 11084 if (Type->isObjCIdType()) { 11085 // For 'id', just check the global pool. 11086 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11087 /*receiverId=*/true); 11088 } else { 11089 // Check protocols. 11090 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11091 /*IsInstance=*/true); 11092 } 11093 } 11094 11095 if (!Method) 11096 return false; 11097 11098 QualType T = Method->parameters()[0]->getType(); 11099 if (!T->isObjCObjectPointerType()) 11100 return false; 11101 11102 QualType R = Method->getReturnType(); 11103 if (!R->isScalarType()) 11104 return false; 11105 11106 return true; 11107 } 11108 11109 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11110 FromE = FromE->IgnoreParenImpCasts(); 11111 switch (FromE->getStmtClass()) { 11112 default: 11113 break; 11114 case Stmt::ObjCStringLiteralClass: 11115 // "string literal" 11116 return LK_String; 11117 case Stmt::ObjCArrayLiteralClass: 11118 // "array literal" 11119 return LK_Array; 11120 case Stmt::ObjCDictionaryLiteralClass: 11121 // "dictionary literal" 11122 return LK_Dictionary; 11123 case Stmt::BlockExprClass: 11124 return LK_Block; 11125 case Stmt::ObjCBoxedExprClass: { 11126 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11127 switch (Inner->getStmtClass()) { 11128 case Stmt::IntegerLiteralClass: 11129 case Stmt::FloatingLiteralClass: 11130 case Stmt::CharacterLiteralClass: 11131 case Stmt::ObjCBoolLiteralExprClass: 11132 case Stmt::CXXBoolLiteralExprClass: 11133 // "numeric literal" 11134 return LK_Numeric; 11135 case Stmt::ImplicitCastExprClass: { 11136 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11137 // Boolean literals can be represented by implicit casts. 11138 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11139 return LK_Numeric; 11140 break; 11141 } 11142 default: 11143 break; 11144 } 11145 return LK_Boxed; 11146 } 11147 } 11148 return LK_None; 11149 } 11150 11151 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11152 ExprResult &LHS, ExprResult &RHS, 11153 BinaryOperator::Opcode Opc){ 11154 Expr *Literal; 11155 Expr *Other; 11156 if (isObjCObjectLiteral(LHS)) { 11157 Literal = LHS.get(); 11158 Other = RHS.get(); 11159 } else { 11160 Literal = RHS.get(); 11161 Other = LHS.get(); 11162 } 11163 11164 // Don't warn on comparisons against nil. 11165 Other = Other->IgnoreParenCasts(); 11166 if (Other->isNullPointerConstant(S.getASTContext(), 11167 Expr::NPC_ValueDependentIsNotNull)) 11168 return; 11169 11170 // This should be kept in sync with warn_objc_literal_comparison. 11171 // LK_String should always be after the other literals, since it has its own 11172 // warning flag. 11173 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11174 assert(LiteralKind != Sema::LK_Block); 11175 if (LiteralKind == Sema::LK_None) { 11176 llvm_unreachable("Unknown Objective-C object literal kind"); 11177 } 11178 11179 if (LiteralKind == Sema::LK_String) 11180 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11181 << Literal->getSourceRange(); 11182 else 11183 S.Diag(Loc, diag::warn_objc_literal_comparison) 11184 << LiteralKind << Literal->getSourceRange(); 11185 11186 if (BinaryOperator::isEqualityOp(Opc) && 11187 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11188 SourceLocation Start = LHS.get()->getBeginLoc(); 11189 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11190 CharSourceRange OpRange = 11191 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11192 11193 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11194 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11195 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11196 << FixItHint::CreateInsertion(End, "]"); 11197 } 11198 } 11199 11200 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11201 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11202 ExprResult &RHS, SourceLocation Loc, 11203 BinaryOperatorKind Opc) { 11204 // Check that left hand side is !something. 11205 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11206 if (!UO || UO->getOpcode() != UO_LNot) return; 11207 11208 // Only check if the right hand side is non-bool arithmetic type. 11209 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11210 11211 // Make sure that the something in !something is not bool. 11212 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11213 if (SubExpr->isKnownToHaveBooleanValue()) return; 11214 11215 // Emit warning. 11216 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11217 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11218 << Loc << IsBitwiseOp; 11219 11220 // First note suggest !(x < y) 11221 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11222 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11223 FirstClose = S.getLocForEndOfToken(FirstClose); 11224 if (FirstClose.isInvalid()) 11225 FirstOpen = SourceLocation(); 11226 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11227 << IsBitwiseOp 11228 << FixItHint::CreateInsertion(FirstOpen, "(") 11229 << FixItHint::CreateInsertion(FirstClose, ")"); 11230 11231 // Second note suggests (!x) < y 11232 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11233 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11234 SecondClose = S.getLocForEndOfToken(SecondClose); 11235 if (SecondClose.isInvalid()) 11236 SecondOpen = SourceLocation(); 11237 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11238 << FixItHint::CreateInsertion(SecondOpen, "(") 11239 << FixItHint::CreateInsertion(SecondClose, ")"); 11240 } 11241 11242 // Returns true if E refers to a non-weak array. 11243 static bool checkForArray(const Expr *E) { 11244 const ValueDecl *D = nullptr; 11245 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11246 D = DR->getDecl(); 11247 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11248 if (Mem->isImplicitAccess()) 11249 D = Mem->getMemberDecl(); 11250 } 11251 if (!D) 11252 return false; 11253 return D->getType()->isArrayType() && !D->isWeak(); 11254 } 11255 11256 /// Diagnose some forms of syntactically-obvious tautological comparison. 11257 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11258 Expr *LHS, Expr *RHS, 11259 BinaryOperatorKind Opc) { 11260 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11261 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11262 11263 QualType LHSType = LHS->getType(); 11264 QualType RHSType = RHS->getType(); 11265 if (LHSType->hasFloatingRepresentation() || 11266 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11267 S.inTemplateInstantiation()) 11268 return; 11269 11270 // Comparisons between two array types are ill-formed for operator<=>, so 11271 // we shouldn't emit any additional warnings about it. 11272 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11273 return; 11274 11275 // For non-floating point types, check for self-comparisons of the form 11276 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11277 // often indicate logic errors in the program. 11278 // 11279 // NOTE: Don't warn about comparison expressions resulting from macro 11280 // expansion. Also don't warn about comparisons which are only self 11281 // comparisons within a template instantiation. The warnings should catch 11282 // obvious cases in the definition of the template anyways. The idea is to 11283 // warn when the typed comparison operator will always evaluate to the same 11284 // result. 11285 11286 // Used for indexing into %select in warn_comparison_always 11287 enum { 11288 AlwaysConstant, 11289 AlwaysTrue, 11290 AlwaysFalse, 11291 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11292 }; 11293 11294 // C++2a [depr.array.comp]: 11295 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11296 // operands of array type are deprecated. 11297 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11298 RHSStripped->getType()->isArrayType()) { 11299 S.Diag(Loc, diag::warn_depr_array_comparison) 11300 << LHS->getSourceRange() << RHS->getSourceRange() 11301 << LHSStripped->getType() << RHSStripped->getType(); 11302 // Carry on to produce the tautological comparison warning, if this 11303 // expression is potentially-evaluated, we can resolve the array to a 11304 // non-weak declaration, and so on. 11305 } 11306 11307 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11308 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11309 unsigned Result; 11310 switch (Opc) { 11311 case BO_EQ: 11312 case BO_LE: 11313 case BO_GE: 11314 Result = AlwaysTrue; 11315 break; 11316 case BO_NE: 11317 case BO_LT: 11318 case BO_GT: 11319 Result = AlwaysFalse; 11320 break; 11321 case BO_Cmp: 11322 Result = AlwaysEqual; 11323 break; 11324 default: 11325 Result = AlwaysConstant; 11326 break; 11327 } 11328 S.DiagRuntimeBehavior(Loc, nullptr, 11329 S.PDiag(diag::warn_comparison_always) 11330 << 0 /*self-comparison*/ 11331 << Result); 11332 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11333 // What is it always going to evaluate to? 11334 unsigned Result; 11335 switch (Opc) { 11336 case BO_EQ: // e.g. array1 == array2 11337 Result = AlwaysFalse; 11338 break; 11339 case BO_NE: // e.g. array1 != array2 11340 Result = AlwaysTrue; 11341 break; 11342 default: // e.g. array1 <= array2 11343 // The best we can say is 'a constant' 11344 Result = AlwaysConstant; 11345 break; 11346 } 11347 S.DiagRuntimeBehavior(Loc, nullptr, 11348 S.PDiag(diag::warn_comparison_always) 11349 << 1 /*array comparison*/ 11350 << Result); 11351 } 11352 } 11353 11354 if (isa<CastExpr>(LHSStripped)) 11355 LHSStripped = LHSStripped->IgnoreParenCasts(); 11356 if (isa<CastExpr>(RHSStripped)) 11357 RHSStripped = RHSStripped->IgnoreParenCasts(); 11358 11359 // Warn about comparisons against a string constant (unless the other 11360 // operand is null); the user probably wants string comparison function. 11361 Expr *LiteralString = nullptr; 11362 Expr *LiteralStringStripped = nullptr; 11363 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11364 !RHSStripped->isNullPointerConstant(S.Context, 11365 Expr::NPC_ValueDependentIsNull)) { 11366 LiteralString = LHS; 11367 LiteralStringStripped = LHSStripped; 11368 } else if ((isa<StringLiteral>(RHSStripped) || 11369 isa<ObjCEncodeExpr>(RHSStripped)) && 11370 !LHSStripped->isNullPointerConstant(S.Context, 11371 Expr::NPC_ValueDependentIsNull)) { 11372 LiteralString = RHS; 11373 LiteralStringStripped = RHSStripped; 11374 } 11375 11376 if (LiteralString) { 11377 S.DiagRuntimeBehavior(Loc, nullptr, 11378 S.PDiag(diag::warn_stringcompare) 11379 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11380 << LiteralString->getSourceRange()); 11381 } 11382 } 11383 11384 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11385 switch (CK) { 11386 default: { 11387 #ifndef NDEBUG 11388 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11389 << "\n"; 11390 #endif 11391 llvm_unreachable("unhandled cast kind"); 11392 } 11393 case CK_UserDefinedConversion: 11394 return ICK_Identity; 11395 case CK_LValueToRValue: 11396 return ICK_Lvalue_To_Rvalue; 11397 case CK_ArrayToPointerDecay: 11398 return ICK_Array_To_Pointer; 11399 case CK_FunctionToPointerDecay: 11400 return ICK_Function_To_Pointer; 11401 case CK_IntegralCast: 11402 return ICK_Integral_Conversion; 11403 case CK_FloatingCast: 11404 return ICK_Floating_Conversion; 11405 case CK_IntegralToFloating: 11406 case CK_FloatingToIntegral: 11407 return ICK_Floating_Integral; 11408 case CK_IntegralComplexCast: 11409 case CK_FloatingComplexCast: 11410 case CK_FloatingComplexToIntegralComplex: 11411 case CK_IntegralComplexToFloatingComplex: 11412 return ICK_Complex_Conversion; 11413 case CK_FloatingComplexToReal: 11414 case CK_FloatingRealToComplex: 11415 case CK_IntegralComplexToReal: 11416 case CK_IntegralRealToComplex: 11417 return ICK_Complex_Real; 11418 } 11419 } 11420 11421 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11422 QualType FromType, 11423 SourceLocation Loc) { 11424 // Check for a narrowing implicit conversion. 11425 StandardConversionSequence SCS; 11426 SCS.setAsIdentityConversion(); 11427 SCS.setToType(0, FromType); 11428 SCS.setToType(1, ToType); 11429 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11430 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11431 11432 APValue PreNarrowingValue; 11433 QualType PreNarrowingType; 11434 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11435 PreNarrowingType, 11436 /*IgnoreFloatToIntegralConversion*/ true)) { 11437 case NK_Dependent_Narrowing: 11438 // Implicit conversion to a narrower type, but the expression is 11439 // value-dependent so we can't tell whether it's actually narrowing. 11440 case NK_Not_Narrowing: 11441 return false; 11442 11443 case NK_Constant_Narrowing: 11444 // Implicit conversion to a narrower type, and the value is not a constant 11445 // expression. 11446 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11447 << /*Constant*/ 1 11448 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11449 return true; 11450 11451 case NK_Variable_Narrowing: 11452 // Implicit conversion to a narrower type, and the value is not a constant 11453 // expression. 11454 case NK_Type_Narrowing: 11455 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11456 << /*Constant*/ 0 << FromType << ToType; 11457 // TODO: It's not a constant expression, but what if the user intended it 11458 // to be? Can we produce notes to help them figure out why it isn't? 11459 return true; 11460 } 11461 llvm_unreachable("unhandled case in switch"); 11462 } 11463 11464 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11465 ExprResult &LHS, 11466 ExprResult &RHS, 11467 SourceLocation Loc) { 11468 QualType LHSType = LHS.get()->getType(); 11469 QualType RHSType = RHS.get()->getType(); 11470 // Dig out the original argument type and expression before implicit casts 11471 // were applied. These are the types/expressions we need to check the 11472 // [expr.spaceship] requirements against. 11473 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11474 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11475 QualType LHSStrippedType = LHSStripped.get()->getType(); 11476 QualType RHSStrippedType = RHSStripped.get()->getType(); 11477 11478 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11479 // other is not, the program is ill-formed. 11480 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11481 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11482 return QualType(); 11483 } 11484 11485 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11486 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11487 RHSStrippedType->isEnumeralType(); 11488 if (NumEnumArgs == 1) { 11489 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11490 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11491 if (OtherTy->hasFloatingRepresentation()) { 11492 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11493 return QualType(); 11494 } 11495 } 11496 if (NumEnumArgs == 2) { 11497 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11498 // type E, the operator yields the result of converting the operands 11499 // to the underlying type of E and applying <=> to the converted operands. 11500 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11501 S.InvalidOperands(Loc, LHS, RHS); 11502 return QualType(); 11503 } 11504 QualType IntType = 11505 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11506 assert(IntType->isArithmeticType()); 11507 11508 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11509 // promote the boolean type, and all other promotable integer types, to 11510 // avoid this. 11511 if (IntType->isPromotableIntegerType()) 11512 IntType = S.Context.getPromotedIntegerType(IntType); 11513 11514 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11515 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11516 LHSType = RHSType = IntType; 11517 } 11518 11519 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11520 // usual arithmetic conversions are applied to the operands. 11521 QualType Type = 11522 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11523 if (LHS.isInvalid() || RHS.isInvalid()) 11524 return QualType(); 11525 if (Type.isNull()) 11526 return S.InvalidOperands(Loc, LHS, RHS); 11527 11528 Optional<ComparisonCategoryType> CCT = 11529 getComparisonCategoryForBuiltinCmp(Type); 11530 if (!CCT) 11531 return S.InvalidOperands(Loc, LHS, RHS); 11532 11533 bool HasNarrowing = checkThreeWayNarrowingConversion( 11534 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11535 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11536 RHS.get()->getBeginLoc()); 11537 if (HasNarrowing) 11538 return QualType(); 11539 11540 assert(!Type.isNull() && "composite type for <=> has not been set"); 11541 11542 return S.CheckComparisonCategoryType( 11543 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11544 } 11545 11546 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11547 ExprResult &RHS, 11548 SourceLocation Loc, 11549 BinaryOperatorKind Opc) { 11550 if (Opc == BO_Cmp) 11551 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11552 11553 // C99 6.5.8p3 / C99 6.5.9p4 11554 QualType Type = 11555 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11556 if (LHS.isInvalid() || RHS.isInvalid()) 11557 return QualType(); 11558 if (Type.isNull()) 11559 return S.InvalidOperands(Loc, LHS, RHS); 11560 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11561 11562 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11563 return S.InvalidOperands(Loc, LHS, RHS); 11564 11565 // Check for comparisons of floating point operands using != and ==. 11566 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11567 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11568 11569 // The result of comparisons is 'bool' in C++, 'int' in C. 11570 return S.Context.getLogicalOperationType(); 11571 } 11572 11573 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11574 if (!NullE.get()->getType()->isAnyPointerType()) 11575 return; 11576 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11577 if (!E.get()->getType()->isAnyPointerType() && 11578 E.get()->isNullPointerConstant(Context, 11579 Expr::NPC_ValueDependentIsNotNull) == 11580 Expr::NPCK_ZeroExpression) { 11581 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11582 if (CL->getValue() == 0) 11583 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11584 << NullValue 11585 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11586 NullValue ? "NULL" : "(void *)0"); 11587 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11588 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11589 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11590 if (T == Context.CharTy) 11591 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11592 << NullValue 11593 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11594 NullValue ? "NULL" : "(void *)0"); 11595 } 11596 } 11597 } 11598 11599 // C99 6.5.8, C++ [expr.rel] 11600 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11601 SourceLocation Loc, 11602 BinaryOperatorKind Opc) { 11603 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11604 bool IsThreeWay = Opc == BO_Cmp; 11605 bool IsOrdered = IsRelational || IsThreeWay; 11606 auto IsAnyPointerType = [](ExprResult E) { 11607 QualType Ty = E.get()->getType(); 11608 return Ty->isPointerType() || Ty->isMemberPointerType(); 11609 }; 11610 11611 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11612 // type, array-to-pointer, ..., conversions are performed on both operands to 11613 // bring them to their composite type. 11614 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11615 // any type-related checks. 11616 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11617 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11618 if (LHS.isInvalid()) 11619 return QualType(); 11620 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11621 if (RHS.isInvalid()) 11622 return QualType(); 11623 } else { 11624 LHS = DefaultLvalueConversion(LHS.get()); 11625 if (LHS.isInvalid()) 11626 return QualType(); 11627 RHS = DefaultLvalueConversion(RHS.get()); 11628 if (RHS.isInvalid()) 11629 return QualType(); 11630 } 11631 11632 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11633 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11634 CheckPtrComparisonWithNullChar(LHS, RHS); 11635 CheckPtrComparisonWithNullChar(RHS, LHS); 11636 } 11637 11638 // Handle vector comparisons separately. 11639 if (LHS.get()->getType()->isVectorType() || 11640 RHS.get()->getType()->isVectorType()) 11641 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11642 11643 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11644 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11645 11646 QualType LHSType = LHS.get()->getType(); 11647 QualType RHSType = RHS.get()->getType(); 11648 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11649 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11650 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11651 11652 const Expr::NullPointerConstantKind LHSNullKind = 11653 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11654 const Expr::NullPointerConstantKind RHSNullKind = 11655 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11656 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11657 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11658 11659 auto computeResultTy = [&]() { 11660 if (Opc != BO_Cmp) 11661 return Context.getLogicalOperationType(); 11662 assert(getLangOpts().CPlusPlus); 11663 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11664 11665 QualType CompositeTy = LHS.get()->getType(); 11666 assert(!CompositeTy->isReferenceType()); 11667 11668 Optional<ComparisonCategoryType> CCT = 11669 getComparisonCategoryForBuiltinCmp(CompositeTy); 11670 if (!CCT) 11671 return InvalidOperands(Loc, LHS, RHS); 11672 11673 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11674 // P0946R0: Comparisons between a null pointer constant and an object 11675 // pointer result in std::strong_equality, which is ill-formed under 11676 // P1959R0. 11677 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11678 << (LHSIsNull ? LHS.get()->getSourceRange() 11679 : RHS.get()->getSourceRange()); 11680 return QualType(); 11681 } 11682 11683 return CheckComparisonCategoryType( 11684 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11685 }; 11686 11687 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11688 bool IsEquality = Opc == BO_EQ; 11689 if (RHSIsNull) 11690 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11691 RHS.get()->getSourceRange()); 11692 else 11693 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11694 LHS.get()->getSourceRange()); 11695 } 11696 11697 if ((LHSType->isIntegerType() && !LHSIsNull) || 11698 (RHSType->isIntegerType() && !RHSIsNull)) { 11699 // Skip normal pointer conversion checks in this case; we have better 11700 // diagnostics for this below. 11701 } else if (getLangOpts().CPlusPlus) { 11702 // Equality comparison of a function pointer to a void pointer is invalid, 11703 // but we allow it as an extension. 11704 // FIXME: If we really want to allow this, should it be part of composite 11705 // pointer type computation so it works in conditionals too? 11706 if (!IsOrdered && 11707 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11708 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11709 // This is a gcc extension compatibility comparison. 11710 // In a SFINAE context, we treat this as a hard error to maintain 11711 // conformance with the C++ standard. 11712 diagnoseFunctionPointerToVoidComparison( 11713 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11714 11715 if (isSFINAEContext()) 11716 return QualType(); 11717 11718 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11719 return computeResultTy(); 11720 } 11721 11722 // C++ [expr.eq]p2: 11723 // If at least one operand is a pointer [...] bring them to their 11724 // composite pointer type. 11725 // C++ [expr.spaceship]p6 11726 // If at least one of the operands is of pointer type, [...] bring them 11727 // to their composite pointer type. 11728 // C++ [expr.rel]p2: 11729 // If both operands are pointers, [...] bring them to their composite 11730 // pointer type. 11731 // For <=>, the only valid non-pointer types are arrays and functions, and 11732 // we already decayed those, so this is really the same as the relational 11733 // comparison rule. 11734 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11735 (IsOrdered ? 2 : 1) && 11736 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11737 RHSType->isObjCObjectPointerType()))) { 11738 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11739 return QualType(); 11740 return computeResultTy(); 11741 } 11742 } else if (LHSType->isPointerType() && 11743 RHSType->isPointerType()) { // C99 6.5.8p2 11744 // All of the following pointer-related warnings are GCC extensions, except 11745 // when handling null pointer constants. 11746 QualType LCanPointeeTy = 11747 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11748 QualType RCanPointeeTy = 11749 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11750 11751 // C99 6.5.9p2 and C99 6.5.8p2 11752 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11753 RCanPointeeTy.getUnqualifiedType())) { 11754 if (IsRelational) { 11755 // Pointers both need to point to complete or incomplete types 11756 if ((LCanPointeeTy->isIncompleteType() != 11757 RCanPointeeTy->isIncompleteType()) && 11758 !getLangOpts().C11) { 11759 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11760 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11761 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11762 << RCanPointeeTy->isIncompleteType(); 11763 } 11764 if (LCanPointeeTy->isFunctionType()) { 11765 // Valid unless a relational comparison of function pointers 11766 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11767 << LHSType << RHSType << LHS.get()->getSourceRange() 11768 << RHS.get()->getSourceRange(); 11769 } 11770 } 11771 } else if (!IsRelational && 11772 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11773 // Valid unless comparison between non-null pointer and function pointer 11774 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11775 && !LHSIsNull && !RHSIsNull) 11776 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11777 /*isError*/false); 11778 } else { 11779 // Invalid 11780 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11781 } 11782 if (LCanPointeeTy != RCanPointeeTy) { 11783 // Treat NULL constant as a special case in OpenCL. 11784 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11785 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11786 Diag(Loc, 11787 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11788 << LHSType << RHSType << 0 /* comparison */ 11789 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11790 } 11791 } 11792 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11793 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11794 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11795 : CK_BitCast; 11796 if (LHSIsNull && !RHSIsNull) 11797 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11798 else 11799 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11800 } 11801 return computeResultTy(); 11802 } 11803 11804 if (getLangOpts().CPlusPlus) { 11805 // C++ [expr.eq]p4: 11806 // Two operands of type std::nullptr_t or one operand of type 11807 // std::nullptr_t and the other a null pointer constant compare equal. 11808 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11809 if (LHSType->isNullPtrType()) { 11810 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11811 return computeResultTy(); 11812 } 11813 if (RHSType->isNullPtrType()) { 11814 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11815 return computeResultTy(); 11816 } 11817 } 11818 11819 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11820 // These aren't covered by the composite pointer type rules. 11821 if (!IsOrdered && RHSType->isNullPtrType() && 11822 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11823 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11824 return computeResultTy(); 11825 } 11826 if (!IsOrdered && LHSType->isNullPtrType() && 11827 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11828 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11829 return computeResultTy(); 11830 } 11831 11832 if (IsRelational && 11833 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11834 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11835 // HACK: Relational comparison of nullptr_t against a pointer type is 11836 // invalid per DR583, but we allow it within std::less<> and friends, 11837 // since otherwise common uses of it break. 11838 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11839 // friends to have std::nullptr_t overload candidates. 11840 DeclContext *DC = CurContext; 11841 if (isa<FunctionDecl>(DC)) 11842 DC = DC->getParent(); 11843 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11844 if (CTSD->isInStdNamespace() && 11845 llvm::StringSwitch<bool>(CTSD->getName()) 11846 .Cases("less", "less_equal", "greater", "greater_equal", true) 11847 .Default(false)) { 11848 if (RHSType->isNullPtrType()) 11849 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11850 else 11851 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11852 return computeResultTy(); 11853 } 11854 } 11855 } 11856 11857 // C++ [expr.eq]p2: 11858 // If at least one operand is a pointer to member, [...] bring them to 11859 // their composite pointer type. 11860 if (!IsOrdered && 11861 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11862 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11863 return QualType(); 11864 else 11865 return computeResultTy(); 11866 } 11867 } 11868 11869 // Handle block pointer types. 11870 if (!IsOrdered && LHSType->isBlockPointerType() && 11871 RHSType->isBlockPointerType()) { 11872 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11873 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11874 11875 if (!LHSIsNull && !RHSIsNull && 11876 !Context.typesAreCompatible(lpointee, rpointee)) { 11877 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11878 << LHSType << RHSType << LHS.get()->getSourceRange() 11879 << RHS.get()->getSourceRange(); 11880 } 11881 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11882 return computeResultTy(); 11883 } 11884 11885 // Allow block pointers to be compared with null pointer constants. 11886 if (!IsOrdered 11887 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11888 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11889 if (!LHSIsNull && !RHSIsNull) { 11890 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11891 ->getPointeeType()->isVoidType()) 11892 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11893 ->getPointeeType()->isVoidType()))) 11894 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11895 << LHSType << RHSType << LHS.get()->getSourceRange() 11896 << RHS.get()->getSourceRange(); 11897 } 11898 if (LHSIsNull && !RHSIsNull) 11899 LHS = ImpCastExprToType(LHS.get(), RHSType, 11900 RHSType->isPointerType() ? CK_BitCast 11901 : CK_AnyPointerToBlockPointerCast); 11902 else 11903 RHS = ImpCastExprToType(RHS.get(), LHSType, 11904 LHSType->isPointerType() ? CK_BitCast 11905 : CK_AnyPointerToBlockPointerCast); 11906 return computeResultTy(); 11907 } 11908 11909 if (LHSType->isObjCObjectPointerType() || 11910 RHSType->isObjCObjectPointerType()) { 11911 const PointerType *LPT = LHSType->getAs<PointerType>(); 11912 const PointerType *RPT = RHSType->getAs<PointerType>(); 11913 if (LPT || RPT) { 11914 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11915 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11916 11917 if (!LPtrToVoid && !RPtrToVoid && 11918 !Context.typesAreCompatible(LHSType, RHSType)) { 11919 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11920 /*isError*/false); 11921 } 11922 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11923 // the RHS, but we have test coverage for this behavior. 11924 // FIXME: Consider using convertPointersToCompositeType in C++. 11925 if (LHSIsNull && !RHSIsNull) { 11926 Expr *E = LHS.get(); 11927 if (getLangOpts().ObjCAutoRefCount) 11928 CheckObjCConversion(SourceRange(), RHSType, E, 11929 CCK_ImplicitConversion); 11930 LHS = ImpCastExprToType(E, RHSType, 11931 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11932 } 11933 else { 11934 Expr *E = RHS.get(); 11935 if (getLangOpts().ObjCAutoRefCount) 11936 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11937 /*Diagnose=*/true, 11938 /*DiagnoseCFAudited=*/false, Opc); 11939 RHS = ImpCastExprToType(E, LHSType, 11940 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11941 } 11942 return computeResultTy(); 11943 } 11944 if (LHSType->isObjCObjectPointerType() && 11945 RHSType->isObjCObjectPointerType()) { 11946 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11947 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11948 /*isError*/false); 11949 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11950 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11951 11952 if (LHSIsNull && !RHSIsNull) 11953 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11954 else 11955 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11956 return computeResultTy(); 11957 } 11958 11959 if (!IsOrdered && LHSType->isBlockPointerType() && 11960 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11961 LHS = ImpCastExprToType(LHS.get(), RHSType, 11962 CK_BlockPointerToObjCPointerCast); 11963 return computeResultTy(); 11964 } else if (!IsOrdered && 11965 LHSType->isBlockCompatibleObjCPointerType(Context) && 11966 RHSType->isBlockPointerType()) { 11967 RHS = ImpCastExprToType(RHS.get(), LHSType, 11968 CK_BlockPointerToObjCPointerCast); 11969 return computeResultTy(); 11970 } 11971 } 11972 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11973 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11974 unsigned DiagID = 0; 11975 bool isError = false; 11976 if (LangOpts.DebuggerSupport) { 11977 // Under a debugger, allow the comparison of pointers to integers, 11978 // since users tend to want to compare addresses. 11979 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11980 (RHSIsNull && RHSType->isIntegerType())) { 11981 if (IsOrdered) { 11982 isError = getLangOpts().CPlusPlus; 11983 DiagID = 11984 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11985 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11986 } 11987 } else if (getLangOpts().CPlusPlus) { 11988 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11989 isError = true; 11990 } else if (IsOrdered) 11991 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11992 else 11993 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11994 11995 if (DiagID) { 11996 Diag(Loc, DiagID) 11997 << LHSType << RHSType << LHS.get()->getSourceRange() 11998 << RHS.get()->getSourceRange(); 11999 if (isError) 12000 return QualType(); 12001 } 12002 12003 if (LHSType->isIntegerType()) 12004 LHS = ImpCastExprToType(LHS.get(), RHSType, 12005 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12006 else 12007 RHS = ImpCastExprToType(RHS.get(), LHSType, 12008 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12009 return computeResultTy(); 12010 } 12011 12012 // Handle block pointers. 12013 if (!IsOrdered && RHSIsNull 12014 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12015 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12016 return computeResultTy(); 12017 } 12018 if (!IsOrdered && LHSIsNull 12019 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12020 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12021 return computeResultTy(); 12022 } 12023 12024 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12025 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12026 return computeResultTy(); 12027 } 12028 12029 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12030 return computeResultTy(); 12031 } 12032 12033 if (LHSIsNull && RHSType->isQueueT()) { 12034 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12035 return computeResultTy(); 12036 } 12037 12038 if (LHSType->isQueueT() && RHSIsNull) { 12039 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12040 return computeResultTy(); 12041 } 12042 } 12043 12044 return InvalidOperands(Loc, LHS, RHS); 12045 } 12046 12047 // Return a signed ext_vector_type that is of identical size and number of 12048 // elements. For floating point vectors, return an integer type of identical 12049 // size and number of elements. In the non ext_vector_type case, search from 12050 // the largest type to the smallest type to avoid cases where long long == long, 12051 // where long gets picked over long long. 12052 QualType Sema::GetSignedVectorType(QualType V) { 12053 const VectorType *VTy = V->castAs<VectorType>(); 12054 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12055 12056 if (isa<ExtVectorType>(VTy)) { 12057 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12058 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12059 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12060 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12061 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12062 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12063 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12064 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12065 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12066 "Unhandled vector element size in vector compare"); 12067 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12068 } 12069 12070 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12071 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12072 VectorType::GenericVector); 12073 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12074 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12075 VectorType::GenericVector); 12076 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12077 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12078 VectorType::GenericVector); 12079 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12080 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12081 VectorType::GenericVector); 12082 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12083 "Unhandled vector element size in vector compare"); 12084 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12085 VectorType::GenericVector); 12086 } 12087 12088 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12089 /// operates on extended vector types. Instead of producing an IntTy result, 12090 /// like a scalar comparison, a vector comparison produces a vector of integer 12091 /// types. 12092 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12093 SourceLocation Loc, 12094 BinaryOperatorKind Opc) { 12095 if (Opc == BO_Cmp) { 12096 Diag(Loc, diag::err_three_way_vector_comparison); 12097 return QualType(); 12098 } 12099 12100 // Check to make sure we're operating on vectors of the same type and width, 12101 // Allowing one side to be a scalar of element type. 12102 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12103 /*AllowBothBool*/true, 12104 /*AllowBoolConversions*/getLangOpts().ZVector); 12105 if (vType.isNull()) 12106 return vType; 12107 12108 QualType LHSType = LHS.get()->getType(); 12109 12110 // If AltiVec, the comparison results in a numeric type, i.e. 12111 // bool for C++, int for C 12112 if (getLangOpts().AltiVec && 12113 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12114 return Context.getLogicalOperationType(); 12115 12116 // For non-floating point types, check for self-comparisons of the form 12117 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12118 // often indicate logic errors in the program. 12119 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12120 12121 // Check for comparisons of floating point operands using != and ==. 12122 if (BinaryOperator::isEqualityOp(Opc) && 12123 LHSType->hasFloatingRepresentation()) { 12124 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12125 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12126 } 12127 12128 // Return a signed type for the vector. 12129 return GetSignedVectorType(vType); 12130 } 12131 12132 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12133 const ExprResult &XorRHS, 12134 const SourceLocation Loc) { 12135 // Do not diagnose macros. 12136 if (Loc.isMacroID()) 12137 return; 12138 12139 // Do not diagnose if both LHS and RHS are macros. 12140 if (XorLHS.get()->getExprLoc().isMacroID() && 12141 XorRHS.get()->getExprLoc().isMacroID()) 12142 return; 12143 12144 bool Negative = false; 12145 bool ExplicitPlus = false; 12146 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12147 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12148 12149 if (!LHSInt) 12150 return; 12151 if (!RHSInt) { 12152 // Check negative literals. 12153 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12154 UnaryOperatorKind Opc = UO->getOpcode(); 12155 if (Opc != UO_Minus && Opc != UO_Plus) 12156 return; 12157 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12158 if (!RHSInt) 12159 return; 12160 Negative = (Opc == UO_Minus); 12161 ExplicitPlus = !Negative; 12162 } else { 12163 return; 12164 } 12165 } 12166 12167 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12168 llvm::APInt RightSideValue = RHSInt->getValue(); 12169 if (LeftSideValue != 2 && LeftSideValue != 10) 12170 return; 12171 12172 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12173 return; 12174 12175 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12176 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12177 llvm::StringRef ExprStr = 12178 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12179 12180 CharSourceRange XorRange = 12181 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12182 llvm::StringRef XorStr = 12183 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12184 // Do not diagnose if xor keyword/macro is used. 12185 if (XorStr == "xor") 12186 return; 12187 12188 std::string LHSStr = std::string(Lexer::getSourceText( 12189 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12190 S.getSourceManager(), S.getLangOpts())); 12191 std::string RHSStr = std::string(Lexer::getSourceText( 12192 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12193 S.getSourceManager(), S.getLangOpts())); 12194 12195 if (Negative) { 12196 RightSideValue = -RightSideValue; 12197 RHSStr = "-" + RHSStr; 12198 } else if (ExplicitPlus) { 12199 RHSStr = "+" + RHSStr; 12200 } 12201 12202 StringRef LHSStrRef = LHSStr; 12203 StringRef RHSStrRef = RHSStr; 12204 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12205 // literals. 12206 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12207 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12208 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12209 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12210 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12211 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12212 LHSStrRef.find('\'') != StringRef::npos || 12213 RHSStrRef.find('\'') != StringRef::npos) 12214 return; 12215 12216 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12217 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12218 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12219 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12220 std::string SuggestedExpr = "1 << " + RHSStr; 12221 bool Overflow = false; 12222 llvm::APInt One = (LeftSideValue - 1); 12223 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12224 if (Overflow) { 12225 if (RightSideIntValue < 64) 12226 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12227 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12228 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12229 else if (RightSideIntValue == 64) 12230 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12231 else 12232 return; 12233 } else { 12234 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12235 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12236 << PowValue.toString(10, true) 12237 << FixItHint::CreateReplacement( 12238 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12239 } 12240 12241 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12242 } else if (LeftSideValue == 10) { 12243 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12244 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12245 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12246 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12247 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12248 } 12249 } 12250 12251 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12252 SourceLocation Loc) { 12253 // Ensure that either both operands are of the same vector type, or 12254 // one operand is of a vector type and the other is of its element type. 12255 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12256 /*AllowBothBool*/true, 12257 /*AllowBoolConversions*/false); 12258 if (vType.isNull()) 12259 return InvalidOperands(Loc, LHS, RHS); 12260 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12261 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12262 return InvalidOperands(Loc, LHS, RHS); 12263 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12264 // usage of the logical operators && and || with vectors in C. This 12265 // check could be notionally dropped. 12266 if (!getLangOpts().CPlusPlus && 12267 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12268 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12269 12270 return GetSignedVectorType(LHS.get()->getType()); 12271 } 12272 12273 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12274 SourceLocation Loc, 12275 bool IsCompAssign) { 12276 if (!IsCompAssign) { 12277 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12278 if (LHS.isInvalid()) 12279 return QualType(); 12280 } 12281 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12282 if (RHS.isInvalid()) 12283 return QualType(); 12284 12285 // For conversion purposes, we ignore any qualifiers. 12286 // For example, "const float" and "float" are equivalent. 12287 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12288 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12289 12290 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12291 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12292 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12293 12294 if (Context.hasSameType(LHSType, RHSType)) 12295 return LHSType; 12296 12297 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12298 // case we have to return InvalidOperands. 12299 ExprResult OriginalLHS = LHS; 12300 ExprResult OriginalRHS = RHS; 12301 if (LHSMatType && !RHSMatType) { 12302 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12303 if (!RHS.isInvalid()) 12304 return LHSType; 12305 12306 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12307 } 12308 12309 if (!LHSMatType && RHSMatType) { 12310 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12311 if (!LHS.isInvalid()) 12312 return RHSType; 12313 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12314 } 12315 12316 return InvalidOperands(Loc, LHS, RHS); 12317 } 12318 12319 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12320 SourceLocation Loc, 12321 bool IsCompAssign) { 12322 if (!IsCompAssign) { 12323 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12324 if (LHS.isInvalid()) 12325 return QualType(); 12326 } 12327 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12328 if (RHS.isInvalid()) 12329 return QualType(); 12330 12331 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12332 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12333 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12334 12335 if (LHSMatType && RHSMatType) { 12336 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12337 return InvalidOperands(Loc, LHS, RHS); 12338 12339 if (!Context.hasSameType(LHSMatType->getElementType(), 12340 RHSMatType->getElementType())) 12341 return InvalidOperands(Loc, LHS, RHS); 12342 12343 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12344 LHSMatType->getNumRows(), 12345 RHSMatType->getNumColumns()); 12346 } 12347 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12348 } 12349 12350 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12351 SourceLocation Loc, 12352 BinaryOperatorKind Opc) { 12353 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12354 12355 bool IsCompAssign = 12356 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12357 12358 if (LHS.get()->getType()->isVectorType() || 12359 RHS.get()->getType()->isVectorType()) { 12360 if (LHS.get()->getType()->hasIntegerRepresentation() && 12361 RHS.get()->getType()->hasIntegerRepresentation()) 12362 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12363 /*AllowBothBool*/true, 12364 /*AllowBoolConversions*/getLangOpts().ZVector); 12365 return InvalidOperands(Loc, LHS, RHS); 12366 } 12367 12368 if (Opc == BO_And) 12369 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12370 12371 if (LHS.get()->getType()->hasFloatingRepresentation() || 12372 RHS.get()->getType()->hasFloatingRepresentation()) 12373 return InvalidOperands(Loc, LHS, RHS); 12374 12375 ExprResult LHSResult = LHS, RHSResult = RHS; 12376 QualType compType = UsualArithmeticConversions( 12377 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12378 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12379 return QualType(); 12380 LHS = LHSResult.get(); 12381 RHS = RHSResult.get(); 12382 12383 if (Opc == BO_Xor) 12384 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12385 12386 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12387 return compType; 12388 return InvalidOperands(Loc, LHS, RHS); 12389 } 12390 12391 // C99 6.5.[13,14] 12392 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12393 SourceLocation Loc, 12394 BinaryOperatorKind Opc) { 12395 // Check vector operands differently. 12396 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12397 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12398 12399 bool EnumConstantInBoolContext = false; 12400 for (const ExprResult &HS : {LHS, RHS}) { 12401 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12402 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12403 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12404 EnumConstantInBoolContext = true; 12405 } 12406 } 12407 12408 if (EnumConstantInBoolContext) 12409 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12410 12411 // Diagnose cases where the user write a logical and/or but probably meant a 12412 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12413 // is a constant. 12414 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12415 !LHS.get()->getType()->isBooleanType() && 12416 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12417 // Don't warn in macros or template instantiations. 12418 !Loc.isMacroID() && !inTemplateInstantiation()) { 12419 // If the RHS can be constant folded, and if it constant folds to something 12420 // that isn't 0 or 1 (which indicate a potential logical operation that 12421 // happened to fold to true/false) then warn. 12422 // Parens on the RHS are ignored. 12423 Expr::EvalResult EVResult; 12424 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12425 llvm::APSInt Result = EVResult.Val.getInt(); 12426 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12427 !RHS.get()->getExprLoc().isMacroID()) || 12428 (Result != 0 && Result != 1)) { 12429 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12430 << RHS.get()->getSourceRange() 12431 << (Opc == BO_LAnd ? "&&" : "||"); 12432 // Suggest replacing the logical operator with the bitwise version 12433 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12434 << (Opc == BO_LAnd ? "&" : "|") 12435 << FixItHint::CreateReplacement(SourceRange( 12436 Loc, getLocForEndOfToken(Loc)), 12437 Opc == BO_LAnd ? "&" : "|"); 12438 if (Opc == BO_LAnd) 12439 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12440 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12441 << FixItHint::CreateRemoval( 12442 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12443 RHS.get()->getEndLoc())); 12444 } 12445 } 12446 } 12447 12448 if (!Context.getLangOpts().CPlusPlus) { 12449 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12450 // not operate on the built-in scalar and vector float types. 12451 if (Context.getLangOpts().OpenCL && 12452 Context.getLangOpts().OpenCLVersion < 120) { 12453 if (LHS.get()->getType()->isFloatingType() || 12454 RHS.get()->getType()->isFloatingType()) 12455 return InvalidOperands(Loc, LHS, RHS); 12456 } 12457 12458 LHS = UsualUnaryConversions(LHS.get()); 12459 if (LHS.isInvalid()) 12460 return QualType(); 12461 12462 RHS = UsualUnaryConversions(RHS.get()); 12463 if (RHS.isInvalid()) 12464 return QualType(); 12465 12466 if (!LHS.get()->getType()->isScalarType() || 12467 !RHS.get()->getType()->isScalarType()) 12468 return InvalidOperands(Loc, LHS, RHS); 12469 12470 return Context.IntTy; 12471 } 12472 12473 // The following is safe because we only use this method for 12474 // non-overloadable operands. 12475 12476 // C++ [expr.log.and]p1 12477 // C++ [expr.log.or]p1 12478 // The operands are both contextually converted to type bool. 12479 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12480 if (LHSRes.isInvalid()) 12481 return InvalidOperands(Loc, LHS, RHS); 12482 LHS = LHSRes; 12483 12484 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12485 if (RHSRes.isInvalid()) 12486 return InvalidOperands(Loc, LHS, RHS); 12487 RHS = RHSRes; 12488 12489 // C++ [expr.log.and]p2 12490 // C++ [expr.log.or]p2 12491 // The result is a bool. 12492 return Context.BoolTy; 12493 } 12494 12495 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12496 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12497 if (!ME) return false; 12498 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12499 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12500 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12501 if (!Base) return false; 12502 return Base->getMethodDecl() != nullptr; 12503 } 12504 12505 /// Is the given expression (which must be 'const') a reference to a 12506 /// variable which was originally non-const, but which has become 12507 /// 'const' due to being captured within a block? 12508 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12509 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12510 assert(E->isLValue() && E->getType().isConstQualified()); 12511 E = E->IgnoreParens(); 12512 12513 // Must be a reference to a declaration from an enclosing scope. 12514 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12515 if (!DRE) return NCCK_None; 12516 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12517 12518 // The declaration must be a variable which is not declared 'const'. 12519 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12520 if (!var) return NCCK_None; 12521 if (var->getType().isConstQualified()) return NCCK_None; 12522 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12523 12524 // Decide whether the first capture was for a block or a lambda. 12525 DeclContext *DC = S.CurContext, *Prev = nullptr; 12526 // Decide whether the first capture was for a block or a lambda. 12527 while (DC) { 12528 // For init-capture, it is possible that the variable belongs to the 12529 // template pattern of the current context. 12530 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12531 if (var->isInitCapture() && 12532 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12533 break; 12534 if (DC == var->getDeclContext()) 12535 break; 12536 Prev = DC; 12537 DC = DC->getParent(); 12538 } 12539 // Unless we have an init-capture, we've gone one step too far. 12540 if (!var->isInitCapture()) 12541 DC = Prev; 12542 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12543 } 12544 12545 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12546 Ty = Ty.getNonReferenceType(); 12547 if (IsDereference && Ty->isPointerType()) 12548 Ty = Ty->getPointeeType(); 12549 return !Ty.isConstQualified(); 12550 } 12551 12552 // Update err_typecheck_assign_const and note_typecheck_assign_const 12553 // when this enum is changed. 12554 enum { 12555 ConstFunction, 12556 ConstVariable, 12557 ConstMember, 12558 ConstMethod, 12559 NestedConstMember, 12560 ConstUnknown, // Keep as last element 12561 }; 12562 12563 /// Emit the "read-only variable not assignable" error and print notes to give 12564 /// more information about why the variable is not assignable, such as pointing 12565 /// to the declaration of a const variable, showing that a method is const, or 12566 /// that the function is returning a const reference. 12567 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12568 SourceLocation Loc) { 12569 SourceRange ExprRange = E->getSourceRange(); 12570 12571 // Only emit one error on the first const found. All other consts will emit 12572 // a note to the error. 12573 bool DiagnosticEmitted = false; 12574 12575 // Track if the current expression is the result of a dereference, and if the 12576 // next checked expression is the result of a dereference. 12577 bool IsDereference = false; 12578 bool NextIsDereference = false; 12579 12580 // Loop to process MemberExpr chains. 12581 while (true) { 12582 IsDereference = NextIsDereference; 12583 12584 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12585 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12586 NextIsDereference = ME->isArrow(); 12587 const ValueDecl *VD = ME->getMemberDecl(); 12588 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12589 // Mutable fields can be modified even if the class is const. 12590 if (Field->isMutable()) { 12591 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12592 break; 12593 } 12594 12595 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12596 if (!DiagnosticEmitted) { 12597 S.Diag(Loc, diag::err_typecheck_assign_const) 12598 << ExprRange << ConstMember << false /*static*/ << Field 12599 << Field->getType(); 12600 DiagnosticEmitted = true; 12601 } 12602 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12603 << ConstMember << false /*static*/ << Field << Field->getType() 12604 << Field->getSourceRange(); 12605 } 12606 E = ME->getBase(); 12607 continue; 12608 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12609 if (VDecl->getType().isConstQualified()) { 12610 if (!DiagnosticEmitted) { 12611 S.Diag(Loc, diag::err_typecheck_assign_const) 12612 << ExprRange << ConstMember << true /*static*/ << VDecl 12613 << VDecl->getType(); 12614 DiagnosticEmitted = true; 12615 } 12616 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12617 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12618 << VDecl->getSourceRange(); 12619 } 12620 // Static fields do not inherit constness from parents. 12621 break; 12622 } 12623 break; // End MemberExpr 12624 } else if (const ArraySubscriptExpr *ASE = 12625 dyn_cast<ArraySubscriptExpr>(E)) { 12626 E = ASE->getBase()->IgnoreParenImpCasts(); 12627 continue; 12628 } else if (const ExtVectorElementExpr *EVE = 12629 dyn_cast<ExtVectorElementExpr>(E)) { 12630 E = EVE->getBase()->IgnoreParenImpCasts(); 12631 continue; 12632 } 12633 break; 12634 } 12635 12636 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12637 // Function calls 12638 const FunctionDecl *FD = CE->getDirectCallee(); 12639 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12640 if (!DiagnosticEmitted) { 12641 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12642 << ConstFunction << FD; 12643 DiagnosticEmitted = true; 12644 } 12645 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12646 diag::note_typecheck_assign_const) 12647 << ConstFunction << FD << FD->getReturnType() 12648 << FD->getReturnTypeSourceRange(); 12649 } 12650 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12651 // Point to variable declaration. 12652 if (const ValueDecl *VD = DRE->getDecl()) { 12653 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12654 if (!DiagnosticEmitted) { 12655 S.Diag(Loc, diag::err_typecheck_assign_const) 12656 << ExprRange << ConstVariable << VD << VD->getType(); 12657 DiagnosticEmitted = true; 12658 } 12659 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12660 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12661 } 12662 } 12663 } else if (isa<CXXThisExpr>(E)) { 12664 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12665 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12666 if (MD->isConst()) { 12667 if (!DiagnosticEmitted) { 12668 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12669 << ConstMethod << MD; 12670 DiagnosticEmitted = true; 12671 } 12672 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12673 << ConstMethod << MD << MD->getSourceRange(); 12674 } 12675 } 12676 } 12677 } 12678 12679 if (DiagnosticEmitted) 12680 return; 12681 12682 // Can't determine a more specific message, so display the generic error. 12683 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12684 } 12685 12686 enum OriginalExprKind { 12687 OEK_Variable, 12688 OEK_Member, 12689 OEK_LValue 12690 }; 12691 12692 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12693 const RecordType *Ty, 12694 SourceLocation Loc, SourceRange Range, 12695 OriginalExprKind OEK, 12696 bool &DiagnosticEmitted) { 12697 std::vector<const RecordType *> RecordTypeList; 12698 RecordTypeList.push_back(Ty); 12699 unsigned NextToCheckIndex = 0; 12700 // We walk the record hierarchy breadth-first to ensure that we print 12701 // diagnostics in field nesting order. 12702 while (RecordTypeList.size() > NextToCheckIndex) { 12703 bool IsNested = NextToCheckIndex > 0; 12704 for (const FieldDecl *Field : 12705 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12706 // First, check every field for constness. 12707 QualType FieldTy = Field->getType(); 12708 if (FieldTy.isConstQualified()) { 12709 if (!DiagnosticEmitted) { 12710 S.Diag(Loc, diag::err_typecheck_assign_const) 12711 << Range << NestedConstMember << OEK << VD 12712 << IsNested << Field; 12713 DiagnosticEmitted = true; 12714 } 12715 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12716 << NestedConstMember << IsNested << Field 12717 << FieldTy << Field->getSourceRange(); 12718 } 12719 12720 // Then we append it to the list to check next in order. 12721 FieldTy = FieldTy.getCanonicalType(); 12722 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12723 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12724 RecordTypeList.push_back(FieldRecTy); 12725 } 12726 } 12727 ++NextToCheckIndex; 12728 } 12729 } 12730 12731 /// Emit an error for the case where a record we are trying to assign to has a 12732 /// const-qualified field somewhere in its hierarchy. 12733 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12734 SourceLocation Loc) { 12735 QualType Ty = E->getType(); 12736 assert(Ty->isRecordType() && "lvalue was not record?"); 12737 SourceRange Range = E->getSourceRange(); 12738 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12739 bool DiagEmitted = false; 12740 12741 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12742 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12743 Range, OEK_Member, DiagEmitted); 12744 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12745 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12746 Range, OEK_Variable, DiagEmitted); 12747 else 12748 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12749 Range, OEK_LValue, DiagEmitted); 12750 if (!DiagEmitted) 12751 DiagnoseConstAssignment(S, E, Loc); 12752 } 12753 12754 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12755 /// emit an error and return true. If so, return false. 12756 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12757 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12758 12759 S.CheckShadowingDeclModification(E, Loc); 12760 12761 SourceLocation OrigLoc = Loc; 12762 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12763 &Loc); 12764 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12765 IsLV = Expr::MLV_InvalidMessageExpression; 12766 if (IsLV == Expr::MLV_Valid) 12767 return false; 12768 12769 unsigned DiagID = 0; 12770 bool NeedType = false; 12771 switch (IsLV) { // C99 6.5.16p2 12772 case Expr::MLV_ConstQualified: 12773 // Use a specialized diagnostic when we're assigning to an object 12774 // from an enclosing function or block. 12775 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12776 if (NCCK == NCCK_Block) 12777 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12778 else 12779 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12780 break; 12781 } 12782 12783 // In ARC, use some specialized diagnostics for occasions where we 12784 // infer 'const'. These are always pseudo-strong variables. 12785 if (S.getLangOpts().ObjCAutoRefCount) { 12786 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12787 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12788 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12789 12790 // Use the normal diagnostic if it's pseudo-__strong but the 12791 // user actually wrote 'const'. 12792 if (var->isARCPseudoStrong() && 12793 (!var->getTypeSourceInfo() || 12794 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12795 // There are three pseudo-strong cases: 12796 // - self 12797 ObjCMethodDecl *method = S.getCurMethodDecl(); 12798 if (method && var == method->getSelfDecl()) { 12799 DiagID = method->isClassMethod() 12800 ? diag::err_typecheck_arc_assign_self_class_method 12801 : diag::err_typecheck_arc_assign_self; 12802 12803 // - Objective-C externally_retained attribute. 12804 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12805 isa<ParmVarDecl>(var)) { 12806 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12807 12808 // - fast enumeration variables 12809 } else { 12810 DiagID = diag::err_typecheck_arr_assign_enumeration; 12811 } 12812 12813 SourceRange Assign; 12814 if (Loc != OrigLoc) 12815 Assign = SourceRange(OrigLoc, OrigLoc); 12816 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12817 // We need to preserve the AST regardless, so migration tool 12818 // can do its job. 12819 return false; 12820 } 12821 } 12822 } 12823 12824 // If none of the special cases above are triggered, then this is a 12825 // simple const assignment. 12826 if (DiagID == 0) { 12827 DiagnoseConstAssignment(S, E, Loc); 12828 return true; 12829 } 12830 12831 break; 12832 case Expr::MLV_ConstAddrSpace: 12833 DiagnoseConstAssignment(S, E, Loc); 12834 return true; 12835 case Expr::MLV_ConstQualifiedField: 12836 DiagnoseRecursiveConstFields(S, E, Loc); 12837 return true; 12838 case Expr::MLV_ArrayType: 12839 case Expr::MLV_ArrayTemporary: 12840 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12841 NeedType = true; 12842 break; 12843 case Expr::MLV_NotObjectType: 12844 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12845 NeedType = true; 12846 break; 12847 case Expr::MLV_LValueCast: 12848 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12849 break; 12850 case Expr::MLV_Valid: 12851 llvm_unreachable("did not take early return for MLV_Valid"); 12852 case Expr::MLV_InvalidExpression: 12853 case Expr::MLV_MemberFunction: 12854 case Expr::MLV_ClassTemporary: 12855 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12856 break; 12857 case Expr::MLV_IncompleteType: 12858 case Expr::MLV_IncompleteVoidType: 12859 return S.RequireCompleteType(Loc, E->getType(), 12860 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12861 case Expr::MLV_DuplicateVectorComponents: 12862 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12863 break; 12864 case Expr::MLV_NoSetterProperty: 12865 llvm_unreachable("readonly properties should be processed differently"); 12866 case Expr::MLV_InvalidMessageExpression: 12867 DiagID = diag::err_readonly_message_assignment; 12868 break; 12869 case Expr::MLV_SubObjCPropertySetting: 12870 DiagID = diag::err_no_subobject_property_setting; 12871 break; 12872 } 12873 12874 SourceRange Assign; 12875 if (Loc != OrigLoc) 12876 Assign = SourceRange(OrigLoc, OrigLoc); 12877 if (NeedType) 12878 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12879 else 12880 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12881 return true; 12882 } 12883 12884 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12885 SourceLocation Loc, 12886 Sema &Sema) { 12887 if (Sema.inTemplateInstantiation()) 12888 return; 12889 if (Sema.isUnevaluatedContext()) 12890 return; 12891 if (Loc.isInvalid() || Loc.isMacroID()) 12892 return; 12893 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12894 return; 12895 12896 // C / C++ fields 12897 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12898 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12899 if (ML && MR) { 12900 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12901 return; 12902 const ValueDecl *LHSDecl = 12903 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12904 const ValueDecl *RHSDecl = 12905 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12906 if (LHSDecl != RHSDecl) 12907 return; 12908 if (LHSDecl->getType().isVolatileQualified()) 12909 return; 12910 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12911 if (RefTy->getPointeeType().isVolatileQualified()) 12912 return; 12913 12914 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12915 } 12916 12917 // Objective-C instance variables 12918 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12919 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12920 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12921 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12922 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12923 if (RL && RR && RL->getDecl() == RR->getDecl()) 12924 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12925 } 12926 } 12927 12928 // C99 6.5.16.1 12929 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12930 SourceLocation Loc, 12931 QualType CompoundType) { 12932 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12933 12934 // Verify that LHS is a modifiable lvalue, and emit error if not. 12935 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12936 return QualType(); 12937 12938 QualType LHSType = LHSExpr->getType(); 12939 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12940 CompoundType; 12941 // OpenCL v1.2 s6.1.1.1 p2: 12942 // The half data type can only be used to declare a pointer to a buffer that 12943 // contains half values 12944 if (getLangOpts().OpenCL && 12945 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 12946 LHSType->isHalfType()) { 12947 Diag(Loc, diag::err_opencl_half_load_store) << 1 12948 << LHSType.getUnqualifiedType(); 12949 return QualType(); 12950 } 12951 12952 AssignConvertType ConvTy; 12953 if (CompoundType.isNull()) { 12954 Expr *RHSCheck = RHS.get(); 12955 12956 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12957 12958 QualType LHSTy(LHSType); 12959 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12960 if (RHS.isInvalid()) 12961 return QualType(); 12962 // Special case of NSObject attributes on c-style pointer types. 12963 if (ConvTy == IncompatiblePointer && 12964 ((Context.isObjCNSObjectType(LHSType) && 12965 RHSType->isObjCObjectPointerType()) || 12966 (Context.isObjCNSObjectType(RHSType) && 12967 LHSType->isObjCObjectPointerType()))) 12968 ConvTy = Compatible; 12969 12970 if (ConvTy == Compatible && 12971 LHSType->isObjCObjectType()) 12972 Diag(Loc, diag::err_objc_object_assignment) 12973 << LHSType; 12974 12975 // If the RHS is a unary plus or minus, check to see if they = and + are 12976 // right next to each other. If so, the user may have typo'd "x =+ 4" 12977 // instead of "x += 4". 12978 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12979 RHSCheck = ICE->getSubExpr(); 12980 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12981 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12982 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12983 // Only if the two operators are exactly adjacent. 12984 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12985 // And there is a space or other character before the subexpr of the 12986 // unary +/-. We don't want to warn on "x=-1". 12987 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12988 UO->getSubExpr()->getBeginLoc().isFileID()) { 12989 Diag(Loc, diag::warn_not_compound_assign) 12990 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12991 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12992 } 12993 } 12994 12995 if (ConvTy == Compatible) { 12996 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12997 // Warn about retain cycles where a block captures the LHS, but 12998 // not if the LHS is a simple variable into which the block is 12999 // being stored...unless that variable can be captured by reference! 13000 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13001 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13002 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13003 checkRetainCycles(LHSExpr, RHS.get()); 13004 } 13005 13006 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13007 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13008 // It is safe to assign a weak reference into a strong variable. 13009 // Although this code can still have problems: 13010 // id x = self.weakProp; 13011 // id y = self.weakProp; 13012 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13013 // paths through the function. This should be revisited if 13014 // -Wrepeated-use-of-weak is made flow-sensitive. 13015 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13016 // variable, which will be valid for the current autorelease scope. 13017 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13018 RHS.get()->getBeginLoc())) 13019 getCurFunction()->markSafeWeakUse(RHS.get()); 13020 13021 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13022 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13023 } 13024 } 13025 } else { 13026 // Compound assignment "x += y" 13027 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13028 } 13029 13030 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13031 RHS.get(), AA_Assigning)) 13032 return QualType(); 13033 13034 CheckForNullPointerDereference(*this, LHSExpr); 13035 13036 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13037 if (CompoundType.isNull()) { 13038 // C++2a [expr.ass]p5: 13039 // A simple-assignment whose left operand is of a volatile-qualified 13040 // type is deprecated unless the assignment is either a discarded-value 13041 // expression or an unevaluated operand 13042 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13043 } else { 13044 // C++2a [expr.ass]p6: 13045 // [Compound-assignment] expressions are deprecated if E1 has 13046 // volatile-qualified type 13047 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13048 } 13049 } 13050 13051 // C99 6.5.16p3: The type of an assignment expression is the type of the 13052 // left operand unless the left operand has qualified type, in which case 13053 // it is the unqualified version of the type of the left operand. 13054 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13055 // is converted to the type of the assignment expression (above). 13056 // C++ 5.17p1: the type of the assignment expression is that of its left 13057 // operand. 13058 return (getLangOpts().CPlusPlus 13059 ? LHSType : LHSType.getUnqualifiedType()); 13060 } 13061 13062 // Only ignore explicit casts to void. 13063 static bool IgnoreCommaOperand(const Expr *E) { 13064 E = E->IgnoreParens(); 13065 13066 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13067 if (CE->getCastKind() == CK_ToVoid) { 13068 return true; 13069 } 13070 13071 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13072 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13073 CE->getSubExpr()->getType()->isDependentType()) { 13074 return true; 13075 } 13076 } 13077 13078 return false; 13079 } 13080 13081 // Look for instances where it is likely the comma operator is confused with 13082 // another operator. There is an explicit list of acceptable expressions for 13083 // the left hand side of the comma operator, otherwise emit a warning. 13084 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13085 // No warnings in macros 13086 if (Loc.isMacroID()) 13087 return; 13088 13089 // Don't warn in template instantiations. 13090 if (inTemplateInstantiation()) 13091 return; 13092 13093 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13094 // instead, skip more than needed, then call back into here with the 13095 // CommaVisitor in SemaStmt.cpp. 13096 // The listed locations are the initialization and increment portions 13097 // of a for loop. The additional checks are on the condition of 13098 // if statements, do/while loops, and for loops. 13099 // Differences in scope flags for C89 mode requires the extra logic. 13100 const unsigned ForIncrementFlags = 13101 getLangOpts().C99 || getLangOpts().CPlusPlus 13102 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13103 : Scope::ContinueScope | Scope::BreakScope; 13104 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13105 const unsigned ScopeFlags = getCurScope()->getFlags(); 13106 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13107 (ScopeFlags & ForInitFlags) == ForInitFlags) 13108 return; 13109 13110 // If there are multiple comma operators used together, get the RHS of the 13111 // of the comma operator as the LHS. 13112 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13113 if (BO->getOpcode() != BO_Comma) 13114 break; 13115 LHS = BO->getRHS(); 13116 } 13117 13118 // Only allow some expressions on LHS to not warn. 13119 if (IgnoreCommaOperand(LHS)) 13120 return; 13121 13122 Diag(Loc, diag::warn_comma_operator); 13123 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13124 << LHS->getSourceRange() 13125 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13126 LangOpts.CPlusPlus ? "static_cast<void>(" 13127 : "(void)(") 13128 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13129 ")"); 13130 } 13131 13132 // C99 6.5.17 13133 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13134 SourceLocation Loc) { 13135 LHS = S.CheckPlaceholderExpr(LHS.get()); 13136 RHS = S.CheckPlaceholderExpr(RHS.get()); 13137 if (LHS.isInvalid() || RHS.isInvalid()) 13138 return QualType(); 13139 13140 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13141 // operands, but not unary promotions. 13142 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13143 13144 // So we treat the LHS as a ignored value, and in C++ we allow the 13145 // containing site to determine what should be done with the RHS. 13146 LHS = S.IgnoredValueConversions(LHS.get()); 13147 if (LHS.isInvalid()) 13148 return QualType(); 13149 13150 S.DiagnoseUnusedExprResult(LHS.get()); 13151 13152 if (!S.getLangOpts().CPlusPlus) { 13153 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13154 if (RHS.isInvalid()) 13155 return QualType(); 13156 if (!RHS.get()->getType()->isVoidType()) 13157 S.RequireCompleteType(Loc, RHS.get()->getType(), 13158 diag::err_incomplete_type); 13159 } 13160 13161 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13162 S.DiagnoseCommaOperator(LHS.get(), Loc); 13163 13164 return RHS.get()->getType(); 13165 } 13166 13167 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13168 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13169 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13170 ExprValueKind &VK, 13171 ExprObjectKind &OK, 13172 SourceLocation OpLoc, 13173 bool IsInc, bool IsPrefix) { 13174 if (Op->isTypeDependent()) 13175 return S.Context.DependentTy; 13176 13177 QualType ResType = Op->getType(); 13178 // Atomic types can be used for increment / decrement where the non-atomic 13179 // versions can, so ignore the _Atomic() specifier for the purpose of 13180 // checking. 13181 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13182 ResType = ResAtomicType->getValueType(); 13183 13184 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13185 13186 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13187 // Decrement of bool is not allowed. 13188 if (!IsInc) { 13189 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13190 return QualType(); 13191 } 13192 // Increment of bool sets it to true, but is deprecated. 13193 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13194 : diag::warn_increment_bool) 13195 << Op->getSourceRange(); 13196 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13197 // Error on enum increments and decrements in C++ mode 13198 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13199 return QualType(); 13200 } else if (ResType->isRealType()) { 13201 // OK! 13202 } else if (ResType->isPointerType()) { 13203 // C99 6.5.2.4p2, 6.5.6p2 13204 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13205 return QualType(); 13206 } else if (ResType->isObjCObjectPointerType()) { 13207 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13208 // Otherwise, we just need a complete type. 13209 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13210 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13211 return QualType(); 13212 } else if (ResType->isAnyComplexType()) { 13213 // C99 does not support ++/-- on complex types, we allow as an extension. 13214 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13215 << ResType << Op->getSourceRange(); 13216 } else if (ResType->isPlaceholderType()) { 13217 ExprResult PR = S.CheckPlaceholderExpr(Op); 13218 if (PR.isInvalid()) return QualType(); 13219 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13220 IsInc, IsPrefix); 13221 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13222 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13223 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13224 (ResType->castAs<VectorType>()->getVectorKind() != 13225 VectorType::AltiVecBool)) { 13226 // The z vector extensions allow ++ and -- for non-bool vectors. 13227 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13228 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13229 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13230 } else { 13231 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13232 << ResType << int(IsInc) << Op->getSourceRange(); 13233 return QualType(); 13234 } 13235 // At this point, we know we have a real, complex or pointer type. 13236 // Now make sure the operand is a modifiable lvalue. 13237 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13238 return QualType(); 13239 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13240 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13241 // An operand with volatile-qualified type is deprecated 13242 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13243 << IsInc << ResType; 13244 } 13245 // In C++, a prefix increment is the same type as the operand. Otherwise 13246 // (in C or with postfix), the increment is the unqualified type of the 13247 // operand. 13248 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13249 VK = VK_LValue; 13250 OK = Op->getObjectKind(); 13251 return ResType; 13252 } else { 13253 VK = VK_RValue; 13254 return ResType.getUnqualifiedType(); 13255 } 13256 } 13257 13258 13259 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13260 /// This routine allows us to typecheck complex/recursive expressions 13261 /// where the declaration is needed for type checking. We only need to 13262 /// handle cases when the expression references a function designator 13263 /// or is an lvalue. Here are some examples: 13264 /// - &(x) => x 13265 /// - &*****f => f for f a function designator. 13266 /// - &s.xx => s 13267 /// - &s.zz[1].yy -> s, if zz is an array 13268 /// - *(x + 1) -> x, if x is an array 13269 /// - &"123"[2] -> 0 13270 /// - & __real__ x -> x 13271 /// 13272 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13273 /// members. 13274 static ValueDecl *getPrimaryDecl(Expr *E) { 13275 switch (E->getStmtClass()) { 13276 case Stmt::DeclRefExprClass: 13277 return cast<DeclRefExpr>(E)->getDecl(); 13278 case Stmt::MemberExprClass: 13279 // If this is an arrow operator, the address is an offset from 13280 // the base's value, so the object the base refers to is 13281 // irrelevant. 13282 if (cast<MemberExpr>(E)->isArrow()) 13283 return nullptr; 13284 // Otherwise, the expression refers to a part of the base 13285 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13286 case Stmt::ArraySubscriptExprClass: { 13287 // FIXME: This code shouldn't be necessary! We should catch the implicit 13288 // promotion of register arrays earlier. 13289 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13290 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13291 if (ICE->getSubExpr()->getType()->isArrayType()) 13292 return getPrimaryDecl(ICE->getSubExpr()); 13293 } 13294 return nullptr; 13295 } 13296 case Stmt::UnaryOperatorClass: { 13297 UnaryOperator *UO = cast<UnaryOperator>(E); 13298 13299 switch(UO->getOpcode()) { 13300 case UO_Real: 13301 case UO_Imag: 13302 case UO_Extension: 13303 return getPrimaryDecl(UO->getSubExpr()); 13304 default: 13305 return nullptr; 13306 } 13307 } 13308 case Stmt::ParenExprClass: 13309 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13310 case Stmt::ImplicitCastExprClass: 13311 // If the result of an implicit cast is an l-value, we care about 13312 // the sub-expression; otherwise, the result here doesn't matter. 13313 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13314 case Stmt::CXXUuidofExprClass: 13315 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13316 default: 13317 return nullptr; 13318 } 13319 } 13320 13321 namespace { 13322 enum { 13323 AO_Bit_Field = 0, 13324 AO_Vector_Element = 1, 13325 AO_Property_Expansion = 2, 13326 AO_Register_Variable = 3, 13327 AO_Matrix_Element = 4, 13328 AO_No_Error = 5 13329 }; 13330 } 13331 /// Diagnose invalid operand for address of operations. 13332 /// 13333 /// \param Type The type of operand which cannot have its address taken. 13334 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13335 Expr *E, unsigned Type) { 13336 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13337 } 13338 13339 /// CheckAddressOfOperand - The operand of & must be either a function 13340 /// designator or an lvalue designating an object. If it is an lvalue, the 13341 /// object cannot be declared with storage class register or be a bit field. 13342 /// Note: The usual conversions are *not* applied to the operand of the & 13343 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13344 /// In C++, the operand might be an overloaded function name, in which case 13345 /// we allow the '&' but retain the overloaded-function type. 13346 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13347 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13348 if (PTy->getKind() == BuiltinType::Overload) { 13349 Expr *E = OrigOp.get()->IgnoreParens(); 13350 if (!isa<OverloadExpr>(E)) { 13351 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13352 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13353 << OrigOp.get()->getSourceRange(); 13354 return QualType(); 13355 } 13356 13357 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13358 if (isa<UnresolvedMemberExpr>(Ovl)) 13359 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13360 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13361 << OrigOp.get()->getSourceRange(); 13362 return QualType(); 13363 } 13364 13365 return Context.OverloadTy; 13366 } 13367 13368 if (PTy->getKind() == BuiltinType::UnknownAny) 13369 return Context.UnknownAnyTy; 13370 13371 if (PTy->getKind() == BuiltinType::BoundMember) { 13372 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13373 << OrigOp.get()->getSourceRange(); 13374 return QualType(); 13375 } 13376 13377 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13378 if (OrigOp.isInvalid()) return QualType(); 13379 } 13380 13381 if (OrigOp.get()->isTypeDependent()) 13382 return Context.DependentTy; 13383 13384 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13385 13386 // Make sure to ignore parentheses in subsequent checks 13387 Expr *op = OrigOp.get()->IgnoreParens(); 13388 13389 // In OpenCL captures for blocks called as lambda functions 13390 // are located in the private address space. Blocks used in 13391 // enqueue_kernel can be located in a different address space 13392 // depending on a vendor implementation. Thus preventing 13393 // taking an address of the capture to avoid invalid AS casts. 13394 if (LangOpts.OpenCL) { 13395 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13396 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13397 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13398 return QualType(); 13399 } 13400 } 13401 13402 if (getLangOpts().C99) { 13403 // Implement C99-only parts of addressof rules. 13404 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13405 if (uOp->getOpcode() == UO_Deref) 13406 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13407 // (assuming the deref expression is valid). 13408 return uOp->getSubExpr()->getType(); 13409 } 13410 // Technically, there should be a check for array subscript 13411 // expressions here, but the result of one is always an lvalue anyway. 13412 } 13413 ValueDecl *dcl = getPrimaryDecl(op); 13414 13415 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13416 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13417 op->getBeginLoc())) 13418 return QualType(); 13419 13420 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13421 unsigned AddressOfError = AO_No_Error; 13422 13423 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13424 bool sfinae = (bool)isSFINAEContext(); 13425 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13426 : diag::ext_typecheck_addrof_temporary) 13427 << op->getType() << op->getSourceRange(); 13428 if (sfinae) 13429 return QualType(); 13430 // Materialize the temporary as an lvalue so that we can take its address. 13431 OrigOp = op = 13432 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13433 } else if (isa<ObjCSelectorExpr>(op)) { 13434 return Context.getPointerType(op->getType()); 13435 } else if (lval == Expr::LV_MemberFunction) { 13436 // If it's an instance method, make a member pointer. 13437 // The expression must have exactly the form &A::foo. 13438 13439 // If the underlying expression isn't a decl ref, give up. 13440 if (!isa<DeclRefExpr>(op)) { 13441 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13442 << OrigOp.get()->getSourceRange(); 13443 return QualType(); 13444 } 13445 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13446 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13447 13448 // The id-expression was parenthesized. 13449 if (OrigOp.get() != DRE) { 13450 Diag(OpLoc, diag::err_parens_pointer_member_function) 13451 << OrigOp.get()->getSourceRange(); 13452 13453 // The method was named without a qualifier. 13454 } else if (!DRE->getQualifier()) { 13455 if (MD->getParent()->getName().empty()) 13456 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13457 << op->getSourceRange(); 13458 else { 13459 SmallString<32> Str; 13460 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13461 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13462 << op->getSourceRange() 13463 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13464 } 13465 } 13466 13467 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13468 if (isa<CXXDestructorDecl>(MD)) 13469 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13470 13471 QualType MPTy = Context.getMemberPointerType( 13472 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13473 // Under the MS ABI, lock down the inheritance model now. 13474 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13475 (void)isCompleteType(OpLoc, MPTy); 13476 return MPTy; 13477 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13478 // C99 6.5.3.2p1 13479 // The operand must be either an l-value or a function designator 13480 if (!op->getType()->isFunctionType()) { 13481 // Use a special diagnostic for loads from property references. 13482 if (isa<PseudoObjectExpr>(op)) { 13483 AddressOfError = AO_Property_Expansion; 13484 } else { 13485 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13486 << op->getType() << op->getSourceRange(); 13487 return QualType(); 13488 } 13489 } 13490 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13491 // The operand cannot be a bit-field 13492 AddressOfError = AO_Bit_Field; 13493 } else if (op->getObjectKind() == OK_VectorComponent) { 13494 // The operand cannot be an element of a vector 13495 AddressOfError = AO_Vector_Element; 13496 } else if (op->getObjectKind() == OK_MatrixComponent) { 13497 // The operand cannot be an element of a matrix. 13498 AddressOfError = AO_Matrix_Element; 13499 } else if (dcl) { // C99 6.5.3.2p1 13500 // We have an lvalue with a decl. Make sure the decl is not declared 13501 // with the register storage-class specifier. 13502 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13503 // in C++ it is not error to take address of a register 13504 // variable (c++03 7.1.1P3) 13505 if (vd->getStorageClass() == SC_Register && 13506 !getLangOpts().CPlusPlus) { 13507 AddressOfError = AO_Register_Variable; 13508 } 13509 } else if (isa<MSPropertyDecl>(dcl)) { 13510 AddressOfError = AO_Property_Expansion; 13511 } else if (isa<FunctionTemplateDecl>(dcl)) { 13512 return Context.OverloadTy; 13513 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13514 // Okay: we can take the address of a field. 13515 // Could be a pointer to member, though, if there is an explicit 13516 // scope qualifier for the class. 13517 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13518 DeclContext *Ctx = dcl->getDeclContext(); 13519 if (Ctx && Ctx->isRecord()) { 13520 if (dcl->getType()->isReferenceType()) { 13521 Diag(OpLoc, 13522 diag::err_cannot_form_pointer_to_member_of_reference_type) 13523 << dcl->getDeclName() << dcl->getType(); 13524 return QualType(); 13525 } 13526 13527 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13528 Ctx = Ctx->getParent(); 13529 13530 QualType MPTy = Context.getMemberPointerType( 13531 op->getType(), 13532 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13533 // Under the MS ABI, lock down the inheritance model now. 13534 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13535 (void)isCompleteType(OpLoc, MPTy); 13536 return MPTy; 13537 } 13538 } 13539 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13540 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13541 llvm_unreachable("Unknown/unexpected decl type"); 13542 } 13543 13544 if (AddressOfError != AO_No_Error) { 13545 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13546 return QualType(); 13547 } 13548 13549 if (lval == Expr::LV_IncompleteVoidType) { 13550 // Taking the address of a void variable is technically illegal, but we 13551 // allow it in cases which are otherwise valid. 13552 // Example: "extern void x; void* y = &x;". 13553 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13554 } 13555 13556 // If the operand has type "type", the result has type "pointer to type". 13557 if (op->getType()->isObjCObjectType()) 13558 return Context.getObjCObjectPointerType(op->getType()); 13559 13560 CheckAddressOfPackedMember(op); 13561 13562 return Context.getPointerType(op->getType()); 13563 } 13564 13565 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13566 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13567 if (!DRE) 13568 return; 13569 const Decl *D = DRE->getDecl(); 13570 if (!D) 13571 return; 13572 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13573 if (!Param) 13574 return; 13575 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13576 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13577 return; 13578 if (FunctionScopeInfo *FD = S.getCurFunction()) 13579 if (!FD->ModifiedNonNullParams.count(Param)) 13580 FD->ModifiedNonNullParams.insert(Param); 13581 } 13582 13583 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13584 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13585 SourceLocation OpLoc) { 13586 if (Op->isTypeDependent()) 13587 return S.Context.DependentTy; 13588 13589 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13590 if (ConvResult.isInvalid()) 13591 return QualType(); 13592 Op = ConvResult.get(); 13593 QualType OpTy = Op->getType(); 13594 QualType Result; 13595 13596 if (isa<CXXReinterpretCastExpr>(Op)) { 13597 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13598 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13599 Op->getSourceRange()); 13600 } 13601 13602 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13603 { 13604 Result = PT->getPointeeType(); 13605 } 13606 else if (const ObjCObjectPointerType *OPT = 13607 OpTy->getAs<ObjCObjectPointerType>()) 13608 Result = OPT->getPointeeType(); 13609 else { 13610 ExprResult PR = S.CheckPlaceholderExpr(Op); 13611 if (PR.isInvalid()) return QualType(); 13612 if (PR.get() != Op) 13613 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13614 } 13615 13616 if (Result.isNull()) { 13617 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13618 << OpTy << Op->getSourceRange(); 13619 return QualType(); 13620 } 13621 13622 // Note that per both C89 and C99, indirection is always legal, even if Result 13623 // is an incomplete type or void. It would be possible to warn about 13624 // dereferencing a void pointer, but it's completely well-defined, and such a 13625 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13626 // for pointers to 'void' but is fine for any other pointer type: 13627 // 13628 // C++ [expr.unary.op]p1: 13629 // [...] the expression to which [the unary * operator] is applied shall 13630 // be a pointer to an object type, or a pointer to a function type 13631 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13632 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13633 << OpTy << Op->getSourceRange(); 13634 13635 // Dereferences are usually l-values... 13636 VK = VK_LValue; 13637 13638 // ...except that certain expressions are never l-values in C. 13639 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13640 VK = VK_RValue; 13641 13642 return Result; 13643 } 13644 13645 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13646 BinaryOperatorKind Opc; 13647 switch (Kind) { 13648 default: llvm_unreachable("Unknown binop!"); 13649 case tok::periodstar: Opc = BO_PtrMemD; break; 13650 case tok::arrowstar: Opc = BO_PtrMemI; break; 13651 case tok::star: Opc = BO_Mul; break; 13652 case tok::slash: Opc = BO_Div; break; 13653 case tok::percent: Opc = BO_Rem; break; 13654 case tok::plus: Opc = BO_Add; break; 13655 case tok::minus: Opc = BO_Sub; break; 13656 case tok::lessless: Opc = BO_Shl; break; 13657 case tok::greatergreater: Opc = BO_Shr; break; 13658 case tok::lessequal: Opc = BO_LE; break; 13659 case tok::less: Opc = BO_LT; break; 13660 case tok::greaterequal: Opc = BO_GE; break; 13661 case tok::greater: Opc = BO_GT; break; 13662 case tok::exclaimequal: Opc = BO_NE; break; 13663 case tok::equalequal: Opc = BO_EQ; break; 13664 case tok::spaceship: Opc = BO_Cmp; break; 13665 case tok::amp: Opc = BO_And; break; 13666 case tok::caret: Opc = BO_Xor; break; 13667 case tok::pipe: Opc = BO_Or; break; 13668 case tok::ampamp: Opc = BO_LAnd; break; 13669 case tok::pipepipe: Opc = BO_LOr; break; 13670 case tok::equal: Opc = BO_Assign; break; 13671 case tok::starequal: Opc = BO_MulAssign; break; 13672 case tok::slashequal: Opc = BO_DivAssign; break; 13673 case tok::percentequal: Opc = BO_RemAssign; break; 13674 case tok::plusequal: Opc = BO_AddAssign; break; 13675 case tok::minusequal: Opc = BO_SubAssign; break; 13676 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13677 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13678 case tok::ampequal: Opc = BO_AndAssign; break; 13679 case tok::caretequal: Opc = BO_XorAssign; break; 13680 case tok::pipeequal: Opc = BO_OrAssign; break; 13681 case tok::comma: Opc = BO_Comma; break; 13682 } 13683 return Opc; 13684 } 13685 13686 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13687 tok::TokenKind Kind) { 13688 UnaryOperatorKind Opc; 13689 switch (Kind) { 13690 default: llvm_unreachable("Unknown unary op!"); 13691 case tok::plusplus: Opc = UO_PreInc; break; 13692 case tok::minusminus: Opc = UO_PreDec; break; 13693 case tok::amp: Opc = UO_AddrOf; break; 13694 case tok::star: Opc = UO_Deref; break; 13695 case tok::plus: Opc = UO_Plus; break; 13696 case tok::minus: Opc = UO_Minus; break; 13697 case tok::tilde: Opc = UO_Not; break; 13698 case tok::exclaim: Opc = UO_LNot; break; 13699 case tok::kw___real: Opc = UO_Real; break; 13700 case tok::kw___imag: Opc = UO_Imag; break; 13701 case tok::kw___extension__: Opc = UO_Extension; break; 13702 } 13703 return Opc; 13704 } 13705 13706 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13707 /// This warning suppressed in the event of macro expansions. 13708 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13709 SourceLocation OpLoc, bool IsBuiltin) { 13710 if (S.inTemplateInstantiation()) 13711 return; 13712 if (S.isUnevaluatedContext()) 13713 return; 13714 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13715 return; 13716 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13717 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13718 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13719 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13720 if (!LHSDeclRef || !RHSDeclRef || 13721 LHSDeclRef->getLocation().isMacroID() || 13722 RHSDeclRef->getLocation().isMacroID()) 13723 return; 13724 const ValueDecl *LHSDecl = 13725 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13726 const ValueDecl *RHSDecl = 13727 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13728 if (LHSDecl != RHSDecl) 13729 return; 13730 if (LHSDecl->getType().isVolatileQualified()) 13731 return; 13732 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13733 if (RefTy->getPointeeType().isVolatileQualified()) 13734 return; 13735 13736 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13737 : diag::warn_self_assignment_overloaded) 13738 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13739 << RHSExpr->getSourceRange(); 13740 } 13741 13742 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13743 /// is usually indicative of introspection within the Objective-C pointer. 13744 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13745 SourceLocation OpLoc) { 13746 if (!S.getLangOpts().ObjC) 13747 return; 13748 13749 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13750 const Expr *LHS = L.get(); 13751 const Expr *RHS = R.get(); 13752 13753 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13754 ObjCPointerExpr = LHS; 13755 OtherExpr = RHS; 13756 } 13757 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13758 ObjCPointerExpr = RHS; 13759 OtherExpr = LHS; 13760 } 13761 13762 // This warning is deliberately made very specific to reduce false 13763 // positives with logic that uses '&' for hashing. This logic mainly 13764 // looks for code trying to introspect into tagged pointers, which 13765 // code should generally never do. 13766 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13767 unsigned Diag = diag::warn_objc_pointer_masking; 13768 // Determine if we are introspecting the result of performSelectorXXX. 13769 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13770 // Special case messages to -performSelector and friends, which 13771 // can return non-pointer values boxed in a pointer value. 13772 // Some clients may wish to silence warnings in this subcase. 13773 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13774 Selector S = ME->getSelector(); 13775 StringRef SelArg0 = S.getNameForSlot(0); 13776 if (SelArg0.startswith("performSelector")) 13777 Diag = diag::warn_objc_pointer_masking_performSelector; 13778 } 13779 13780 S.Diag(OpLoc, Diag) 13781 << ObjCPointerExpr->getSourceRange(); 13782 } 13783 } 13784 13785 static NamedDecl *getDeclFromExpr(Expr *E) { 13786 if (!E) 13787 return nullptr; 13788 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13789 return DRE->getDecl(); 13790 if (auto *ME = dyn_cast<MemberExpr>(E)) 13791 return ME->getMemberDecl(); 13792 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13793 return IRE->getDecl(); 13794 return nullptr; 13795 } 13796 13797 // This helper function promotes a binary operator's operands (which are of a 13798 // half vector type) to a vector of floats and then truncates the result to 13799 // a vector of either half or short. 13800 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13801 BinaryOperatorKind Opc, QualType ResultTy, 13802 ExprValueKind VK, ExprObjectKind OK, 13803 bool IsCompAssign, SourceLocation OpLoc, 13804 FPOptionsOverride FPFeatures) { 13805 auto &Context = S.getASTContext(); 13806 assert((isVector(ResultTy, Context.HalfTy) || 13807 isVector(ResultTy, Context.ShortTy)) && 13808 "Result must be a vector of half or short"); 13809 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13810 isVector(RHS.get()->getType(), Context.HalfTy) && 13811 "both operands expected to be a half vector"); 13812 13813 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13814 QualType BinOpResTy = RHS.get()->getType(); 13815 13816 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13817 // change BinOpResTy to a vector of ints. 13818 if (isVector(ResultTy, Context.ShortTy)) 13819 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13820 13821 if (IsCompAssign) 13822 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13823 ResultTy, VK, OK, OpLoc, FPFeatures, 13824 BinOpResTy, BinOpResTy); 13825 13826 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13827 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13828 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13829 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13830 } 13831 13832 static std::pair<ExprResult, ExprResult> 13833 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13834 Expr *RHSExpr) { 13835 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13836 if (!S.Context.isDependenceAllowed()) { 13837 // C cannot handle TypoExpr nodes on either side of a binop because it 13838 // doesn't handle dependent types properly, so make sure any TypoExprs have 13839 // been dealt with before checking the operands. 13840 LHS = S.CorrectDelayedTyposInExpr(LHS); 13841 RHS = S.CorrectDelayedTyposInExpr( 13842 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13843 [Opc, LHS](Expr *E) { 13844 if (Opc != BO_Assign) 13845 return ExprResult(E); 13846 // Avoid correcting the RHS to the same Expr as the LHS. 13847 Decl *D = getDeclFromExpr(E); 13848 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13849 }); 13850 } 13851 return std::make_pair(LHS, RHS); 13852 } 13853 13854 /// Returns true if conversion between vectors of halfs and vectors of floats 13855 /// is needed. 13856 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13857 Expr *E0, Expr *E1 = nullptr) { 13858 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13859 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13860 return false; 13861 13862 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13863 QualType Ty = E->IgnoreImplicit()->getType(); 13864 13865 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13866 // to vectors of floats. Although the element type of the vectors is __fp16, 13867 // the vectors shouldn't be treated as storage-only types. See the 13868 // discussion here: https://reviews.llvm.org/rG825235c140e7 13869 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13870 if (VT->getVectorKind() == VectorType::NeonVector) 13871 return false; 13872 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13873 } 13874 return false; 13875 }; 13876 13877 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13878 } 13879 13880 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13881 /// operator @p Opc at location @c TokLoc. This routine only supports 13882 /// built-in operations; ActOnBinOp handles overloaded operators. 13883 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13884 BinaryOperatorKind Opc, 13885 Expr *LHSExpr, Expr *RHSExpr) { 13886 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13887 // The syntax only allows initializer lists on the RHS of assignment, 13888 // so we don't need to worry about accepting invalid code for 13889 // non-assignment operators. 13890 // C++11 5.17p9: 13891 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13892 // of x = {} is x = T(). 13893 InitializationKind Kind = InitializationKind::CreateDirectList( 13894 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13895 InitializedEntity Entity = 13896 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13897 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13898 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13899 if (Init.isInvalid()) 13900 return Init; 13901 RHSExpr = Init.get(); 13902 } 13903 13904 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13905 QualType ResultTy; // Result type of the binary operator. 13906 // The following two variables are used for compound assignment operators 13907 QualType CompLHSTy; // Type of LHS after promotions for computation 13908 QualType CompResultTy; // Type of computation result 13909 ExprValueKind VK = VK_RValue; 13910 ExprObjectKind OK = OK_Ordinary; 13911 bool ConvertHalfVec = false; 13912 13913 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13914 if (!LHS.isUsable() || !RHS.isUsable()) 13915 return ExprError(); 13916 13917 if (getLangOpts().OpenCL) { 13918 QualType LHSTy = LHSExpr->getType(); 13919 QualType RHSTy = RHSExpr->getType(); 13920 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13921 // the ATOMIC_VAR_INIT macro. 13922 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13923 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13924 if (BO_Assign == Opc) 13925 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13926 else 13927 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13928 return ExprError(); 13929 } 13930 13931 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13932 // only with a builtin functions and therefore should be disallowed here. 13933 if (LHSTy->isImageType() || RHSTy->isImageType() || 13934 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13935 LHSTy->isPipeType() || RHSTy->isPipeType() || 13936 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13937 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13938 return ExprError(); 13939 } 13940 } 13941 13942 switch (Opc) { 13943 case BO_Assign: 13944 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13945 if (getLangOpts().CPlusPlus && 13946 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13947 VK = LHS.get()->getValueKind(); 13948 OK = LHS.get()->getObjectKind(); 13949 } 13950 if (!ResultTy.isNull()) { 13951 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13952 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13953 13954 // Avoid copying a block to the heap if the block is assigned to a local 13955 // auto variable that is declared in the same scope as the block. This 13956 // optimization is unsafe if the local variable is declared in an outer 13957 // scope. For example: 13958 // 13959 // BlockTy b; 13960 // { 13961 // b = ^{...}; 13962 // } 13963 // // It is unsafe to invoke the block here if it wasn't copied to the 13964 // // heap. 13965 // b(); 13966 13967 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13968 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13969 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13970 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13971 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13972 13973 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13974 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13975 NTCUC_Assignment, NTCUK_Copy); 13976 } 13977 RecordModifiableNonNullParam(*this, LHS.get()); 13978 break; 13979 case BO_PtrMemD: 13980 case BO_PtrMemI: 13981 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13982 Opc == BO_PtrMemI); 13983 break; 13984 case BO_Mul: 13985 case BO_Div: 13986 ConvertHalfVec = true; 13987 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13988 Opc == BO_Div); 13989 break; 13990 case BO_Rem: 13991 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13992 break; 13993 case BO_Add: 13994 ConvertHalfVec = true; 13995 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13996 break; 13997 case BO_Sub: 13998 ConvertHalfVec = true; 13999 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14000 break; 14001 case BO_Shl: 14002 case BO_Shr: 14003 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14004 break; 14005 case BO_LE: 14006 case BO_LT: 14007 case BO_GE: 14008 case BO_GT: 14009 ConvertHalfVec = true; 14010 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14011 break; 14012 case BO_EQ: 14013 case BO_NE: 14014 ConvertHalfVec = true; 14015 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14016 break; 14017 case BO_Cmp: 14018 ConvertHalfVec = true; 14019 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14020 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14021 break; 14022 case BO_And: 14023 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14024 LLVM_FALLTHROUGH; 14025 case BO_Xor: 14026 case BO_Or: 14027 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14028 break; 14029 case BO_LAnd: 14030 case BO_LOr: 14031 ConvertHalfVec = true; 14032 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14033 break; 14034 case BO_MulAssign: 14035 case BO_DivAssign: 14036 ConvertHalfVec = true; 14037 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14038 Opc == BO_DivAssign); 14039 CompLHSTy = CompResultTy; 14040 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14041 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14042 break; 14043 case BO_RemAssign: 14044 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14045 CompLHSTy = CompResultTy; 14046 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14047 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14048 break; 14049 case BO_AddAssign: 14050 ConvertHalfVec = true; 14051 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14052 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14053 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14054 break; 14055 case BO_SubAssign: 14056 ConvertHalfVec = true; 14057 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14058 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14059 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14060 break; 14061 case BO_ShlAssign: 14062 case BO_ShrAssign: 14063 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14064 CompLHSTy = CompResultTy; 14065 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14066 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14067 break; 14068 case BO_AndAssign: 14069 case BO_OrAssign: // fallthrough 14070 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14071 LLVM_FALLTHROUGH; 14072 case BO_XorAssign: 14073 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14074 CompLHSTy = CompResultTy; 14075 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14076 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14077 break; 14078 case BO_Comma: 14079 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14080 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14081 VK = RHS.get()->getValueKind(); 14082 OK = RHS.get()->getObjectKind(); 14083 } 14084 break; 14085 } 14086 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14087 return ExprError(); 14088 14089 // Some of the binary operations require promoting operands of half vector to 14090 // float vectors and truncating the result back to half vector. For now, we do 14091 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14092 // arm64). 14093 assert( 14094 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14095 isVector(LHS.get()->getType(), Context.HalfTy)) && 14096 "both sides are half vectors or neither sides are"); 14097 ConvertHalfVec = 14098 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14099 14100 // Check for array bounds violations for both sides of the BinaryOperator 14101 CheckArrayAccess(LHS.get()); 14102 CheckArrayAccess(RHS.get()); 14103 14104 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14105 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14106 &Context.Idents.get("object_setClass"), 14107 SourceLocation(), LookupOrdinaryName); 14108 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14109 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14110 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14111 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14112 "object_setClass(") 14113 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14114 ",") 14115 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14116 } 14117 else 14118 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14119 } 14120 else if (const ObjCIvarRefExpr *OIRE = 14121 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14122 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14123 14124 // Opc is not a compound assignment if CompResultTy is null. 14125 if (CompResultTy.isNull()) { 14126 if (ConvertHalfVec) 14127 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14128 OpLoc, CurFPFeatureOverrides()); 14129 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14130 VK, OK, OpLoc, CurFPFeatureOverrides()); 14131 } 14132 14133 // Handle compound assignments. 14134 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14135 OK_ObjCProperty) { 14136 VK = VK_LValue; 14137 OK = LHS.get()->getObjectKind(); 14138 } 14139 14140 // The LHS is not converted to the result type for fixed-point compound 14141 // assignment as the common type is computed on demand. Reset the CompLHSTy 14142 // to the LHS type we would have gotten after unary conversions. 14143 if (CompResultTy->isFixedPointType()) 14144 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14145 14146 if (ConvertHalfVec) 14147 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14148 OpLoc, CurFPFeatureOverrides()); 14149 14150 return CompoundAssignOperator::Create( 14151 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14152 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14153 } 14154 14155 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14156 /// operators are mixed in a way that suggests that the programmer forgot that 14157 /// comparison operators have higher precedence. The most typical example of 14158 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14159 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14160 SourceLocation OpLoc, Expr *LHSExpr, 14161 Expr *RHSExpr) { 14162 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14163 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14164 14165 // Check that one of the sides is a comparison operator and the other isn't. 14166 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14167 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14168 if (isLeftComp == isRightComp) 14169 return; 14170 14171 // Bitwise operations are sometimes used as eager logical ops. 14172 // Don't diagnose this. 14173 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14174 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14175 if (isLeftBitwise || isRightBitwise) 14176 return; 14177 14178 SourceRange DiagRange = isLeftComp 14179 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14180 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14181 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14182 SourceRange ParensRange = 14183 isLeftComp 14184 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14185 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14186 14187 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14188 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14189 SuggestParentheses(Self, OpLoc, 14190 Self.PDiag(diag::note_precedence_silence) << OpStr, 14191 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14192 SuggestParentheses(Self, OpLoc, 14193 Self.PDiag(diag::note_precedence_bitwise_first) 14194 << BinaryOperator::getOpcodeStr(Opc), 14195 ParensRange); 14196 } 14197 14198 /// It accepts a '&&' expr that is inside a '||' one. 14199 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14200 /// in parentheses. 14201 static void 14202 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14203 BinaryOperator *Bop) { 14204 assert(Bop->getOpcode() == BO_LAnd); 14205 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14206 << Bop->getSourceRange() << OpLoc; 14207 SuggestParentheses(Self, Bop->getOperatorLoc(), 14208 Self.PDiag(diag::note_precedence_silence) 14209 << Bop->getOpcodeStr(), 14210 Bop->getSourceRange()); 14211 } 14212 14213 /// Returns true if the given expression can be evaluated as a constant 14214 /// 'true'. 14215 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14216 bool Res; 14217 return !E->isValueDependent() && 14218 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14219 } 14220 14221 /// Returns true if the given expression can be evaluated as a constant 14222 /// 'false'. 14223 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14224 bool Res; 14225 return !E->isValueDependent() && 14226 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14227 } 14228 14229 /// Look for '&&' in the left hand of a '||' expr. 14230 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14231 Expr *LHSExpr, Expr *RHSExpr) { 14232 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14233 if (Bop->getOpcode() == BO_LAnd) { 14234 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14235 if (EvaluatesAsFalse(S, RHSExpr)) 14236 return; 14237 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14238 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14239 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14240 } else if (Bop->getOpcode() == BO_LOr) { 14241 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14242 // If it's "a || b && 1 || c" we didn't warn earlier for 14243 // "a || b && 1", but warn now. 14244 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14245 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14246 } 14247 } 14248 } 14249 } 14250 14251 /// Look for '&&' in the right hand of a '||' expr. 14252 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14253 Expr *LHSExpr, Expr *RHSExpr) { 14254 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14255 if (Bop->getOpcode() == BO_LAnd) { 14256 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14257 if (EvaluatesAsFalse(S, LHSExpr)) 14258 return; 14259 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14260 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14261 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14262 } 14263 } 14264 } 14265 14266 /// Look for bitwise op in the left or right hand of a bitwise op with 14267 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14268 /// the '&' expression in parentheses. 14269 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14270 SourceLocation OpLoc, Expr *SubExpr) { 14271 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14272 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14273 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14274 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14275 << Bop->getSourceRange() << OpLoc; 14276 SuggestParentheses(S, Bop->getOperatorLoc(), 14277 S.PDiag(diag::note_precedence_silence) 14278 << Bop->getOpcodeStr(), 14279 Bop->getSourceRange()); 14280 } 14281 } 14282 } 14283 14284 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14285 Expr *SubExpr, StringRef Shift) { 14286 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14287 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14288 StringRef Op = Bop->getOpcodeStr(); 14289 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14290 << Bop->getSourceRange() << OpLoc << Shift << Op; 14291 SuggestParentheses(S, Bop->getOperatorLoc(), 14292 S.PDiag(diag::note_precedence_silence) << Op, 14293 Bop->getSourceRange()); 14294 } 14295 } 14296 } 14297 14298 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14299 Expr *LHSExpr, Expr *RHSExpr) { 14300 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14301 if (!OCE) 14302 return; 14303 14304 FunctionDecl *FD = OCE->getDirectCallee(); 14305 if (!FD || !FD->isOverloadedOperator()) 14306 return; 14307 14308 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14309 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14310 return; 14311 14312 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14313 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14314 << (Kind == OO_LessLess); 14315 SuggestParentheses(S, OCE->getOperatorLoc(), 14316 S.PDiag(diag::note_precedence_silence) 14317 << (Kind == OO_LessLess ? "<<" : ">>"), 14318 OCE->getSourceRange()); 14319 SuggestParentheses( 14320 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14321 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14322 } 14323 14324 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14325 /// precedence. 14326 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14327 SourceLocation OpLoc, Expr *LHSExpr, 14328 Expr *RHSExpr){ 14329 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14330 if (BinaryOperator::isBitwiseOp(Opc)) 14331 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14332 14333 // Diagnose "arg1 & arg2 | arg3" 14334 if ((Opc == BO_Or || Opc == BO_Xor) && 14335 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14336 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14337 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14338 } 14339 14340 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14341 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14342 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14343 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14344 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14345 } 14346 14347 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14348 || Opc == BO_Shr) { 14349 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14350 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14351 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14352 } 14353 14354 // Warn on overloaded shift operators and comparisons, such as: 14355 // cout << 5 == 4; 14356 if (BinaryOperator::isComparisonOp(Opc)) 14357 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14358 } 14359 14360 // Binary Operators. 'Tok' is the token for the operator. 14361 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14362 tok::TokenKind Kind, 14363 Expr *LHSExpr, Expr *RHSExpr) { 14364 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14365 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14366 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14367 14368 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14369 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14370 14371 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14372 } 14373 14374 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14375 UnresolvedSetImpl &Functions) { 14376 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14377 if (OverOp != OO_None && OverOp != OO_Equal) 14378 LookupOverloadedOperatorName(OverOp, S, Functions); 14379 14380 // In C++20 onwards, we may have a second operator to look up. 14381 if (getLangOpts().CPlusPlus20) { 14382 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14383 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14384 } 14385 } 14386 14387 /// Build an overloaded binary operator expression in the given scope. 14388 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14389 BinaryOperatorKind Opc, 14390 Expr *LHS, Expr *RHS) { 14391 switch (Opc) { 14392 case BO_Assign: 14393 case BO_DivAssign: 14394 case BO_RemAssign: 14395 case BO_SubAssign: 14396 case BO_AndAssign: 14397 case BO_OrAssign: 14398 case BO_XorAssign: 14399 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14400 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14401 break; 14402 default: 14403 break; 14404 } 14405 14406 // Find all of the overloaded operators visible from this point. 14407 UnresolvedSet<16> Functions; 14408 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14409 14410 // Build the (potentially-overloaded, potentially-dependent) 14411 // binary operation. 14412 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14413 } 14414 14415 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14416 BinaryOperatorKind Opc, 14417 Expr *LHSExpr, Expr *RHSExpr) { 14418 ExprResult LHS, RHS; 14419 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14420 if (!LHS.isUsable() || !RHS.isUsable()) 14421 return ExprError(); 14422 LHSExpr = LHS.get(); 14423 RHSExpr = RHS.get(); 14424 14425 // We want to end up calling one of checkPseudoObjectAssignment 14426 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14427 // both expressions are overloadable or either is type-dependent), 14428 // or CreateBuiltinBinOp (in any other case). We also want to get 14429 // any placeholder types out of the way. 14430 14431 // Handle pseudo-objects in the LHS. 14432 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14433 // Assignments with a pseudo-object l-value need special analysis. 14434 if (pty->getKind() == BuiltinType::PseudoObject && 14435 BinaryOperator::isAssignmentOp(Opc)) 14436 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14437 14438 // Don't resolve overloads if the other type is overloadable. 14439 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14440 // We can't actually test that if we still have a placeholder, 14441 // though. Fortunately, none of the exceptions we see in that 14442 // code below are valid when the LHS is an overload set. Note 14443 // that an overload set can be dependently-typed, but it never 14444 // instantiates to having an overloadable type. 14445 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14446 if (resolvedRHS.isInvalid()) return ExprError(); 14447 RHSExpr = resolvedRHS.get(); 14448 14449 if (RHSExpr->isTypeDependent() || 14450 RHSExpr->getType()->isOverloadableType()) 14451 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14452 } 14453 14454 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14455 // template, diagnose the missing 'template' keyword instead of diagnosing 14456 // an invalid use of a bound member function. 14457 // 14458 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14459 // to C++1z [over.over]/1.4, but we already checked for that case above. 14460 if (Opc == BO_LT && inTemplateInstantiation() && 14461 (pty->getKind() == BuiltinType::BoundMember || 14462 pty->getKind() == BuiltinType::Overload)) { 14463 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14464 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14465 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14466 return isa<FunctionTemplateDecl>(ND); 14467 })) { 14468 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14469 : OE->getNameLoc(), 14470 diag::err_template_kw_missing) 14471 << OE->getName().getAsString() << ""; 14472 return ExprError(); 14473 } 14474 } 14475 14476 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14477 if (LHS.isInvalid()) return ExprError(); 14478 LHSExpr = LHS.get(); 14479 } 14480 14481 // Handle pseudo-objects in the RHS. 14482 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14483 // An overload in the RHS can potentially be resolved by the type 14484 // being assigned to. 14485 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14486 if (getLangOpts().CPlusPlus && 14487 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14488 LHSExpr->getType()->isOverloadableType())) 14489 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14490 14491 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14492 } 14493 14494 // Don't resolve overloads if the other type is overloadable. 14495 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14496 LHSExpr->getType()->isOverloadableType()) 14497 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14498 14499 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14500 if (!resolvedRHS.isUsable()) return ExprError(); 14501 RHSExpr = resolvedRHS.get(); 14502 } 14503 14504 if (getLangOpts().CPlusPlus) { 14505 // If either expression is type-dependent, always build an 14506 // overloaded op. 14507 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14508 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14509 14510 // Otherwise, build an overloaded op if either expression has an 14511 // overloadable type. 14512 if (LHSExpr->getType()->isOverloadableType() || 14513 RHSExpr->getType()->isOverloadableType()) 14514 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14515 } 14516 14517 if (getLangOpts().RecoveryAST && 14518 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14519 assert(!getLangOpts().CPlusPlus); 14520 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14521 "Should only occur in error-recovery path."); 14522 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14523 // C [6.15.16] p3: 14524 // An assignment expression has the value of the left operand after the 14525 // assignment, but is not an lvalue. 14526 return CompoundAssignOperator::Create( 14527 Context, LHSExpr, RHSExpr, Opc, 14528 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14529 OpLoc, CurFPFeatureOverrides()); 14530 QualType ResultType; 14531 switch (Opc) { 14532 case BO_Assign: 14533 ResultType = LHSExpr->getType().getUnqualifiedType(); 14534 break; 14535 case BO_LT: 14536 case BO_GT: 14537 case BO_LE: 14538 case BO_GE: 14539 case BO_EQ: 14540 case BO_NE: 14541 case BO_LAnd: 14542 case BO_LOr: 14543 // These operators have a fixed result type regardless of operands. 14544 ResultType = Context.IntTy; 14545 break; 14546 case BO_Comma: 14547 ResultType = RHSExpr->getType(); 14548 break; 14549 default: 14550 ResultType = Context.DependentTy; 14551 break; 14552 } 14553 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14554 VK_RValue, OK_Ordinary, OpLoc, 14555 CurFPFeatureOverrides()); 14556 } 14557 14558 // Build a built-in binary operation. 14559 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14560 } 14561 14562 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14563 if (T.isNull() || T->isDependentType()) 14564 return false; 14565 14566 if (!T->isPromotableIntegerType()) 14567 return true; 14568 14569 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14570 } 14571 14572 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14573 UnaryOperatorKind Opc, 14574 Expr *InputExpr) { 14575 ExprResult Input = InputExpr; 14576 ExprValueKind VK = VK_RValue; 14577 ExprObjectKind OK = OK_Ordinary; 14578 QualType resultType; 14579 bool CanOverflow = false; 14580 14581 bool ConvertHalfVec = false; 14582 if (getLangOpts().OpenCL) { 14583 QualType Ty = InputExpr->getType(); 14584 // The only legal unary operation for atomics is '&'. 14585 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14586 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14587 // only with a builtin functions and therefore should be disallowed here. 14588 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14589 || Ty->isBlockPointerType())) { 14590 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14591 << InputExpr->getType() 14592 << Input.get()->getSourceRange()); 14593 } 14594 } 14595 14596 switch (Opc) { 14597 case UO_PreInc: 14598 case UO_PreDec: 14599 case UO_PostInc: 14600 case UO_PostDec: 14601 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14602 OpLoc, 14603 Opc == UO_PreInc || 14604 Opc == UO_PostInc, 14605 Opc == UO_PreInc || 14606 Opc == UO_PreDec); 14607 CanOverflow = isOverflowingIntegerType(Context, resultType); 14608 break; 14609 case UO_AddrOf: 14610 resultType = CheckAddressOfOperand(Input, OpLoc); 14611 CheckAddressOfNoDeref(InputExpr); 14612 RecordModifiableNonNullParam(*this, InputExpr); 14613 break; 14614 case UO_Deref: { 14615 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14616 if (Input.isInvalid()) return ExprError(); 14617 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14618 break; 14619 } 14620 case UO_Plus: 14621 case UO_Minus: 14622 CanOverflow = Opc == UO_Minus && 14623 isOverflowingIntegerType(Context, Input.get()->getType()); 14624 Input = UsualUnaryConversions(Input.get()); 14625 if (Input.isInvalid()) return ExprError(); 14626 // Unary plus and minus require promoting an operand of half vector to a 14627 // float vector and truncating the result back to a half vector. For now, we 14628 // do this only when HalfArgsAndReturns is set (that is, when the target is 14629 // arm or arm64). 14630 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14631 14632 // If the operand is a half vector, promote it to a float vector. 14633 if (ConvertHalfVec) 14634 Input = convertVector(Input.get(), Context.FloatTy, *this); 14635 resultType = Input.get()->getType(); 14636 if (resultType->isDependentType()) 14637 break; 14638 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14639 break; 14640 else if (resultType->isVectorType() && 14641 // The z vector extensions don't allow + or - with bool vectors. 14642 (!Context.getLangOpts().ZVector || 14643 resultType->castAs<VectorType>()->getVectorKind() != 14644 VectorType::AltiVecBool)) 14645 break; 14646 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14647 Opc == UO_Plus && 14648 resultType->isPointerType()) 14649 break; 14650 14651 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14652 << resultType << Input.get()->getSourceRange()); 14653 14654 case UO_Not: // bitwise complement 14655 Input = UsualUnaryConversions(Input.get()); 14656 if (Input.isInvalid()) 14657 return ExprError(); 14658 resultType = Input.get()->getType(); 14659 if (resultType->isDependentType()) 14660 break; 14661 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14662 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14663 // C99 does not support '~' for complex conjugation. 14664 Diag(OpLoc, diag::ext_integer_complement_complex) 14665 << resultType << Input.get()->getSourceRange(); 14666 else if (resultType->hasIntegerRepresentation()) 14667 break; 14668 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14669 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14670 // on vector float types. 14671 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14672 if (!T->isIntegerType()) 14673 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14674 << resultType << Input.get()->getSourceRange()); 14675 } else { 14676 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14677 << resultType << Input.get()->getSourceRange()); 14678 } 14679 break; 14680 14681 case UO_LNot: // logical negation 14682 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14683 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14684 if (Input.isInvalid()) return ExprError(); 14685 resultType = Input.get()->getType(); 14686 14687 // Though we still have to promote half FP to float... 14688 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14689 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14690 resultType = Context.FloatTy; 14691 } 14692 14693 if (resultType->isDependentType()) 14694 break; 14695 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14696 // C99 6.5.3.3p1: ok, fallthrough; 14697 if (Context.getLangOpts().CPlusPlus) { 14698 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14699 // operand contextually converted to bool. 14700 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14701 ScalarTypeToBooleanCastKind(resultType)); 14702 } else if (Context.getLangOpts().OpenCL && 14703 Context.getLangOpts().OpenCLVersion < 120) { 14704 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14705 // operate on scalar float types. 14706 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14707 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14708 << resultType << Input.get()->getSourceRange()); 14709 } 14710 } else if (resultType->isExtVectorType()) { 14711 if (Context.getLangOpts().OpenCL && 14712 Context.getLangOpts().OpenCLVersion < 120 && 14713 !Context.getLangOpts().OpenCLCPlusPlus) { 14714 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14715 // operate on vector float types. 14716 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14717 if (!T->isIntegerType()) 14718 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14719 << resultType << Input.get()->getSourceRange()); 14720 } 14721 // Vector logical not returns the signed variant of the operand type. 14722 resultType = GetSignedVectorType(resultType); 14723 break; 14724 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14725 const VectorType *VTy = resultType->castAs<VectorType>(); 14726 if (VTy->getVectorKind() != VectorType::GenericVector) 14727 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14728 << resultType << Input.get()->getSourceRange()); 14729 14730 // Vector logical not returns the signed variant of the operand type. 14731 resultType = GetSignedVectorType(resultType); 14732 break; 14733 } else { 14734 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14735 << resultType << Input.get()->getSourceRange()); 14736 } 14737 14738 // LNot always has type int. C99 6.5.3.3p5. 14739 // In C++, it's bool. C++ 5.3.1p8 14740 resultType = Context.getLogicalOperationType(); 14741 break; 14742 case UO_Real: 14743 case UO_Imag: 14744 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14745 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14746 // complex l-values to ordinary l-values and all other values to r-values. 14747 if (Input.isInvalid()) return ExprError(); 14748 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14749 if (Input.get()->getValueKind() != VK_RValue && 14750 Input.get()->getObjectKind() == OK_Ordinary) 14751 VK = Input.get()->getValueKind(); 14752 } else if (!getLangOpts().CPlusPlus) { 14753 // In C, a volatile scalar is read by __imag. In C++, it is not. 14754 Input = DefaultLvalueConversion(Input.get()); 14755 } 14756 break; 14757 case UO_Extension: 14758 resultType = Input.get()->getType(); 14759 VK = Input.get()->getValueKind(); 14760 OK = Input.get()->getObjectKind(); 14761 break; 14762 case UO_Coawait: 14763 // It's unnecessary to represent the pass-through operator co_await in the 14764 // AST; just return the input expression instead. 14765 assert(!Input.get()->getType()->isDependentType() && 14766 "the co_await expression must be non-dependant before " 14767 "building operator co_await"); 14768 return Input; 14769 } 14770 if (resultType.isNull() || Input.isInvalid()) 14771 return ExprError(); 14772 14773 // Check for array bounds violations in the operand of the UnaryOperator, 14774 // except for the '*' and '&' operators that have to be handled specially 14775 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14776 // that are explicitly defined as valid by the standard). 14777 if (Opc != UO_AddrOf && Opc != UO_Deref) 14778 CheckArrayAccess(Input.get()); 14779 14780 auto *UO = 14781 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14782 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14783 14784 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14785 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14786 !isUnevaluatedContext()) 14787 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14788 14789 // Convert the result back to a half vector. 14790 if (ConvertHalfVec) 14791 return convertVector(UO, Context.HalfTy, *this); 14792 return UO; 14793 } 14794 14795 /// Determine whether the given expression is a qualified member 14796 /// access expression, of a form that could be turned into a pointer to member 14797 /// with the address-of operator. 14798 bool Sema::isQualifiedMemberAccess(Expr *E) { 14799 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14800 if (!DRE->getQualifier()) 14801 return false; 14802 14803 ValueDecl *VD = DRE->getDecl(); 14804 if (!VD->isCXXClassMember()) 14805 return false; 14806 14807 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14808 return true; 14809 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14810 return Method->isInstance(); 14811 14812 return false; 14813 } 14814 14815 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14816 if (!ULE->getQualifier()) 14817 return false; 14818 14819 for (NamedDecl *D : ULE->decls()) { 14820 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14821 if (Method->isInstance()) 14822 return true; 14823 } else { 14824 // Overload set does not contain methods. 14825 break; 14826 } 14827 } 14828 14829 return false; 14830 } 14831 14832 return false; 14833 } 14834 14835 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14836 UnaryOperatorKind Opc, Expr *Input) { 14837 // First things first: handle placeholders so that the 14838 // overloaded-operator check considers the right type. 14839 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14840 // Increment and decrement of pseudo-object references. 14841 if (pty->getKind() == BuiltinType::PseudoObject && 14842 UnaryOperator::isIncrementDecrementOp(Opc)) 14843 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14844 14845 // extension is always a builtin operator. 14846 if (Opc == UO_Extension) 14847 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14848 14849 // & gets special logic for several kinds of placeholder. 14850 // The builtin code knows what to do. 14851 if (Opc == UO_AddrOf && 14852 (pty->getKind() == BuiltinType::Overload || 14853 pty->getKind() == BuiltinType::UnknownAny || 14854 pty->getKind() == BuiltinType::BoundMember)) 14855 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14856 14857 // Anything else needs to be handled now. 14858 ExprResult Result = CheckPlaceholderExpr(Input); 14859 if (Result.isInvalid()) return ExprError(); 14860 Input = Result.get(); 14861 } 14862 14863 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14864 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14865 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14866 // Find all of the overloaded operators visible from this point. 14867 UnresolvedSet<16> Functions; 14868 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14869 if (S && OverOp != OO_None) 14870 LookupOverloadedOperatorName(OverOp, S, Functions); 14871 14872 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14873 } 14874 14875 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14876 } 14877 14878 // Unary Operators. 'Tok' is the token for the operator. 14879 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14880 tok::TokenKind Op, Expr *Input) { 14881 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14882 } 14883 14884 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14885 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14886 LabelDecl *TheDecl) { 14887 TheDecl->markUsed(Context); 14888 // Create the AST node. The address of a label always has type 'void*'. 14889 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14890 Context.getPointerType(Context.VoidTy)); 14891 } 14892 14893 void Sema::ActOnStartStmtExpr() { 14894 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14895 } 14896 14897 void Sema::ActOnStmtExprError() { 14898 // Note that function is also called by TreeTransform when leaving a 14899 // StmtExpr scope without rebuilding anything. 14900 14901 DiscardCleanupsInEvaluationContext(); 14902 PopExpressionEvaluationContext(); 14903 } 14904 14905 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14906 SourceLocation RPLoc) { 14907 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14908 } 14909 14910 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14911 SourceLocation RPLoc, unsigned TemplateDepth) { 14912 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14913 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14914 14915 if (hasAnyUnrecoverableErrorsInThisFunction()) 14916 DiscardCleanupsInEvaluationContext(); 14917 assert(!Cleanup.exprNeedsCleanups() && 14918 "cleanups within StmtExpr not correctly bound!"); 14919 PopExpressionEvaluationContext(); 14920 14921 // FIXME: there are a variety of strange constraints to enforce here, for 14922 // example, it is not possible to goto into a stmt expression apparently. 14923 // More semantic analysis is needed. 14924 14925 // If there are sub-stmts in the compound stmt, take the type of the last one 14926 // as the type of the stmtexpr. 14927 QualType Ty = Context.VoidTy; 14928 bool StmtExprMayBindToTemp = false; 14929 if (!Compound->body_empty()) { 14930 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14931 if (const auto *LastStmt = 14932 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14933 if (const Expr *Value = LastStmt->getExprStmt()) { 14934 StmtExprMayBindToTemp = true; 14935 Ty = Value->getType(); 14936 } 14937 } 14938 } 14939 14940 // FIXME: Check that expression type is complete/non-abstract; statement 14941 // expressions are not lvalues. 14942 Expr *ResStmtExpr = 14943 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14944 if (StmtExprMayBindToTemp) 14945 return MaybeBindToTemporary(ResStmtExpr); 14946 return ResStmtExpr; 14947 } 14948 14949 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14950 if (ER.isInvalid()) 14951 return ExprError(); 14952 14953 // Do function/array conversion on the last expression, but not 14954 // lvalue-to-rvalue. However, initialize an unqualified type. 14955 ER = DefaultFunctionArrayConversion(ER.get()); 14956 if (ER.isInvalid()) 14957 return ExprError(); 14958 Expr *E = ER.get(); 14959 14960 if (E->isTypeDependent()) 14961 return E; 14962 14963 // In ARC, if the final expression ends in a consume, splice 14964 // the consume out and bind it later. In the alternate case 14965 // (when dealing with a retainable type), the result 14966 // initialization will create a produce. In both cases the 14967 // result will be +1, and we'll need to balance that out with 14968 // a bind. 14969 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14970 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14971 return Cast->getSubExpr(); 14972 14973 // FIXME: Provide a better location for the initialization. 14974 return PerformCopyInitialization( 14975 InitializedEntity::InitializeStmtExprResult( 14976 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14977 SourceLocation(), E); 14978 } 14979 14980 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14981 TypeSourceInfo *TInfo, 14982 ArrayRef<OffsetOfComponent> Components, 14983 SourceLocation RParenLoc) { 14984 QualType ArgTy = TInfo->getType(); 14985 bool Dependent = ArgTy->isDependentType(); 14986 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14987 14988 // We must have at least one component that refers to the type, and the first 14989 // one is known to be a field designator. Verify that the ArgTy represents 14990 // a struct/union/class. 14991 if (!Dependent && !ArgTy->isRecordType()) 14992 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14993 << ArgTy << TypeRange); 14994 14995 // Type must be complete per C99 7.17p3 because a declaring a variable 14996 // with an incomplete type would be ill-formed. 14997 if (!Dependent 14998 && RequireCompleteType(BuiltinLoc, ArgTy, 14999 diag::err_offsetof_incomplete_type, TypeRange)) 15000 return ExprError(); 15001 15002 bool DidWarnAboutNonPOD = false; 15003 QualType CurrentType = ArgTy; 15004 SmallVector<OffsetOfNode, 4> Comps; 15005 SmallVector<Expr*, 4> Exprs; 15006 for (const OffsetOfComponent &OC : Components) { 15007 if (OC.isBrackets) { 15008 // Offset of an array sub-field. TODO: Should we allow vector elements? 15009 if (!CurrentType->isDependentType()) { 15010 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15011 if(!AT) 15012 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15013 << CurrentType); 15014 CurrentType = AT->getElementType(); 15015 } else 15016 CurrentType = Context.DependentTy; 15017 15018 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15019 if (IdxRval.isInvalid()) 15020 return ExprError(); 15021 Expr *Idx = IdxRval.get(); 15022 15023 // The expression must be an integral expression. 15024 // FIXME: An integral constant expression? 15025 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15026 !Idx->getType()->isIntegerType()) 15027 return ExprError( 15028 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15029 << Idx->getSourceRange()); 15030 15031 // Record this array index. 15032 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15033 Exprs.push_back(Idx); 15034 continue; 15035 } 15036 15037 // Offset of a field. 15038 if (CurrentType->isDependentType()) { 15039 // We have the offset of a field, but we can't look into the dependent 15040 // type. Just record the identifier of the field. 15041 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15042 CurrentType = Context.DependentTy; 15043 continue; 15044 } 15045 15046 // We need to have a complete type to look into. 15047 if (RequireCompleteType(OC.LocStart, CurrentType, 15048 diag::err_offsetof_incomplete_type)) 15049 return ExprError(); 15050 15051 // Look for the designated field. 15052 const RecordType *RC = CurrentType->getAs<RecordType>(); 15053 if (!RC) 15054 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15055 << CurrentType); 15056 RecordDecl *RD = RC->getDecl(); 15057 15058 // C++ [lib.support.types]p5: 15059 // The macro offsetof accepts a restricted set of type arguments in this 15060 // International Standard. type shall be a POD structure or a POD union 15061 // (clause 9). 15062 // C++11 [support.types]p4: 15063 // If type is not a standard-layout class (Clause 9), the results are 15064 // undefined. 15065 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15066 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15067 unsigned DiagID = 15068 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15069 : diag::ext_offsetof_non_pod_type; 15070 15071 if (!IsSafe && !DidWarnAboutNonPOD && 15072 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15073 PDiag(DiagID) 15074 << SourceRange(Components[0].LocStart, OC.LocEnd) 15075 << CurrentType)) 15076 DidWarnAboutNonPOD = true; 15077 } 15078 15079 // Look for the field. 15080 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15081 LookupQualifiedName(R, RD); 15082 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15083 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15084 if (!MemberDecl) { 15085 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15086 MemberDecl = IndirectMemberDecl->getAnonField(); 15087 } 15088 15089 if (!MemberDecl) 15090 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15091 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15092 OC.LocEnd)); 15093 15094 // C99 7.17p3: 15095 // (If the specified member is a bit-field, the behavior is undefined.) 15096 // 15097 // We diagnose this as an error. 15098 if (MemberDecl->isBitField()) { 15099 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15100 << MemberDecl->getDeclName() 15101 << SourceRange(BuiltinLoc, RParenLoc); 15102 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15103 return ExprError(); 15104 } 15105 15106 RecordDecl *Parent = MemberDecl->getParent(); 15107 if (IndirectMemberDecl) 15108 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15109 15110 // If the member was found in a base class, introduce OffsetOfNodes for 15111 // the base class indirections. 15112 CXXBasePaths Paths; 15113 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15114 Paths)) { 15115 if (Paths.getDetectedVirtual()) { 15116 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15117 << MemberDecl->getDeclName() 15118 << SourceRange(BuiltinLoc, RParenLoc); 15119 return ExprError(); 15120 } 15121 15122 CXXBasePath &Path = Paths.front(); 15123 for (const CXXBasePathElement &B : Path) 15124 Comps.push_back(OffsetOfNode(B.Base)); 15125 } 15126 15127 if (IndirectMemberDecl) { 15128 for (auto *FI : IndirectMemberDecl->chain()) { 15129 assert(isa<FieldDecl>(FI)); 15130 Comps.push_back(OffsetOfNode(OC.LocStart, 15131 cast<FieldDecl>(FI), OC.LocEnd)); 15132 } 15133 } else 15134 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15135 15136 CurrentType = MemberDecl->getType().getNonReferenceType(); 15137 } 15138 15139 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15140 Comps, Exprs, RParenLoc); 15141 } 15142 15143 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15144 SourceLocation BuiltinLoc, 15145 SourceLocation TypeLoc, 15146 ParsedType ParsedArgTy, 15147 ArrayRef<OffsetOfComponent> Components, 15148 SourceLocation RParenLoc) { 15149 15150 TypeSourceInfo *ArgTInfo; 15151 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15152 if (ArgTy.isNull()) 15153 return ExprError(); 15154 15155 if (!ArgTInfo) 15156 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15157 15158 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15159 } 15160 15161 15162 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15163 Expr *CondExpr, 15164 Expr *LHSExpr, Expr *RHSExpr, 15165 SourceLocation RPLoc) { 15166 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15167 15168 ExprValueKind VK = VK_RValue; 15169 ExprObjectKind OK = OK_Ordinary; 15170 QualType resType; 15171 bool CondIsTrue = false; 15172 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15173 resType = Context.DependentTy; 15174 } else { 15175 // The conditional expression is required to be a constant expression. 15176 llvm::APSInt condEval(32); 15177 ExprResult CondICE = VerifyIntegerConstantExpression( 15178 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15179 if (CondICE.isInvalid()) 15180 return ExprError(); 15181 CondExpr = CondICE.get(); 15182 CondIsTrue = condEval.getZExtValue(); 15183 15184 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15185 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15186 15187 resType = ActiveExpr->getType(); 15188 VK = ActiveExpr->getValueKind(); 15189 OK = ActiveExpr->getObjectKind(); 15190 } 15191 15192 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15193 resType, VK, OK, RPLoc, CondIsTrue); 15194 } 15195 15196 //===----------------------------------------------------------------------===// 15197 // Clang Extensions. 15198 //===----------------------------------------------------------------------===// 15199 15200 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15201 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15202 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15203 15204 if (LangOpts.CPlusPlus) { 15205 MangleNumberingContext *MCtx; 15206 Decl *ManglingContextDecl; 15207 std::tie(MCtx, ManglingContextDecl) = 15208 getCurrentMangleNumberContext(Block->getDeclContext()); 15209 if (MCtx) { 15210 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15211 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15212 } 15213 } 15214 15215 PushBlockScope(CurScope, Block); 15216 CurContext->addDecl(Block); 15217 if (CurScope) 15218 PushDeclContext(CurScope, Block); 15219 else 15220 CurContext = Block; 15221 15222 getCurBlock()->HasImplicitReturnType = true; 15223 15224 // Enter a new evaluation context to insulate the block from any 15225 // cleanups from the enclosing full-expression. 15226 PushExpressionEvaluationContext( 15227 ExpressionEvaluationContext::PotentiallyEvaluated); 15228 } 15229 15230 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15231 Scope *CurScope) { 15232 assert(ParamInfo.getIdentifier() == nullptr && 15233 "block-id should have no identifier!"); 15234 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15235 BlockScopeInfo *CurBlock = getCurBlock(); 15236 15237 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15238 QualType T = Sig->getType(); 15239 15240 // FIXME: We should allow unexpanded parameter packs here, but that would, 15241 // in turn, make the block expression contain unexpanded parameter packs. 15242 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15243 // Drop the parameters. 15244 FunctionProtoType::ExtProtoInfo EPI; 15245 EPI.HasTrailingReturn = false; 15246 EPI.TypeQuals.addConst(); 15247 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15248 Sig = Context.getTrivialTypeSourceInfo(T); 15249 } 15250 15251 // GetTypeForDeclarator always produces a function type for a block 15252 // literal signature. Furthermore, it is always a FunctionProtoType 15253 // unless the function was written with a typedef. 15254 assert(T->isFunctionType() && 15255 "GetTypeForDeclarator made a non-function block signature"); 15256 15257 // Look for an explicit signature in that function type. 15258 FunctionProtoTypeLoc ExplicitSignature; 15259 15260 if ((ExplicitSignature = Sig->getTypeLoc() 15261 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15262 15263 // Check whether that explicit signature was synthesized by 15264 // GetTypeForDeclarator. If so, don't save that as part of the 15265 // written signature. 15266 if (ExplicitSignature.getLocalRangeBegin() == 15267 ExplicitSignature.getLocalRangeEnd()) { 15268 // This would be much cheaper if we stored TypeLocs instead of 15269 // TypeSourceInfos. 15270 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15271 unsigned Size = Result.getFullDataSize(); 15272 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15273 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15274 15275 ExplicitSignature = FunctionProtoTypeLoc(); 15276 } 15277 } 15278 15279 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15280 CurBlock->FunctionType = T; 15281 15282 const auto *Fn = T->castAs<FunctionType>(); 15283 QualType RetTy = Fn->getReturnType(); 15284 bool isVariadic = 15285 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15286 15287 CurBlock->TheDecl->setIsVariadic(isVariadic); 15288 15289 // Context.DependentTy is used as a placeholder for a missing block 15290 // return type. TODO: what should we do with declarators like: 15291 // ^ * { ... } 15292 // If the answer is "apply template argument deduction".... 15293 if (RetTy != Context.DependentTy) { 15294 CurBlock->ReturnType = RetTy; 15295 CurBlock->TheDecl->setBlockMissingReturnType(false); 15296 CurBlock->HasImplicitReturnType = false; 15297 } 15298 15299 // Push block parameters from the declarator if we had them. 15300 SmallVector<ParmVarDecl*, 8> Params; 15301 if (ExplicitSignature) { 15302 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15303 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15304 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15305 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15306 // Diagnose this as an extension in C17 and earlier. 15307 if (!getLangOpts().C2x) 15308 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15309 } 15310 Params.push_back(Param); 15311 } 15312 15313 // Fake up parameter variables if we have a typedef, like 15314 // ^ fntype { ... } 15315 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15316 for (const auto &I : Fn->param_types()) { 15317 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15318 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15319 Params.push_back(Param); 15320 } 15321 } 15322 15323 // Set the parameters on the block decl. 15324 if (!Params.empty()) { 15325 CurBlock->TheDecl->setParams(Params); 15326 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15327 /*CheckParameterNames=*/false); 15328 } 15329 15330 // Finally we can process decl attributes. 15331 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15332 15333 // Put the parameter variables in scope. 15334 for (auto AI : CurBlock->TheDecl->parameters()) { 15335 AI->setOwningFunction(CurBlock->TheDecl); 15336 15337 // If this has an identifier, add it to the scope stack. 15338 if (AI->getIdentifier()) { 15339 CheckShadow(CurBlock->TheScope, AI); 15340 15341 PushOnScopeChains(AI, CurBlock->TheScope); 15342 } 15343 } 15344 } 15345 15346 /// ActOnBlockError - If there is an error parsing a block, this callback 15347 /// is invoked to pop the information about the block from the action impl. 15348 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15349 // Leave the expression-evaluation context. 15350 DiscardCleanupsInEvaluationContext(); 15351 PopExpressionEvaluationContext(); 15352 15353 // Pop off CurBlock, handle nested blocks. 15354 PopDeclContext(); 15355 PopFunctionScopeInfo(); 15356 } 15357 15358 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15359 /// literal was successfully completed. ^(int x){...} 15360 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15361 Stmt *Body, Scope *CurScope) { 15362 // If blocks are disabled, emit an error. 15363 if (!LangOpts.Blocks) 15364 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15365 15366 // Leave the expression-evaluation context. 15367 if (hasAnyUnrecoverableErrorsInThisFunction()) 15368 DiscardCleanupsInEvaluationContext(); 15369 assert(!Cleanup.exprNeedsCleanups() && 15370 "cleanups within block not correctly bound!"); 15371 PopExpressionEvaluationContext(); 15372 15373 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15374 BlockDecl *BD = BSI->TheDecl; 15375 15376 if (BSI->HasImplicitReturnType) 15377 deduceClosureReturnType(*BSI); 15378 15379 QualType RetTy = Context.VoidTy; 15380 if (!BSI->ReturnType.isNull()) 15381 RetTy = BSI->ReturnType; 15382 15383 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15384 QualType BlockTy; 15385 15386 // If the user wrote a function type in some form, try to use that. 15387 if (!BSI->FunctionType.isNull()) { 15388 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15389 15390 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15391 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15392 15393 // Turn protoless block types into nullary block types. 15394 if (isa<FunctionNoProtoType>(FTy)) { 15395 FunctionProtoType::ExtProtoInfo EPI; 15396 EPI.ExtInfo = Ext; 15397 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15398 15399 // Otherwise, if we don't need to change anything about the function type, 15400 // preserve its sugar structure. 15401 } else if (FTy->getReturnType() == RetTy && 15402 (!NoReturn || FTy->getNoReturnAttr())) { 15403 BlockTy = BSI->FunctionType; 15404 15405 // Otherwise, make the minimal modifications to the function type. 15406 } else { 15407 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15408 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15409 EPI.TypeQuals = Qualifiers(); 15410 EPI.ExtInfo = Ext; 15411 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15412 } 15413 15414 // If we don't have a function type, just build one from nothing. 15415 } else { 15416 FunctionProtoType::ExtProtoInfo EPI; 15417 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15418 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15419 } 15420 15421 DiagnoseUnusedParameters(BD->parameters()); 15422 BlockTy = Context.getBlockPointerType(BlockTy); 15423 15424 // If needed, diagnose invalid gotos and switches in the block. 15425 if (getCurFunction()->NeedsScopeChecking() && 15426 !PP.isCodeCompletionEnabled()) 15427 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15428 15429 BD->setBody(cast<CompoundStmt>(Body)); 15430 15431 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15432 DiagnoseUnguardedAvailabilityViolations(BD); 15433 15434 // Try to apply the named return value optimization. We have to check again 15435 // if we can do this, though, because blocks keep return statements around 15436 // to deduce an implicit return type. 15437 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15438 !BD->isDependentContext()) 15439 computeNRVO(Body, BSI); 15440 15441 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15442 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15443 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15444 NTCUK_Destruct|NTCUK_Copy); 15445 15446 PopDeclContext(); 15447 15448 // Set the captured variables on the block. 15449 SmallVector<BlockDecl::Capture, 4> Captures; 15450 for (Capture &Cap : BSI->Captures) { 15451 if (Cap.isInvalid() || Cap.isThisCapture()) 15452 continue; 15453 15454 VarDecl *Var = Cap.getVariable(); 15455 Expr *CopyExpr = nullptr; 15456 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15457 if (const RecordType *Record = 15458 Cap.getCaptureType()->getAs<RecordType>()) { 15459 // The capture logic needs the destructor, so make sure we mark it. 15460 // Usually this is unnecessary because most local variables have 15461 // their destructors marked at declaration time, but parameters are 15462 // an exception because it's technically only the call site that 15463 // actually requires the destructor. 15464 if (isa<ParmVarDecl>(Var)) 15465 FinalizeVarWithDestructor(Var, Record); 15466 15467 // Enter a separate potentially-evaluated context while building block 15468 // initializers to isolate their cleanups from those of the block 15469 // itself. 15470 // FIXME: Is this appropriate even when the block itself occurs in an 15471 // unevaluated operand? 15472 EnterExpressionEvaluationContext EvalContext( 15473 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15474 15475 SourceLocation Loc = Cap.getLocation(); 15476 15477 ExprResult Result = BuildDeclarationNameExpr( 15478 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15479 15480 // According to the blocks spec, the capture of a variable from 15481 // the stack requires a const copy constructor. This is not true 15482 // of the copy/move done to move a __block variable to the heap. 15483 if (!Result.isInvalid() && 15484 !Result.get()->getType().isConstQualified()) { 15485 Result = ImpCastExprToType(Result.get(), 15486 Result.get()->getType().withConst(), 15487 CK_NoOp, VK_LValue); 15488 } 15489 15490 if (!Result.isInvalid()) { 15491 Result = PerformCopyInitialization( 15492 InitializedEntity::InitializeBlock(Var->getLocation(), 15493 Cap.getCaptureType(), false), 15494 Loc, Result.get()); 15495 } 15496 15497 // Build a full-expression copy expression if initialization 15498 // succeeded and used a non-trivial constructor. Recover from 15499 // errors by pretending that the copy isn't necessary. 15500 if (!Result.isInvalid() && 15501 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15502 ->isTrivial()) { 15503 Result = MaybeCreateExprWithCleanups(Result); 15504 CopyExpr = Result.get(); 15505 } 15506 } 15507 } 15508 15509 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15510 CopyExpr); 15511 Captures.push_back(NewCap); 15512 } 15513 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15514 15515 // Pop the block scope now but keep it alive to the end of this function. 15516 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15517 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15518 15519 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15520 15521 // If the block isn't obviously global, i.e. it captures anything at 15522 // all, then we need to do a few things in the surrounding context: 15523 if (Result->getBlockDecl()->hasCaptures()) { 15524 // First, this expression has a new cleanup object. 15525 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15526 Cleanup.setExprNeedsCleanups(true); 15527 15528 // It also gets a branch-protected scope if any of the captured 15529 // variables needs destruction. 15530 for (const auto &CI : Result->getBlockDecl()->captures()) { 15531 const VarDecl *var = CI.getVariable(); 15532 if (var->getType().isDestructedType() != QualType::DK_none) { 15533 setFunctionHasBranchProtectedScope(); 15534 break; 15535 } 15536 } 15537 } 15538 15539 if (getCurFunction()) 15540 getCurFunction()->addBlock(BD); 15541 15542 return Result; 15543 } 15544 15545 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15546 SourceLocation RPLoc) { 15547 TypeSourceInfo *TInfo; 15548 GetTypeFromParser(Ty, &TInfo); 15549 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15550 } 15551 15552 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15553 Expr *E, TypeSourceInfo *TInfo, 15554 SourceLocation RPLoc) { 15555 Expr *OrigExpr = E; 15556 bool IsMS = false; 15557 15558 // CUDA device code does not support varargs. 15559 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15560 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15561 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15562 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15563 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15564 } 15565 } 15566 15567 // NVPTX does not support va_arg expression. 15568 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15569 Context.getTargetInfo().getTriple().isNVPTX()) 15570 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15571 15572 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15573 // as Microsoft ABI on an actual Microsoft platform, where 15574 // __builtin_ms_va_list and __builtin_va_list are the same.) 15575 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15576 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15577 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15578 if (Context.hasSameType(MSVaListType, E->getType())) { 15579 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15580 return ExprError(); 15581 IsMS = true; 15582 } 15583 } 15584 15585 // Get the va_list type 15586 QualType VaListType = Context.getBuiltinVaListType(); 15587 if (!IsMS) { 15588 if (VaListType->isArrayType()) { 15589 // Deal with implicit array decay; for example, on x86-64, 15590 // va_list is an array, but it's supposed to decay to 15591 // a pointer for va_arg. 15592 VaListType = Context.getArrayDecayedType(VaListType); 15593 // Make sure the input expression also decays appropriately. 15594 ExprResult Result = UsualUnaryConversions(E); 15595 if (Result.isInvalid()) 15596 return ExprError(); 15597 E = Result.get(); 15598 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15599 // If va_list is a record type and we are compiling in C++ mode, 15600 // check the argument using reference binding. 15601 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15602 Context, Context.getLValueReferenceType(VaListType), false); 15603 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15604 if (Init.isInvalid()) 15605 return ExprError(); 15606 E = Init.getAs<Expr>(); 15607 } else { 15608 // Otherwise, the va_list argument must be an l-value because 15609 // it is modified by va_arg. 15610 if (!E->isTypeDependent() && 15611 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15612 return ExprError(); 15613 } 15614 } 15615 15616 if (!IsMS && !E->isTypeDependent() && 15617 !Context.hasSameType(VaListType, E->getType())) 15618 return ExprError( 15619 Diag(E->getBeginLoc(), 15620 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15621 << OrigExpr->getType() << E->getSourceRange()); 15622 15623 if (!TInfo->getType()->isDependentType()) { 15624 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15625 diag::err_second_parameter_to_va_arg_incomplete, 15626 TInfo->getTypeLoc())) 15627 return ExprError(); 15628 15629 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15630 TInfo->getType(), 15631 diag::err_second_parameter_to_va_arg_abstract, 15632 TInfo->getTypeLoc())) 15633 return ExprError(); 15634 15635 if (!TInfo->getType().isPODType(Context)) { 15636 Diag(TInfo->getTypeLoc().getBeginLoc(), 15637 TInfo->getType()->isObjCLifetimeType() 15638 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15639 : diag::warn_second_parameter_to_va_arg_not_pod) 15640 << TInfo->getType() 15641 << TInfo->getTypeLoc().getSourceRange(); 15642 } 15643 15644 // Check for va_arg where arguments of the given type will be promoted 15645 // (i.e. this va_arg is guaranteed to have undefined behavior). 15646 QualType PromoteType; 15647 if (TInfo->getType()->isPromotableIntegerType()) { 15648 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15649 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15650 PromoteType = QualType(); 15651 } 15652 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15653 PromoteType = Context.DoubleTy; 15654 if (!PromoteType.isNull()) 15655 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15656 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15657 << TInfo->getType() 15658 << PromoteType 15659 << TInfo->getTypeLoc().getSourceRange()); 15660 } 15661 15662 QualType T = TInfo->getType().getNonLValueExprType(Context); 15663 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15664 } 15665 15666 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15667 // The type of __null will be int or long, depending on the size of 15668 // pointers on the target. 15669 QualType Ty; 15670 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15671 if (pw == Context.getTargetInfo().getIntWidth()) 15672 Ty = Context.IntTy; 15673 else if (pw == Context.getTargetInfo().getLongWidth()) 15674 Ty = Context.LongTy; 15675 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15676 Ty = Context.LongLongTy; 15677 else { 15678 llvm_unreachable("I don't know size of pointer!"); 15679 } 15680 15681 return new (Context) GNUNullExpr(Ty, TokenLoc); 15682 } 15683 15684 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15685 SourceLocation BuiltinLoc, 15686 SourceLocation RPLoc) { 15687 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15688 } 15689 15690 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15691 SourceLocation BuiltinLoc, 15692 SourceLocation RPLoc, 15693 DeclContext *ParentContext) { 15694 return new (Context) 15695 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15696 } 15697 15698 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15699 bool Diagnose) { 15700 if (!getLangOpts().ObjC) 15701 return false; 15702 15703 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15704 if (!PT) 15705 return false; 15706 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15707 15708 // Ignore any parens, implicit casts (should only be 15709 // array-to-pointer decays), and not-so-opaque values. The last is 15710 // important for making this trigger for property assignments. 15711 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15712 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15713 if (OV->getSourceExpr()) 15714 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15715 15716 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15717 if (!PT->isObjCIdType() && 15718 !(ID && ID->getIdentifier()->isStr("NSString"))) 15719 return false; 15720 if (!SL->isAscii()) 15721 return false; 15722 15723 if (Diagnose) { 15724 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15725 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15726 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15727 } 15728 return true; 15729 } 15730 15731 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15732 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15733 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15734 !SrcExpr->isNullPointerConstant( 15735 getASTContext(), Expr::NPC_NeverValueDependent)) { 15736 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15737 return false; 15738 if (Diagnose) { 15739 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15740 << /*number*/1 15741 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15742 Expr *NumLit = 15743 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15744 if (NumLit) 15745 Exp = NumLit; 15746 } 15747 return true; 15748 } 15749 15750 return false; 15751 } 15752 15753 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15754 const Expr *SrcExpr) { 15755 if (!DstType->isFunctionPointerType() || 15756 !SrcExpr->getType()->isFunctionType()) 15757 return false; 15758 15759 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15760 if (!DRE) 15761 return false; 15762 15763 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15764 if (!FD) 15765 return false; 15766 15767 return !S.checkAddressOfFunctionIsAvailable(FD, 15768 /*Complain=*/true, 15769 SrcExpr->getBeginLoc()); 15770 } 15771 15772 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15773 SourceLocation Loc, 15774 QualType DstType, QualType SrcType, 15775 Expr *SrcExpr, AssignmentAction Action, 15776 bool *Complained) { 15777 if (Complained) 15778 *Complained = false; 15779 15780 // Decode the result (notice that AST's are still created for extensions). 15781 bool CheckInferredResultType = false; 15782 bool isInvalid = false; 15783 unsigned DiagKind = 0; 15784 ConversionFixItGenerator ConvHints; 15785 bool MayHaveConvFixit = false; 15786 bool MayHaveFunctionDiff = false; 15787 const ObjCInterfaceDecl *IFace = nullptr; 15788 const ObjCProtocolDecl *PDecl = nullptr; 15789 15790 switch (ConvTy) { 15791 case Compatible: 15792 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15793 return false; 15794 15795 case PointerToInt: 15796 if (getLangOpts().CPlusPlus) { 15797 DiagKind = diag::err_typecheck_convert_pointer_int; 15798 isInvalid = true; 15799 } else { 15800 DiagKind = diag::ext_typecheck_convert_pointer_int; 15801 } 15802 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15803 MayHaveConvFixit = true; 15804 break; 15805 case IntToPointer: 15806 if (getLangOpts().CPlusPlus) { 15807 DiagKind = diag::err_typecheck_convert_int_pointer; 15808 isInvalid = true; 15809 } else { 15810 DiagKind = diag::ext_typecheck_convert_int_pointer; 15811 } 15812 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15813 MayHaveConvFixit = true; 15814 break; 15815 case IncompatibleFunctionPointer: 15816 if (getLangOpts().CPlusPlus) { 15817 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15818 isInvalid = true; 15819 } else { 15820 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15821 } 15822 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15823 MayHaveConvFixit = true; 15824 break; 15825 case IncompatiblePointer: 15826 if (Action == AA_Passing_CFAudited) { 15827 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15828 } else if (getLangOpts().CPlusPlus) { 15829 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15830 isInvalid = true; 15831 } else { 15832 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15833 } 15834 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15835 SrcType->isObjCObjectPointerType(); 15836 if (!CheckInferredResultType) { 15837 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15838 } else if (CheckInferredResultType) { 15839 SrcType = SrcType.getUnqualifiedType(); 15840 DstType = DstType.getUnqualifiedType(); 15841 } 15842 MayHaveConvFixit = true; 15843 break; 15844 case IncompatiblePointerSign: 15845 if (getLangOpts().CPlusPlus) { 15846 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15847 isInvalid = true; 15848 } else { 15849 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15850 } 15851 break; 15852 case FunctionVoidPointer: 15853 if (getLangOpts().CPlusPlus) { 15854 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15855 isInvalid = true; 15856 } else { 15857 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15858 } 15859 break; 15860 case IncompatiblePointerDiscardsQualifiers: { 15861 // Perform array-to-pointer decay if necessary. 15862 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15863 15864 isInvalid = true; 15865 15866 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15867 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15868 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15869 DiagKind = diag::err_typecheck_incompatible_address_space; 15870 break; 15871 15872 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15873 DiagKind = diag::err_typecheck_incompatible_ownership; 15874 break; 15875 } 15876 15877 llvm_unreachable("unknown error case for discarding qualifiers!"); 15878 // fallthrough 15879 } 15880 case CompatiblePointerDiscardsQualifiers: 15881 // If the qualifiers lost were because we were applying the 15882 // (deprecated) C++ conversion from a string literal to a char* 15883 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15884 // Ideally, this check would be performed in 15885 // checkPointerTypesForAssignment. However, that would require a 15886 // bit of refactoring (so that the second argument is an 15887 // expression, rather than a type), which should be done as part 15888 // of a larger effort to fix checkPointerTypesForAssignment for 15889 // C++ semantics. 15890 if (getLangOpts().CPlusPlus && 15891 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15892 return false; 15893 if (getLangOpts().CPlusPlus) { 15894 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15895 isInvalid = true; 15896 } else { 15897 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15898 } 15899 15900 break; 15901 case IncompatibleNestedPointerQualifiers: 15902 if (getLangOpts().CPlusPlus) { 15903 isInvalid = true; 15904 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15905 } else { 15906 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15907 } 15908 break; 15909 case IncompatibleNestedPointerAddressSpaceMismatch: 15910 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15911 isInvalid = true; 15912 break; 15913 case IntToBlockPointer: 15914 DiagKind = diag::err_int_to_block_pointer; 15915 isInvalid = true; 15916 break; 15917 case IncompatibleBlockPointer: 15918 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15919 isInvalid = true; 15920 break; 15921 case IncompatibleObjCQualifiedId: { 15922 if (SrcType->isObjCQualifiedIdType()) { 15923 const ObjCObjectPointerType *srcOPT = 15924 SrcType->castAs<ObjCObjectPointerType>(); 15925 for (auto *srcProto : srcOPT->quals()) { 15926 PDecl = srcProto; 15927 break; 15928 } 15929 if (const ObjCInterfaceType *IFaceT = 15930 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15931 IFace = IFaceT->getDecl(); 15932 } 15933 else if (DstType->isObjCQualifiedIdType()) { 15934 const ObjCObjectPointerType *dstOPT = 15935 DstType->castAs<ObjCObjectPointerType>(); 15936 for (auto *dstProto : dstOPT->quals()) { 15937 PDecl = dstProto; 15938 break; 15939 } 15940 if (const ObjCInterfaceType *IFaceT = 15941 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15942 IFace = IFaceT->getDecl(); 15943 } 15944 if (getLangOpts().CPlusPlus) { 15945 DiagKind = diag::err_incompatible_qualified_id; 15946 isInvalid = true; 15947 } else { 15948 DiagKind = diag::warn_incompatible_qualified_id; 15949 } 15950 break; 15951 } 15952 case IncompatibleVectors: 15953 if (getLangOpts().CPlusPlus) { 15954 DiagKind = diag::err_incompatible_vectors; 15955 isInvalid = true; 15956 } else { 15957 DiagKind = diag::warn_incompatible_vectors; 15958 } 15959 break; 15960 case IncompatibleObjCWeakRef: 15961 DiagKind = diag::err_arc_weak_unavailable_assign; 15962 isInvalid = true; 15963 break; 15964 case Incompatible: 15965 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15966 if (Complained) 15967 *Complained = true; 15968 return true; 15969 } 15970 15971 DiagKind = diag::err_typecheck_convert_incompatible; 15972 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15973 MayHaveConvFixit = true; 15974 isInvalid = true; 15975 MayHaveFunctionDiff = true; 15976 break; 15977 } 15978 15979 QualType FirstType, SecondType; 15980 switch (Action) { 15981 case AA_Assigning: 15982 case AA_Initializing: 15983 // The destination type comes first. 15984 FirstType = DstType; 15985 SecondType = SrcType; 15986 break; 15987 15988 case AA_Returning: 15989 case AA_Passing: 15990 case AA_Passing_CFAudited: 15991 case AA_Converting: 15992 case AA_Sending: 15993 case AA_Casting: 15994 // The source type comes first. 15995 FirstType = SrcType; 15996 SecondType = DstType; 15997 break; 15998 } 15999 16000 PartialDiagnostic FDiag = PDiag(DiagKind); 16001 if (Action == AA_Passing_CFAudited) 16002 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16003 else 16004 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16005 16006 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16007 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16008 auto isPlainChar = [](const clang::Type *Type) { 16009 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16010 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16011 }; 16012 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16013 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16014 } 16015 16016 // If we can fix the conversion, suggest the FixIts. 16017 if (!ConvHints.isNull()) { 16018 for (FixItHint &H : ConvHints.Hints) 16019 FDiag << H; 16020 } 16021 16022 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16023 16024 if (MayHaveFunctionDiff) 16025 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16026 16027 Diag(Loc, FDiag); 16028 if ((DiagKind == diag::warn_incompatible_qualified_id || 16029 DiagKind == diag::err_incompatible_qualified_id) && 16030 PDecl && IFace && !IFace->hasDefinition()) 16031 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16032 << IFace << PDecl; 16033 16034 if (SecondType == Context.OverloadTy) 16035 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16036 FirstType, /*TakingAddress=*/true); 16037 16038 if (CheckInferredResultType) 16039 EmitRelatedResultTypeNote(SrcExpr); 16040 16041 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16042 EmitRelatedResultTypeNoteForReturn(DstType); 16043 16044 if (Complained) 16045 *Complained = true; 16046 return isInvalid; 16047 } 16048 16049 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16050 llvm::APSInt *Result, 16051 AllowFoldKind CanFold) { 16052 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16053 public: 16054 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16055 QualType T) override { 16056 return S.Diag(Loc, diag::err_ice_not_integral) 16057 << T << S.LangOpts.CPlusPlus; 16058 } 16059 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16060 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16061 } 16062 } Diagnoser; 16063 16064 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16065 } 16066 16067 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16068 llvm::APSInt *Result, 16069 unsigned DiagID, 16070 AllowFoldKind CanFold) { 16071 class IDDiagnoser : public VerifyICEDiagnoser { 16072 unsigned DiagID; 16073 16074 public: 16075 IDDiagnoser(unsigned DiagID) 16076 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16077 16078 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16079 return S.Diag(Loc, DiagID); 16080 } 16081 } Diagnoser(DiagID); 16082 16083 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16084 } 16085 16086 Sema::SemaDiagnosticBuilder 16087 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16088 QualType T) { 16089 return diagnoseNotICE(S, Loc); 16090 } 16091 16092 Sema::SemaDiagnosticBuilder 16093 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16094 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16095 } 16096 16097 ExprResult 16098 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16099 VerifyICEDiagnoser &Diagnoser, 16100 AllowFoldKind CanFold) { 16101 SourceLocation DiagLoc = E->getBeginLoc(); 16102 16103 if (getLangOpts().CPlusPlus11) { 16104 // C++11 [expr.const]p5: 16105 // If an expression of literal class type is used in a context where an 16106 // integral constant expression is required, then that class type shall 16107 // have a single non-explicit conversion function to an integral or 16108 // unscoped enumeration type 16109 ExprResult Converted; 16110 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16111 VerifyICEDiagnoser &BaseDiagnoser; 16112 public: 16113 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16114 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16115 BaseDiagnoser.Suppress, true), 16116 BaseDiagnoser(BaseDiagnoser) {} 16117 16118 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16119 QualType T) override { 16120 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16121 } 16122 16123 SemaDiagnosticBuilder diagnoseIncomplete( 16124 Sema &S, SourceLocation Loc, QualType T) override { 16125 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16126 } 16127 16128 SemaDiagnosticBuilder diagnoseExplicitConv( 16129 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16130 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16131 } 16132 16133 SemaDiagnosticBuilder noteExplicitConv( 16134 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16135 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16136 << ConvTy->isEnumeralType() << ConvTy; 16137 } 16138 16139 SemaDiagnosticBuilder diagnoseAmbiguous( 16140 Sema &S, SourceLocation Loc, QualType T) override { 16141 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16142 } 16143 16144 SemaDiagnosticBuilder noteAmbiguous( 16145 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16146 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16147 << ConvTy->isEnumeralType() << ConvTy; 16148 } 16149 16150 SemaDiagnosticBuilder diagnoseConversion( 16151 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16152 llvm_unreachable("conversion functions are permitted"); 16153 } 16154 } ConvertDiagnoser(Diagnoser); 16155 16156 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16157 ConvertDiagnoser); 16158 if (Converted.isInvalid()) 16159 return Converted; 16160 E = Converted.get(); 16161 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16162 return ExprError(); 16163 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16164 // An ICE must be of integral or unscoped enumeration type. 16165 if (!Diagnoser.Suppress) 16166 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16167 << E->getSourceRange(); 16168 return ExprError(); 16169 } 16170 16171 ExprResult RValueExpr = DefaultLvalueConversion(E); 16172 if (RValueExpr.isInvalid()) 16173 return ExprError(); 16174 16175 E = RValueExpr.get(); 16176 16177 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16178 // in the non-ICE case. 16179 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16180 if (Result) 16181 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16182 if (!isa<ConstantExpr>(E)) 16183 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16184 : ConstantExpr::Create(Context, E); 16185 return E; 16186 } 16187 16188 Expr::EvalResult EvalResult; 16189 SmallVector<PartialDiagnosticAt, 8> Notes; 16190 EvalResult.Diag = &Notes; 16191 16192 // Try to evaluate the expression, and produce diagnostics explaining why it's 16193 // not a constant expression as a side-effect. 16194 bool Folded = 16195 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16196 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16197 16198 if (!isa<ConstantExpr>(E)) 16199 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16200 16201 // In C++11, we can rely on diagnostics being produced for any expression 16202 // which is not a constant expression. If no diagnostics were produced, then 16203 // this is a constant expression. 16204 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16205 if (Result) 16206 *Result = EvalResult.Val.getInt(); 16207 return E; 16208 } 16209 16210 // If our only note is the usual "invalid subexpression" note, just point 16211 // the caret at its location rather than producing an essentially 16212 // redundant note. 16213 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16214 diag::note_invalid_subexpr_in_const_expr) { 16215 DiagLoc = Notes[0].first; 16216 Notes.clear(); 16217 } 16218 16219 if (!Folded || !CanFold) { 16220 if (!Diagnoser.Suppress) { 16221 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16222 for (const PartialDiagnosticAt &Note : Notes) 16223 Diag(Note.first, Note.second); 16224 } 16225 16226 return ExprError(); 16227 } 16228 16229 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16230 for (const PartialDiagnosticAt &Note : Notes) 16231 Diag(Note.first, Note.second); 16232 16233 if (Result) 16234 *Result = EvalResult.Val.getInt(); 16235 return E; 16236 } 16237 16238 namespace { 16239 // Handle the case where we conclude a expression which we speculatively 16240 // considered to be unevaluated is actually evaluated. 16241 class TransformToPE : public TreeTransform<TransformToPE> { 16242 typedef TreeTransform<TransformToPE> BaseTransform; 16243 16244 public: 16245 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16246 16247 // Make sure we redo semantic analysis 16248 bool AlwaysRebuild() { return true; } 16249 bool ReplacingOriginal() { return true; } 16250 16251 // We need to special-case DeclRefExprs referring to FieldDecls which 16252 // are not part of a member pointer formation; normal TreeTransforming 16253 // doesn't catch this case because of the way we represent them in the AST. 16254 // FIXME: This is a bit ugly; is it really the best way to handle this 16255 // case? 16256 // 16257 // Error on DeclRefExprs referring to FieldDecls. 16258 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16259 if (isa<FieldDecl>(E->getDecl()) && 16260 !SemaRef.isUnevaluatedContext()) 16261 return SemaRef.Diag(E->getLocation(), 16262 diag::err_invalid_non_static_member_use) 16263 << E->getDecl() << E->getSourceRange(); 16264 16265 return BaseTransform::TransformDeclRefExpr(E); 16266 } 16267 16268 // Exception: filter out member pointer formation 16269 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16270 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16271 return E; 16272 16273 return BaseTransform::TransformUnaryOperator(E); 16274 } 16275 16276 // The body of a lambda-expression is in a separate expression evaluation 16277 // context so never needs to be transformed. 16278 // FIXME: Ideally we wouldn't transform the closure type either, and would 16279 // just recreate the capture expressions and lambda expression. 16280 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16281 return SkipLambdaBody(E, Body); 16282 } 16283 }; 16284 } 16285 16286 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16287 assert(isUnevaluatedContext() && 16288 "Should only transform unevaluated expressions"); 16289 ExprEvalContexts.back().Context = 16290 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16291 if (isUnevaluatedContext()) 16292 return E; 16293 return TransformToPE(*this).TransformExpr(E); 16294 } 16295 16296 void 16297 Sema::PushExpressionEvaluationContext( 16298 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16299 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16300 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16301 LambdaContextDecl, ExprContext); 16302 Cleanup.reset(); 16303 if (!MaybeODRUseExprs.empty()) 16304 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16305 } 16306 16307 void 16308 Sema::PushExpressionEvaluationContext( 16309 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16310 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16311 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16312 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16313 } 16314 16315 namespace { 16316 16317 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16318 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16319 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16320 if (E->getOpcode() == UO_Deref) 16321 return CheckPossibleDeref(S, E->getSubExpr()); 16322 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16323 return CheckPossibleDeref(S, E->getBase()); 16324 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16325 return CheckPossibleDeref(S, E->getBase()); 16326 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16327 QualType Inner; 16328 QualType Ty = E->getType(); 16329 if (const auto *Ptr = Ty->getAs<PointerType>()) 16330 Inner = Ptr->getPointeeType(); 16331 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16332 Inner = Arr->getElementType(); 16333 else 16334 return nullptr; 16335 16336 if (Inner->hasAttr(attr::NoDeref)) 16337 return E; 16338 } 16339 return nullptr; 16340 } 16341 16342 } // namespace 16343 16344 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16345 for (const Expr *E : Rec.PossibleDerefs) { 16346 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16347 if (DeclRef) { 16348 const ValueDecl *Decl = DeclRef->getDecl(); 16349 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16350 << Decl->getName() << E->getSourceRange(); 16351 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16352 } else { 16353 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16354 << E->getSourceRange(); 16355 } 16356 } 16357 Rec.PossibleDerefs.clear(); 16358 } 16359 16360 /// Check whether E, which is either a discarded-value expression or an 16361 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16362 /// and if so, remove it from the list of volatile-qualified assignments that 16363 /// we are going to warn are deprecated. 16364 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16365 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16366 return; 16367 16368 // Note: ignoring parens here is not justified by the standard rules, but 16369 // ignoring parentheses seems like a more reasonable approach, and this only 16370 // drives a deprecation warning so doesn't affect conformance. 16371 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16372 if (BO->getOpcode() == BO_Assign) { 16373 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16374 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16375 LHSs.end()); 16376 } 16377 } 16378 } 16379 16380 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16381 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16382 RebuildingImmediateInvocation) 16383 return E; 16384 16385 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16386 /// It's OK if this fails; we'll also remove this in 16387 /// HandleImmediateInvocations, but catching it here allows us to avoid 16388 /// walking the AST looking for it in simple cases. 16389 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16390 if (auto *DeclRef = 16391 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16392 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16393 16394 E = MaybeCreateExprWithCleanups(E); 16395 16396 ConstantExpr *Res = ConstantExpr::Create( 16397 getASTContext(), E.get(), 16398 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16399 getASTContext()), 16400 /*IsImmediateInvocation*/ true); 16401 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16402 return Res; 16403 } 16404 16405 static void EvaluateAndDiagnoseImmediateInvocation( 16406 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16407 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16408 Expr::EvalResult Eval; 16409 Eval.Diag = &Notes; 16410 ConstantExpr *CE = Candidate.getPointer(); 16411 bool Result = CE->EvaluateAsConstantExpr( 16412 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16413 if (!Result || !Notes.empty()) { 16414 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16415 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16416 InnerExpr = FunctionalCast->getSubExpr(); 16417 FunctionDecl *FD = nullptr; 16418 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16419 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16420 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16421 FD = Call->getConstructor(); 16422 else 16423 llvm_unreachable("unhandled decl kind"); 16424 assert(FD->isConsteval()); 16425 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16426 for (auto &Note : Notes) 16427 SemaRef.Diag(Note.first, Note.second); 16428 return; 16429 } 16430 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16431 } 16432 16433 static void RemoveNestedImmediateInvocation( 16434 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16435 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16436 struct ComplexRemove : TreeTransform<ComplexRemove> { 16437 using Base = TreeTransform<ComplexRemove>; 16438 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16439 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16440 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16441 CurrentII; 16442 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16443 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16444 SmallVector<Sema::ImmediateInvocationCandidate, 16445 4>::reverse_iterator Current) 16446 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16447 void RemoveImmediateInvocation(ConstantExpr* E) { 16448 auto It = std::find_if(CurrentII, IISet.rend(), 16449 [E](Sema::ImmediateInvocationCandidate Elem) { 16450 return Elem.getPointer() == E; 16451 }); 16452 assert(It != IISet.rend() && 16453 "ConstantExpr marked IsImmediateInvocation should " 16454 "be present"); 16455 It->setInt(1); // Mark as deleted 16456 } 16457 ExprResult TransformConstantExpr(ConstantExpr *E) { 16458 if (!E->isImmediateInvocation()) 16459 return Base::TransformConstantExpr(E); 16460 RemoveImmediateInvocation(E); 16461 return Base::TransformExpr(E->getSubExpr()); 16462 } 16463 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16464 /// we need to remove its DeclRefExpr from the DRSet. 16465 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16466 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16467 return Base::TransformCXXOperatorCallExpr(E); 16468 } 16469 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16470 /// here. 16471 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16472 if (!Init) 16473 return Init; 16474 /// ConstantExpr are the first layer of implicit node to be removed so if 16475 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16476 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16477 if (CE->isImmediateInvocation()) 16478 RemoveImmediateInvocation(CE); 16479 return Base::TransformInitializer(Init, NotCopyInit); 16480 } 16481 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16482 DRSet.erase(E); 16483 return E; 16484 } 16485 bool AlwaysRebuild() { return false; } 16486 bool ReplacingOriginal() { return true; } 16487 bool AllowSkippingCXXConstructExpr() { 16488 bool Res = AllowSkippingFirstCXXConstructExpr; 16489 AllowSkippingFirstCXXConstructExpr = true; 16490 return Res; 16491 } 16492 bool AllowSkippingFirstCXXConstructExpr = true; 16493 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16494 Rec.ImmediateInvocationCandidates, It); 16495 16496 /// CXXConstructExpr with a single argument are getting skipped by 16497 /// TreeTransform in some situtation because they could be implicit. This 16498 /// can only occur for the top-level CXXConstructExpr because it is used 16499 /// nowhere in the expression being transformed therefore will not be rebuilt. 16500 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16501 /// skipping the first CXXConstructExpr. 16502 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16503 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16504 16505 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16506 assert(Res.isUsable()); 16507 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16508 It->getPointer()->setSubExpr(Res.get()); 16509 } 16510 16511 static void 16512 HandleImmediateInvocations(Sema &SemaRef, 16513 Sema::ExpressionEvaluationContextRecord &Rec) { 16514 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16515 Rec.ReferenceToConsteval.size() == 0) || 16516 SemaRef.RebuildingImmediateInvocation) 16517 return; 16518 16519 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16520 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16521 /// need to remove ReferenceToConsteval in the immediate invocation. 16522 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16523 16524 /// Prevent sema calls during the tree transform from adding pointers that 16525 /// are already in the sets. 16526 llvm::SaveAndRestore<bool> DisableIITracking( 16527 SemaRef.RebuildingImmediateInvocation, true); 16528 16529 /// Prevent diagnostic during tree transfrom as they are duplicates 16530 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16531 16532 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16533 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16534 if (!It->getInt()) 16535 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16536 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16537 Rec.ReferenceToConsteval.size()) { 16538 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16539 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16540 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16541 bool VisitDeclRefExpr(DeclRefExpr *E) { 16542 DRSet.erase(E); 16543 return DRSet.size(); 16544 } 16545 } Visitor(Rec.ReferenceToConsteval); 16546 Visitor.TraverseStmt( 16547 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16548 } 16549 for (auto CE : Rec.ImmediateInvocationCandidates) 16550 if (!CE.getInt()) 16551 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16552 for (auto DR : Rec.ReferenceToConsteval) { 16553 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16554 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16555 << FD; 16556 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16557 } 16558 } 16559 16560 void Sema::PopExpressionEvaluationContext() { 16561 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16562 unsigned NumTypos = Rec.NumTypos; 16563 16564 if (!Rec.Lambdas.empty()) { 16565 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16566 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16567 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16568 unsigned D; 16569 if (Rec.isUnevaluated()) { 16570 // C++11 [expr.prim.lambda]p2: 16571 // A lambda-expression shall not appear in an unevaluated operand 16572 // (Clause 5). 16573 D = diag::err_lambda_unevaluated_operand; 16574 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16575 // C++1y [expr.const]p2: 16576 // A conditional-expression e is a core constant expression unless the 16577 // evaluation of e, following the rules of the abstract machine, would 16578 // evaluate [...] a lambda-expression. 16579 D = diag::err_lambda_in_constant_expression; 16580 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16581 // C++17 [expr.prim.lamda]p2: 16582 // A lambda-expression shall not appear [...] in a template-argument. 16583 D = diag::err_lambda_in_invalid_context; 16584 } else 16585 llvm_unreachable("Couldn't infer lambda error message."); 16586 16587 for (const auto *L : Rec.Lambdas) 16588 Diag(L->getBeginLoc(), D); 16589 } 16590 } 16591 16592 WarnOnPendingNoDerefs(Rec); 16593 HandleImmediateInvocations(*this, Rec); 16594 16595 // Warn on any volatile-qualified simple-assignments that are not discarded- 16596 // value expressions nor unevaluated operands (those cases get removed from 16597 // this list by CheckUnusedVolatileAssignment). 16598 for (auto *BO : Rec.VolatileAssignmentLHSs) 16599 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16600 << BO->getType(); 16601 16602 // When are coming out of an unevaluated context, clear out any 16603 // temporaries that we may have created as part of the evaluation of 16604 // the expression in that context: they aren't relevant because they 16605 // will never be constructed. 16606 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16607 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16608 ExprCleanupObjects.end()); 16609 Cleanup = Rec.ParentCleanup; 16610 CleanupVarDeclMarking(); 16611 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16612 // Otherwise, merge the contexts together. 16613 } else { 16614 Cleanup.mergeFrom(Rec.ParentCleanup); 16615 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16616 Rec.SavedMaybeODRUseExprs.end()); 16617 } 16618 16619 // Pop the current expression evaluation context off the stack. 16620 ExprEvalContexts.pop_back(); 16621 16622 // The global expression evaluation context record is never popped. 16623 ExprEvalContexts.back().NumTypos += NumTypos; 16624 } 16625 16626 void Sema::DiscardCleanupsInEvaluationContext() { 16627 ExprCleanupObjects.erase( 16628 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16629 ExprCleanupObjects.end()); 16630 Cleanup.reset(); 16631 MaybeODRUseExprs.clear(); 16632 } 16633 16634 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16635 ExprResult Result = CheckPlaceholderExpr(E); 16636 if (Result.isInvalid()) 16637 return ExprError(); 16638 E = Result.get(); 16639 if (!E->getType()->isVariablyModifiedType()) 16640 return E; 16641 return TransformToPotentiallyEvaluated(E); 16642 } 16643 16644 /// Are we in a context that is potentially constant evaluated per C++20 16645 /// [expr.const]p12? 16646 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16647 /// C++2a [expr.const]p12: 16648 // An expression or conversion is potentially constant evaluated if it is 16649 switch (SemaRef.ExprEvalContexts.back().Context) { 16650 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16651 // -- a manifestly constant-evaluated expression, 16652 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16653 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16654 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16655 // -- a potentially-evaluated expression, 16656 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16657 // -- an immediate subexpression of a braced-init-list, 16658 16659 // -- [FIXME] an expression of the form & cast-expression that occurs 16660 // within a templated entity 16661 // -- a subexpression of one of the above that is not a subexpression of 16662 // a nested unevaluated operand. 16663 return true; 16664 16665 case Sema::ExpressionEvaluationContext::Unevaluated: 16666 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16667 // Expressions in this context are never evaluated. 16668 return false; 16669 } 16670 llvm_unreachable("Invalid context"); 16671 } 16672 16673 /// Return true if this function has a calling convention that requires mangling 16674 /// in the size of the parameter pack. 16675 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16676 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16677 // we don't need parameter type sizes. 16678 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16679 if (!TT.isOSWindows() || !TT.isX86()) 16680 return false; 16681 16682 // If this is C++ and this isn't an extern "C" function, parameters do not 16683 // need to be complete. In this case, C++ mangling will apply, which doesn't 16684 // use the size of the parameters. 16685 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16686 return false; 16687 16688 // Stdcall, fastcall, and vectorcall need this special treatment. 16689 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16690 switch (CC) { 16691 case CC_X86StdCall: 16692 case CC_X86FastCall: 16693 case CC_X86VectorCall: 16694 return true; 16695 default: 16696 break; 16697 } 16698 return false; 16699 } 16700 16701 /// Require that all of the parameter types of function be complete. Normally, 16702 /// parameter types are only required to be complete when a function is called 16703 /// or defined, but to mangle functions with certain calling conventions, the 16704 /// mangler needs to know the size of the parameter list. In this situation, 16705 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16706 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16707 /// result in a linker error. Clang doesn't implement this behavior, and instead 16708 /// attempts to error at compile time. 16709 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16710 SourceLocation Loc) { 16711 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16712 FunctionDecl *FD; 16713 ParmVarDecl *Param; 16714 16715 public: 16716 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16717 : FD(FD), Param(Param) {} 16718 16719 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16720 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16721 StringRef CCName; 16722 switch (CC) { 16723 case CC_X86StdCall: 16724 CCName = "stdcall"; 16725 break; 16726 case CC_X86FastCall: 16727 CCName = "fastcall"; 16728 break; 16729 case CC_X86VectorCall: 16730 CCName = "vectorcall"; 16731 break; 16732 default: 16733 llvm_unreachable("CC does not need mangling"); 16734 } 16735 16736 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16737 << Param->getDeclName() << FD->getDeclName() << CCName; 16738 } 16739 }; 16740 16741 for (ParmVarDecl *Param : FD->parameters()) { 16742 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16743 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16744 } 16745 } 16746 16747 namespace { 16748 enum class OdrUseContext { 16749 /// Declarations in this context are not odr-used. 16750 None, 16751 /// Declarations in this context are formally odr-used, but this is a 16752 /// dependent context. 16753 Dependent, 16754 /// Declarations in this context are odr-used but not actually used (yet). 16755 FormallyOdrUsed, 16756 /// Declarations in this context are used. 16757 Used 16758 }; 16759 } 16760 16761 /// Are we within a context in which references to resolved functions or to 16762 /// variables result in odr-use? 16763 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16764 OdrUseContext Result; 16765 16766 switch (SemaRef.ExprEvalContexts.back().Context) { 16767 case Sema::ExpressionEvaluationContext::Unevaluated: 16768 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16769 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16770 return OdrUseContext::None; 16771 16772 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16773 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16774 Result = OdrUseContext::Used; 16775 break; 16776 16777 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16778 Result = OdrUseContext::FormallyOdrUsed; 16779 break; 16780 16781 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16782 // A default argument formally results in odr-use, but doesn't actually 16783 // result in a use in any real sense until it itself is used. 16784 Result = OdrUseContext::FormallyOdrUsed; 16785 break; 16786 } 16787 16788 if (SemaRef.CurContext->isDependentContext()) 16789 return OdrUseContext::Dependent; 16790 16791 return Result; 16792 } 16793 16794 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16795 if (!Func->isConstexpr()) 16796 return false; 16797 16798 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16799 return true; 16800 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16801 return CCD && CCD->getInheritedConstructor(); 16802 } 16803 16804 /// Mark a function referenced, and check whether it is odr-used 16805 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16806 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16807 bool MightBeOdrUse) { 16808 assert(Func && "No function?"); 16809 16810 Func->setReferenced(); 16811 16812 // Recursive functions aren't really used until they're used from some other 16813 // context. 16814 bool IsRecursiveCall = CurContext == Func; 16815 16816 // C++11 [basic.def.odr]p3: 16817 // A function whose name appears as a potentially-evaluated expression is 16818 // odr-used if it is the unique lookup result or the selected member of a 16819 // set of overloaded functions [...]. 16820 // 16821 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16822 // can just check that here. 16823 OdrUseContext OdrUse = 16824 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16825 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16826 OdrUse = OdrUseContext::FormallyOdrUsed; 16827 16828 // Trivial default constructors and destructors are never actually used. 16829 // FIXME: What about other special members? 16830 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16831 OdrUse == OdrUseContext::Used) { 16832 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16833 if (Constructor->isDefaultConstructor()) 16834 OdrUse = OdrUseContext::FormallyOdrUsed; 16835 if (isa<CXXDestructorDecl>(Func)) 16836 OdrUse = OdrUseContext::FormallyOdrUsed; 16837 } 16838 16839 // C++20 [expr.const]p12: 16840 // A function [...] is needed for constant evaluation if it is [...] a 16841 // constexpr function that is named by an expression that is potentially 16842 // constant evaluated 16843 bool NeededForConstantEvaluation = 16844 isPotentiallyConstantEvaluatedContext(*this) && 16845 isImplicitlyDefinableConstexprFunction(Func); 16846 16847 // Determine whether we require a function definition to exist, per 16848 // C++11 [temp.inst]p3: 16849 // Unless a function template specialization has been explicitly 16850 // instantiated or explicitly specialized, the function template 16851 // specialization is implicitly instantiated when the specialization is 16852 // referenced in a context that requires a function definition to exist. 16853 // C++20 [temp.inst]p7: 16854 // The existence of a definition of a [...] function is considered to 16855 // affect the semantics of the program if the [...] function is needed for 16856 // constant evaluation by an expression 16857 // C++20 [basic.def.odr]p10: 16858 // Every program shall contain exactly one definition of every non-inline 16859 // function or variable that is odr-used in that program outside of a 16860 // discarded statement 16861 // C++20 [special]p1: 16862 // The implementation will implicitly define [defaulted special members] 16863 // if they are odr-used or needed for constant evaluation. 16864 // 16865 // Note that we skip the implicit instantiation of templates that are only 16866 // used in unused default arguments or by recursive calls to themselves. 16867 // This is formally non-conforming, but seems reasonable in practice. 16868 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16869 NeededForConstantEvaluation); 16870 16871 // C++14 [temp.expl.spec]p6: 16872 // If a template [...] is explicitly specialized then that specialization 16873 // shall be declared before the first use of that specialization that would 16874 // cause an implicit instantiation to take place, in every translation unit 16875 // in which such a use occurs 16876 if (NeedDefinition && 16877 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16878 Func->getMemberSpecializationInfo())) 16879 checkSpecializationVisibility(Loc, Func); 16880 16881 if (getLangOpts().CUDA) 16882 CheckCUDACall(Loc, Func); 16883 16884 if (getLangOpts().SYCLIsDevice) 16885 checkSYCLDeviceFunction(Loc, Func); 16886 16887 // If we need a definition, try to create one. 16888 if (NeedDefinition && !Func->getBody()) { 16889 runWithSufficientStackSpace(Loc, [&] { 16890 if (CXXConstructorDecl *Constructor = 16891 dyn_cast<CXXConstructorDecl>(Func)) { 16892 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16893 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16894 if (Constructor->isDefaultConstructor()) { 16895 if (Constructor->isTrivial() && 16896 !Constructor->hasAttr<DLLExportAttr>()) 16897 return; 16898 DefineImplicitDefaultConstructor(Loc, Constructor); 16899 } else if (Constructor->isCopyConstructor()) { 16900 DefineImplicitCopyConstructor(Loc, Constructor); 16901 } else if (Constructor->isMoveConstructor()) { 16902 DefineImplicitMoveConstructor(Loc, Constructor); 16903 } 16904 } else if (Constructor->getInheritedConstructor()) { 16905 DefineInheritingConstructor(Loc, Constructor); 16906 } 16907 } else if (CXXDestructorDecl *Destructor = 16908 dyn_cast<CXXDestructorDecl>(Func)) { 16909 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16910 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16911 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16912 return; 16913 DefineImplicitDestructor(Loc, Destructor); 16914 } 16915 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16916 MarkVTableUsed(Loc, Destructor->getParent()); 16917 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16918 if (MethodDecl->isOverloadedOperator() && 16919 MethodDecl->getOverloadedOperator() == OO_Equal) { 16920 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16921 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16922 if (MethodDecl->isCopyAssignmentOperator()) 16923 DefineImplicitCopyAssignment(Loc, MethodDecl); 16924 else if (MethodDecl->isMoveAssignmentOperator()) 16925 DefineImplicitMoveAssignment(Loc, MethodDecl); 16926 } 16927 } else if (isa<CXXConversionDecl>(MethodDecl) && 16928 MethodDecl->getParent()->isLambda()) { 16929 CXXConversionDecl *Conversion = 16930 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16931 if (Conversion->isLambdaToBlockPointerConversion()) 16932 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16933 else 16934 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16935 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16936 MarkVTableUsed(Loc, MethodDecl->getParent()); 16937 } 16938 16939 if (Func->isDefaulted() && !Func->isDeleted()) { 16940 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16941 if (DCK != DefaultedComparisonKind::None) 16942 DefineDefaultedComparison(Loc, Func, DCK); 16943 } 16944 16945 // Implicit instantiation of function templates and member functions of 16946 // class templates. 16947 if (Func->isImplicitlyInstantiable()) { 16948 TemplateSpecializationKind TSK = 16949 Func->getTemplateSpecializationKindForInstantiation(); 16950 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16951 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16952 if (FirstInstantiation) { 16953 PointOfInstantiation = Loc; 16954 if (auto *MSI = Func->getMemberSpecializationInfo()) 16955 MSI->setPointOfInstantiation(Loc); 16956 // FIXME: Notify listener. 16957 else 16958 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16959 } else if (TSK != TSK_ImplicitInstantiation) { 16960 // Use the point of use as the point of instantiation, instead of the 16961 // point of explicit instantiation (which we track as the actual point 16962 // of instantiation). This gives better backtraces in diagnostics. 16963 PointOfInstantiation = Loc; 16964 } 16965 16966 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16967 Func->isConstexpr()) { 16968 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16969 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16970 CodeSynthesisContexts.size()) 16971 PendingLocalImplicitInstantiations.push_back( 16972 std::make_pair(Func, PointOfInstantiation)); 16973 else if (Func->isConstexpr()) 16974 // Do not defer instantiations of constexpr functions, to avoid the 16975 // expression evaluator needing to call back into Sema if it sees a 16976 // call to such a function. 16977 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16978 else { 16979 Func->setInstantiationIsPending(true); 16980 PendingInstantiations.push_back( 16981 std::make_pair(Func, PointOfInstantiation)); 16982 // Notify the consumer that a function was implicitly instantiated. 16983 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16984 } 16985 } 16986 } else { 16987 // Walk redefinitions, as some of them may be instantiable. 16988 for (auto i : Func->redecls()) { 16989 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16990 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16991 } 16992 } 16993 }); 16994 } 16995 16996 // C++14 [except.spec]p17: 16997 // An exception-specification is considered to be needed when: 16998 // - the function is odr-used or, if it appears in an unevaluated operand, 16999 // would be odr-used if the expression were potentially-evaluated; 17000 // 17001 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17002 // function is a pure virtual function we're calling, and in that case the 17003 // function was selected by overload resolution and we need to resolve its 17004 // exception specification for a different reason. 17005 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17006 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17007 ResolveExceptionSpec(Loc, FPT); 17008 17009 // If this is the first "real" use, act on that. 17010 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17011 // Keep track of used but undefined functions. 17012 if (!Func->isDefined()) { 17013 if (mightHaveNonExternalLinkage(Func)) 17014 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17015 else if (Func->getMostRecentDecl()->isInlined() && 17016 !LangOpts.GNUInline && 17017 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17018 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17019 else if (isExternalWithNoLinkageType(Func)) 17020 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17021 } 17022 17023 // Some x86 Windows calling conventions mangle the size of the parameter 17024 // pack into the name. Computing the size of the parameters requires the 17025 // parameter types to be complete. Check that now. 17026 if (funcHasParameterSizeMangling(*this, Func)) 17027 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17028 17029 // In the MS C++ ABI, the compiler emits destructor variants where they are 17030 // used. If the destructor is used here but defined elsewhere, mark the 17031 // virtual base destructors referenced. If those virtual base destructors 17032 // are inline, this will ensure they are defined when emitting the complete 17033 // destructor variant. This checking may be redundant if the destructor is 17034 // provided later in this TU. 17035 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17036 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17037 CXXRecordDecl *Parent = Dtor->getParent(); 17038 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17039 CheckCompleteDestructorVariant(Loc, Dtor); 17040 } 17041 } 17042 17043 Func->markUsed(Context); 17044 } 17045 } 17046 17047 /// Directly mark a variable odr-used. Given a choice, prefer to use 17048 /// MarkVariableReferenced since it does additional checks and then 17049 /// calls MarkVarDeclODRUsed. 17050 /// If the variable must be captured: 17051 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17052 /// - else capture it in the DeclContext that maps to the 17053 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17054 static void 17055 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17056 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17057 // Keep track of used but undefined variables. 17058 // FIXME: We shouldn't suppress this warning for static data members. 17059 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17060 (!Var->isExternallyVisible() || Var->isInline() || 17061 SemaRef.isExternalWithNoLinkageType(Var)) && 17062 !(Var->isStaticDataMember() && Var->hasInit())) { 17063 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17064 if (old.isInvalid()) 17065 old = Loc; 17066 } 17067 QualType CaptureType, DeclRefType; 17068 if (SemaRef.LangOpts.OpenMP) 17069 SemaRef.tryCaptureOpenMPLambdas(Var); 17070 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17071 /*EllipsisLoc*/ SourceLocation(), 17072 /*BuildAndDiagnose*/ true, 17073 CaptureType, DeclRefType, 17074 FunctionScopeIndexToStopAt); 17075 17076 Var->markUsed(SemaRef.Context); 17077 } 17078 17079 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17080 SourceLocation Loc, 17081 unsigned CapturingScopeIndex) { 17082 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17083 } 17084 17085 static void 17086 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17087 ValueDecl *var, DeclContext *DC) { 17088 DeclContext *VarDC = var->getDeclContext(); 17089 17090 // If the parameter still belongs to the translation unit, then 17091 // we're actually just using one parameter in the declaration of 17092 // the next. 17093 if (isa<ParmVarDecl>(var) && 17094 isa<TranslationUnitDecl>(VarDC)) 17095 return; 17096 17097 // For C code, don't diagnose about capture if we're not actually in code 17098 // right now; it's impossible to write a non-constant expression outside of 17099 // function context, so we'll get other (more useful) diagnostics later. 17100 // 17101 // For C++, things get a bit more nasty... it would be nice to suppress this 17102 // diagnostic for certain cases like using a local variable in an array bound 17103 // for a member of a local class, but the correct predicate is not obvious. 17104 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17105 return; 17106 17107 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17108 unsigned ContextKind = 3; // unknown 17109 if (isa<CXXMethodDecl>(VarDC) && 17110 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17111 ContextKind = 2; 17112 } else if (isa<FunctionDecl>(VarDC)) { 17113 ContextKind = 0; 17114 } else if (isa<BlockDecl>(VarDC)) { 17115 ContextKind = 1; 17116 } 17117 17118 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17119 << var << ValueKind << ContextKind << VarDC; 17120 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17121 << var; 17122 17123 // FIXME: Add additional diagnostic info about class etc. which prevents 17124 // capture. 17125 } 17126 17127 17128 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17129 bool &SubCapturesAreNested, 17130 QualType &CaptureType, 17131 QualType &DeclRefType) { 17132 // Check whether we've already captured it. 17133 if (CSI->CaptureMap.count(Var)) { 17134 // If we found a capture, any subcaptures are nested. 17135 SubCapturesAreNested = true; 17136 17137 // Retrieve the capture type for this variable. 17138 CaptureType = CSI->getCapture(Var).getCaptureType(); 17139 17140 // Compute the type of an expression that refers to this variable. 17141 DeclRefType = CaptureType.getNonReferenceType(); 17142 17143 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17144 // are mutable in the sense that user can change their value - they are 17145 // private instances of the captured declarations. 17146 const Capture &Cap = CSI->getCapture(Var); 17147 if (Cap.isCopyCapture() && 17148 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17149 !(isa<CapturedRegionScopeInfo>(CSI) && 17150 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17151 DeclRefType.addConst(); 17152 return true; 17153 } 17154 return false; 17155 } 17156 17157 // Only block literals, captured statements, and lambda expressions can 17158 // capture; other scopes don't work. 17159 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17160 SourceLocation Loc, 17161 const bool Diagnose, Sema &S) { 17162 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17163 return getLambdaAwareParentOfDeclContext(DC); 17164 else if (Var->hasLocalStorage()) { 17165 if (Diagnose) 17166 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17167 } 17168 return nullptr; 17169 } 17170 17171 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17172 // certain types of variables (unnamed, variably modified types etc.) 17173 // so check for eligibility. 17174 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17175 SourceLocation Loc, 17176 const bool Diagnose, Sema &S) { 17177 17178 bool IsBlock = isa<BlockScopeInfo>(CSI); 17179 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17180 17181 // Lambdas are not allowed to capture unnamed variables 17182 // (e.g. anonymous unions). 17183 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17184 // assuming that's the intent. 17185 if (IsLambda && !Var->getDeclName()) { 17186 if (Diagnose) { 17187 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17188 S.Diag(Var->getLocation(), diag::note_declared_at); 17189 } 17190 return false; 17191 } 17192 17193 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17194 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17195 if (Diagnose) { 17196 S.Diag(Loc, diag::err_ref_vm_type); 17197 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17198 } 17199 return false; 17200 } 17201 // Prohibit structs with flexible array members too. 17202 // We cannot capture what is in the tail end of the struct. 17203 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17204 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17205 if (Diagnose) { 17206 if (IsBlock) 17207 S.Diag(Loc, diag::err_ref_flexarray_type); 17208 else 17209 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17210 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17211 } 17212 return false; 17213 } 17214 } 17215 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17216 // Lambdas and captured statements are not allowed to capture __block 17217 // variables; they don't support the expected semantics. 17218 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17219 if (Diagnose) { 17220 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17221 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17222 } 17223 return false; 17224 } 17225 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17226 if (S.getLangOpts().OpenCL && IsBlock && 17227 Var->getType()->isBlockPointerType()) { 17228 if (Diagnose) 17229 S.Diag(Loc, diag::err_opencl_block_ref_block); 17230 return false; 17231 } 17232 17233 return true; 17234 } 17235 17236 // Returns true if the capture by block was successful. 17237 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17238 SourceLocation Loc, 17239 const bool BuildAndDiagnose, 17240 QualType &CaptureType, 17241 QualType &DeclRefType, 17242 const bool Nested, 17243 Sema &S, bool Invalid) { 17244 bool ByRef = false; 17245 17246 // Blocks are not allowed to capture arrays, excepting OpenCL. 17247 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17248 // (decayed to pointers). 17249 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17250 if (BuildAndDiagnose) { 17251 S.Diag(Loc, diag::err_ref_array_type); 17252 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17253 Invalid = true; 17254 } else { 17255 return false; 17256 } 17257 } 17258 17259 // Forbid the block-capture of autoreleasing variables. 17260 if (!Invalid && 17261 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17262 if (BuildAndDiagnose) { 17263 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17264 << /*block*/ 0; 17265 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17266 Invalid = true; 17267 } else { 17268 return false; 17269 } 17270 } 17271 17272 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17273 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17274 QualType PointeeTy = PT->getPointeeType(); 17275 17276 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17277 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17278 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17279 if (BuildAndDiagnose) { 17280 SourceLocation VarLoc = Var->getLocation(); 17281 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17282 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17283 } 17284 } 17285 } 17286 17287 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17288 if (HasBlocksAttr || CaptureType->isReferenceType() || 17289 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17290 // Block capture by reference does not change the capture or 17291 // declaration reference types. 17292 ByRef = true; 17293 } else { 17294 // Block capture by copy introduces 'const'. 17295 CaptureType = CaptureType.getNonReferenceType().withConst(); 17296 DeclRefType = CaptureType; 17297 } 17298 17299 // Actually capture the variable. 17300 if (BuildAndDiagnose) 17301 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17302 CaptureType, Invalid); 17303 17304 return !Invalid; 17305 } 17306 17307 17308 /// Capture the given variable in the captured region. 17309 static bool captureInCapturedRegion( 17310 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17311 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17312 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17313 bool IsTopScope, Sema &S, bool Invalid) { 17314 // By default, capture variables by reference. 17315 bool ByRef = true; 17316 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17317 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17318 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17319 // Using an LValue reference type is consistent with Lambdas (see below). 17320 if (S.isOpenMPCapturedDecl(Var)) { 17321 bool HasConst = DeclRefType.isConstQualified(); 17322 DeclRefType = DeclRefType.getUnqualifiedType(); 17323 // Don't lose diagnostics about assignments to const. 17324 if (HasConst) 17325 DeclRefType.addConst(); 17326 } 17327 // Do not capture firstprivates in tasks. 17328 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17329 OMPC_unknown) 17330 return true; 17331 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17332 RSI->OpenMPCaptureLevel); 17333 } 17334 17335 if (ByRef) 17336 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17337 else 17338 CaptureType = DeclRefType; 17339 17340 // Actually capture the variable. 17341 if (BuildAndDiagnose) 17342 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17343 Loc, SourceLocation(), CaptureType, Invalid); 17344 17345 return !Invalid; 17346 } 17347 17348 /// Capture the given variable in the lambda. 17349 static bool captureInLambda(LambdaScopeInfo *LSI, 17350 VarDecl *Var, 17351 SourceLocation Loc, 17352 const bool BuildAndDiagnose, 17353 QualType &CaptureType, 17354 QualType &DeclRefType, 17355 const bool RefersToCapturedVariable, 17356 const Sema::TryCaptureKind Kind, 17357 SourceLocation EllipsisLoc, 17358 const bool IsTopScope, 17359 Sema &S, bool Invalid) { 17360 // Determine whether we are capturing by reference or by value. 17361 bool ByRef = false; 17362 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17363 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17364 } else { 17365 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17366 } 17367 17368 // Compute the type of the field that will capture this variable. 17369 if (ByRef) { 17370 // C++11 [expr.prim.lambda]p15: 17371 // An entity is captured by reference if it is implicitly or 17372 // explicitly captured but not captured by copy. It is 17373 // unspecified whether additional unnamed non-static data 17374 // members are declared in the closure type for entities 17375 // captured by reference. 17376 // 17377 // FIXME: It is not clear whether we want to build an lvalue reference 17378 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17379 // to do the former, while EDG does the latter. Core issue 1249 will 17380 // clarify, but for now we follow GCC because it's a more permissive and 17381 // easily defensible position. 17382 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17383 } else { 17384 // C++11 [expr.prim.lambda]p14: 17385 // For each entity captured by copy, an unnamed non-static 17386 // data member is declared in the closure type. The 17387 // declaration order of these members is unspecified. The type 17388 // of such a data member is the type of the corresponding 17389 // captured entity if the entity is not a reference to an 17390 // object, or the referenced type otherwise. [Note: If the 17391 // captured entity is a reference to a function, the 17392 // corresponding data member is also a reference to a 17393 // function. - end note ] 17394 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17395 if (!RefType->getPointeeType()->isFunctionType()) 17396 CaptureType = RefType->getPointeeType(); 17397 } 17398 17399 // Forbid the lambda copy-capture of autoreleasing variables. 17400 if (!Invalid && 17401 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17402 if (BuildAndDiagnose) { 17403 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17404 S.Diag(Var->getLocation(), diag::note_previous_decl) 17405 << Var->getDeclName(); 17406 Invalid = true; 17407 } else { 17408 return false; 17409 } 17410 } 17411 17412 // Make sure that by-copy captures are of a complete and non-abstract type. 17413 if (!Invalid && BuildAndDiagnose) { 17414 if (!CaptureType->isDependentType() && 17415 S.RequireCompleteSizedType( 17416 Loc, CaptureType, 17417 diag::err_capture_of_incomplete_or_sizeless_type, 17418 Var->getDeclName())) 17419 Invalid = true; 17420 else if (S.RequireNonAbstractType(Loc, CaptureType, 17421 diag::err_capture_of_abstract_type)) 17422 Invalid = true; 17423 } 17424 } 17425 17426 // Compute the type of a reference to this captured variable. 17427 if (ByRef) 17428 DeclRefType = CaptureType.getNonReferenceType(); 17429 else { 17430 // C++ [expr.prim.lambda]p5: 17431 // The closure type for a lambda-expression has a public inline 17432 // function call operator [...]. This function call operator is 17433 // declared const (9.3.1) if and only if the lambda-expression's 17434 // parameter-declaration-clause is not followed by mutable. 17435 DeclRefType = CaptureType.getNonReferenceType(); 17436 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17437 DeclRefType.addConst(); 17438 } 17439 17440 // Add the capture. 17441 if (BuildAndDiagnose) 17442 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17443 Loc, EllipsisLoc, CaptureType, Invalid); 17444 17445 return !Invalid; 17446 } 17447 17448 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17449 // Offer a Copy fix even if the type is dependent. 17450 if (Var->getType()->isDependentType()) 17451 return true; 17452 QualType T = Var->getType().getNonReferenceType(); 17453 if (T.isTriviallyCopyableType(Context)) 17454 return true; 17455 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17456 17457 if (!(RD = RD->getDefinition())) 17458 return false; 17459 if (RD->hasSimpleCopyConstructor()) 17460 return true; 17461 if (RD->hasUserDeclaredCopyConstructor()) 17462 for (CXXConstructorDecl *Ctor : RD->ctors()) 17463 if (Ctor->isCopyConstructor()) 17464 return !Ctor->isDeleted(); 17465 } 17466 return false; 17467 } 17468 17469 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17470 /// default capture. Fixes may be omitted if they aren't allowed by the 17471 /// standard, for example we can't emit a default copy capture fix-it if we 17472 /// already explicitly copy capture capture another variable. 17473 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17474 VarDecl *Var) { 17475 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17476 // Don't offer Capture by copy of default capture by copy fixes if Var is 17477 // known not to be copy constructible. 17478 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17479 17480 SmallString<32> FixBuffer; 17481 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17482 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17483 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17484 if (ShouldOfferCopyFix) { 17485 // Offer fixes to insert an explicit capture for the variable. 17486 // [] -> [VarName] 17487 // [OtherCapture] -> [OtherCapture, VarName] 17488 FixBuffer.assign({Separator, Var->getName()}); 17489 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17490 << Var << /*value*/ 0 17491 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17492 } 17493 // As above but capture by reference. 17494 FixBuffer.assign({Separator, "&", Var->getName()}); 17495 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17496 << Var << /*reference*/ 1 17497 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17498 } 17499 17500 // Only try to offer default capture if there are no captures excluding this 17501 // and init captures. 17502 // [this]: OK. 17503 // [X = Y]: OK. 17504 // [&A, &B]: Don't offer. 17505 // [A, B]: Don't offer. 17506 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17507 return !C.isThisCapture() && !C.isInitCapture(); 17508 })) 17509 return; 17510 17511 // The default capture specifiers, '=' or '&', must appear first in the 17512 // capture body. 17513 SourceLocation DefaultInsertLoc = 17514 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17515 17516 if (ShouldOfferCopyFix) { 17517 bool CanDefaultCopyCapture = true; 17518 // [=, *this] OK since c++17 17519 // [=, this] OK since c++20 17520 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17521 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17522 ? LSI->getCXXThisCapture().isCopyCapture() 17523 : false; 17524 // We can't use default capture by copy if any captures already specified 17525 // capture by copy. 17526 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17527 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17528 })) { 17529 FixBuffer.assign({"=", Separator}); 17530 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17531 << /*value*/ 0 17532 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17533 } 17534 } 17535 17536 // We can't use default capture by reference if any captures already specified 17537 // capture by reference. 17538 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17539 return !C.isInitCapture() && C.isReferenceCapture() && 17540 !C.isThisCapture(); 17541 })) { 17542 FixBuffer.assign({"&", Separator}); 17543 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17544 << /*reference*/ 1 17545 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17546 } 17547 } 17548 17549 bool Sema::tryCaptureVariable( 17550 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17551 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17552 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17553 // An init-capture is notionally from the context surrounding its 17554 // declaration, but its parent DC is the lambda class. 17555 DeclContext *VarDC = Var->getDeclContext(); 17556 if (Var->isInitCapture()) 17557 VarDC = VarDC->getParent(); 17558 17559 DeclContext *DC = CurContext; 17560 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17561 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17562 // We need to sync up the Declaration Context with the 17563 // FunctionScopeIndexToStopAt 17564 if (FunctionScopeIndexToStopAt) { 17565 unsigned FSIndex = FunctionScopes.size() - 1; 17566 while (FSIndex != MaxFunctionScopesIndex) { 17567 DC = getLambdaAwareParentOfDeclContext(DC); 17568 --FSIndex; 17569 } 17570 } 17571 17572 17573 // If the variable is declared in the current context, there is no need to 17574 // capture it. 17575 if (VarDC == DC) return true; 17576 17577 // Capture global variables if it is required to use private copy of this 17578 // variable. 17579 bool IsGlobal = !Var->hasLocalStorage(); 17580 if (IsGlobal && 17581 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17582 MaxFunctionScopesIndex))) 17583 return true; 17584 Var = Var->getCanonicalDecl(); 17585 17586 // Walk up the stack to determine whether we can capture the variable, 17587 // performing the "simple" checks that don't depend on type. We stop when 17588 // we've either hit the declared scope of the variable or find an existing 17589 // capture of that variable. We start from the innermost capturing-entity 17590 // (the DC) and ensure that all intervening capturing-entities 17591 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17592 // declcontext can either capture the variable or have already captured 17593 // the variable. 17594 CaptureType = Var->getType(); 17595 DeclRefType = CaptureType.getNonReferenceType(); 17596 bool Nested = false; 17597 bool Explicit = (Kind != TryCapture_Implicit); 17598 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17599 do { 17600 // Only block literals, captured statements, and lambda expressions can 17601 // capture; other scopes don't work. 17602 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17603 ExprLoc, 17604 BuildAndDiagnose, 17605 *this); 17606 // We need to check for the parent *first* because, if we *have* 17607 // private-captured a global variable, we need to recursively capture it in 17608 // intermediate blocks, lambdas, etc. 17609 if (!ParentDC) { 17610 if (IsGlobal) { 17611 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17612 break; 17613 } 17614 return true; 17615 } 17616 17617 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17618 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17619 17620 17621 // Check whether we've already captured it. 17622 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17623 DeclRefType)) { 17624 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17625 break; 17626 } 17627 // If we are instantiating a generic lambda call operator body, 17628 // we do not want to capture new variables. What was captured 17629 // during either a lambdas transformation or initial parsing 17630 // should be used. 17631 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17632 if (BuildAndDiagnose) { 17633 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17634 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17635 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17636 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17637 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17638 buildLambdaCaptureFixit(*this, LSI, Var); 17639 } else 17640 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17641 } 17642 return true; 17643 } 17644 17645 // Try to capture variable-length arrays types. 17646 if (Var->getType()->isVariablyModifiedType()) { 17647 // We're going to walk down into the type and look for VLA 17648 // expressions. 17649 QualType QTy = Var->getType(); 17650 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17651 QTy = PVD->getOriginalType(); 17652 captureVariablyModifiedType(Context, QTy, CSI); 17653 } 17654 17655 if (getLangOpts().OpenMP) { 17656 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17657 // OpenMP private variables should not be captured in outer scope, so 17658 // just break here. Similarly, global variables that are captured in a 17659 // target region should not be captured outside the scope of the region. 17660 if (RSI->CapRegionKind == CR_OpenMP) { 17661 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17662 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17663 // If the variable is private (i.e. not captured) and has variably 17664 // modified type, we still need to capture the type for correct 17665 // codegen in all regions, associated with the construct. Currently, 17666 // it is captured in the innermost captured region only. 17667 if (IsOpenMPPrivateDecl != OMPC_unknown && 17668 Var->getType()->isVariablyModifiedType()) { 17669 QualType QTy = Var->getType(); 17670 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17671 QTy = PVD->getOriginalType(); 17672 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17673 I < E; ++I) { 17674 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17675 FunctionScopes[FunctionScopesIndex - I]); 17676 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17677 "Wrong number of captured regions associated with the " 17678 "OpenMP construct."); 17679 captureVariablyModifiedType(Context, QTy, OuterRSI); 17680 } 17681 } 17682 bool IsTargetCap = 17683 IsOpenMPPrivateDecl != OMPC_private && 17684 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17685 RSI->OpenMPCaptureLevel); 17686 // Do not capture global if it is not privatized in outer regions. 17687 bool IsGlobalCap = 17688 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17689 RSI->OpenMPCaptureLevel); 17690 17691 // When we detect target captures we are looking from inside the 17692 // target region, therefore we need to propagate the capture from the 17693 // enclosing region. Therefore, the capture is not initially nested. 17694 if (IsTargetCap) 17695 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17696 17697 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17698 (IsGlobal && !IsGlobalCap)) { 17699 Nested = !IsTargetCap; 17700 bool HasConst = DeclRefType.isConstQualified(); 17701 DeclRefType = DeclRefType.getUnqualifiedType(); 17702 // Don't lose diagnostics about assignments to const. 17703 if (HasConst) 17704 DeclRefType.addConst(); 17705 CaptureType = Context.getLValueReferenceType(DeclRefType); 17706 break; 17707 } 17708 } 17709 } 17710 } 17711 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17712 // No capture-default, and this is not an explicit capture 17713 // so cannot capture this variable. 17714 if (BuildAndDiagnose) { 17715 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17716 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17717 auto *LSI = cast<LambdaScopeInfo>(CSI); 17718 if (LSI->Lambda) { 17719 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17720 buildLambdaCaptureFixit(*this, LSI, Var); 17721 } 17722 // FIXME: If we error out because an outer lambda can not implicitly 17723 // capture a variable that an inner lambda explicitly captures, we 17724 // should have the inner lambda do the explicit capture - because 17725 // it makes for cleaner diagnostics later. This would purely be done 17726 // so that the diagnostic does not misleadingly claim that a variable 17727 // can not be captured by a lambda implicitly even though it is captured 17728 // explicitly. Suggestion: 17729 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17730 // at the function head 17731 // - cache the StartingDeclContext - this must be a lambda 17732 // - captureInLambda in the innermost lambda the variable. 17733 } 17734 return true; 17735 } 17736 17737 FunctionScopesIndex--; 17738 DC = ParentDC; 17739 Explicit = false; 17740 } while (!VarDC->Equals(DC)); 17741 17742 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17743 // computing the type of the capture at each step, checking type-specific 17744 // requirements, and adding captures if requested. 17745 // If the variable had already been captured previously, we start capturing 17746 // at the lambda nested within that one. 17747 bool Invalid = false; 17748 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17749 ++I) { 17750 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17751 17752 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17753 // certain types of variables (unnamed, variably modified types etc.) 17754 // so check for eligibility. 17755 if (!Invalid) 17756 Invalid = 17757 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17758 17759 // After encountering an error, if we're actually supposed to capture, keep 17760 // capturing in nested contexts to suppress any follow-on diagnostics. 17761 if (Invalid && !BuildAndDiagnose) 17762 return true; 17763 17764 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17765 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17766 DeclRefType, Nested, *this, Invalid); 17767 Nested = true; 17768 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17769 Invalid = !captureInCapturedRegion( 17770 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17771 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17772 Nested = true; 17773 } else { 17774 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17775 Invalid = 17776 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17777 DeclRefType, Nested, Kind, EllipsisLoc, 17778 /*IsTopScope*/ I == N - 1, *this, Invalid); 17779 Nested = true; 17780 } 17781 17782 if (Invalid && !BuildAndDiagnose) 17783 return true; 17784 } 17785 return Invalid; 17786 } 17787 17788 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17789 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17790 QualType CaptureType; 17791 QualType DeclRefType; 17792 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17793 /*BuildAndDiagnose=*/true, CaptureType, 17794 DeclRefType, nullptr); 17795 } 17796 17797 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17798 QualType CaptureType; 17799 QualType DeclRefType; 17800 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17801 /*BuildAndDiagnose=*/false, CaptureType, 17802 DeclRefType, nullptr); 17803 } 17804 17805 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17806 QualType CaptureType; 17807 QualType DeclRefType; 17808 17809 // Determine whether we can capture this variable. 17810 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17811 /*BuildAndDiagnose=*/false, CaptureType, 17812 DeclRefType, nullptr)) 17813 return QualType(); 17814 17815 return DeclRefType; 17816 } 17817 17818 namespace { 17819 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17820 // The produced TemplateArgumentListInfo* points to data stored within this 17821 // object, so should only be used in contexts where the pointer will not be 17822 // used after the CopiedTemplateArgs object is destroyed. 17823 class CopiedTemplateArgs { 17824 bool HasArgs; 17825 TemplateArgumentListInfo TemplateArgStorage; 17826 public: 17827 template<typename RefExpr> 17828 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17829 if (HasArgs) 17830 E->copyTemplateArgumentsInto(TemplateArgStorage); 17831 } 17832 operator TemplateArgumentListInfo*() 17833 #ifdef __has_cpp_attribute 17834 #if __has_cpp_attribute(clang::lifetimebound) 17835 [[clang::lifetimebound]] 17836 #endif 17837 #endif 17838 { 17839 return HasArgs ? &TemplateArgStorage : nullptr; 17840 } 17841 }; 17842 } 17843 17844 /// Walk the set of potential results of an expression and mark them all as 17845 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17846 /// 17847 /// \return A new expression if we found any potential results, ExprEmpty() if 17848 /// not, and ExprError() if we diagnosed an error. 17849 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17850 NonOdrUseReason NOUR) { 17851 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17852 // an object that satisfies the requirements for appearing in a 17853 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17854 // is immediately applied." This function handles the lvalue-to-rvalue 17855 // conversion part. 17856 // 17857 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17858 // transform it into the relevant kind of non-odr-use node and rebuild the 17859 // tree of nodes leading to it. 17860 // 17861 // This is a mini-TreeTransform that only transforms a restricted subset of 17862 // nodes (and only certain operands of them). 17863 17864 // Rebuild a subexpression. 17865 auto Rebuild = [&](Expr *Sub) { 17866 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17867 }; 17868 17869 // Check whether a potential result satisfies the requirements of NOUR. 17870 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17871 // Any entity other than a VarDecl is always odr-used whenever it's named 17872 // in a potentially-evaluated expression. 17873 auto *VD = dyn_cast<VarDecl>(D); 17874 if (!VD) 17875 return true; 17876 17877 // C++2a [basic.def.odr]p4: 17878 // A variable x whose name appears as a potentially-evalauted expression 17879 // e is odr-used by e unless 17880 // -- x is a reference that is usable in constant expressions, or 17881 // -- x is a variable of non-reference type that is usable in constant 17882 // expressions and has no mutable subobjects, and e is an element of 17883 // the set of potential results of an expression of 17884 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17885 // conversion is applied, or 17886 // -- x is a variable of non-reference type, and e is an element of the 17887 // set of potential results of a discarded-value expression to which 17888 // the lvalue-to-rvalue conversion is not applied 17889 // 17890 // We check the first bullet and the "potentially-evaluated" condition in 17891 // BuildDeclRefExpr. We check the type requirements in the second bullet 17892 // in CheckLValueToRValueConversionOperand below. 17893 switch (NOUR) { 17894 case NOUR_None: 17895 case NOUR_Unevaluated: 17896 llvm_unreachable("unexpected non-odr-use-reason"); 17897 17898 case NOUR_Constant: 17899 // Constant references were handled when they were built. 17900 if (VD->getType()->isReferenceType()) 17901 return true; 17902 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17903 if (RD->hasMutableFields()) 17904 return true; 17905 if (!VD->isUsableInConstantExpressions(S.Context)) 17906 return true; 17907 break; 17908 17909 case NOUR_Discarded: 17910 if (VD->getType()->isReferenceType()) 17911 return true; 17912 break; 17913 } 17914 return false; 17915 }; 17916 17917 // Mark that this expression does not constitute an odr-use. 17918 auto MarkNotOdrUsed = [&] { 17919 S.MaybeODRUseExprs.remove(E); 17920 if (LambdaScopeInfo *LSI = S.getCurLambda()) 17921 LSI->markVariableExprAsNonODRUsed(E); 17922 }; 17923 17924 // C++2a [basic.def.odr]p2: 17925 // The set of potential results of an expression e is defined as follows: 17926 switch (E->getStmtClass()) { 17927 // -- If e is an id-expression, ... 17928 case Expr::DeclRefExprClass: { 17929 auto *DRE = cast<DeclRefExpr>(E); 17930 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 17931 break; 17932 17933 // Rebuild as a non-odr-use DeclRefExpr. 17934 MarkNotOdrUsed(); 17935 return DeclRefExpr::Create( 17936 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 17937 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 17938 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 17939 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 17940 } 17941 17942 case Expr::FunctionParmPackExprClass: { 17943 auto *FPPE = cast<FunctionParmPackExpr>(E); 17944 // If any of the declarations in the pack is odr-used, then the expression 17945 // as a whole constitutes an odr-use. 17946 for (VarDecl *D : *FPPE) 17947 if (IsPotentialResultOdrUsed(D)) 17948 return ExprEmpty(); 17949 17950 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 17951 // nothing cares about whether we marked this as an odr-use, but it might 17952 // be useful for non-compiler tools. 17953 MarkNotOdrUsed(); 17954 break; 17955 } 17956 17957 // -- If e is a subscripting operation with an array operand... 17958 case Expr::ArraySubscriptExprClass: { 17959 auto *ASE = cast<ArraySubscriptExpr>(E); 17960 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 17961 if (!OldBase->getType()->isArrayType()) 17962 break; 17963 ExprResult Base = Rebuild(OldBase); 17964 if (!Base.isUsable()) 17965 return Base; 17966 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 17967 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 17968 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 17969 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 17970 ASE->getRBracketLoc()); 17971 } 17972 17973 case Expr::MemberExprClass: { 17974 auto *ME = cast<MemberExpr>(E); 17975 // -- If e is a class member access expression [...] naming a non-static 17976 // data member... 17977 if (isa<FieldDecl>(ME->getMemberDecl())) { 17978 ExprResult Base = Rebuild(ME->getBase()); 17979 if (!Base.isUsable()) 17980 return Base; 17981 return MemberExpr::Create( 17982 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 17983 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 17984 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 17985 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 17986 ME->getObjectKind(), ME->isNonOdrUse()); 17987 } 17988 17989 if (ME->getMemberDecl()->isCXXInstanceMember()) 17990 break; 17991 17992 // -- If e is a class member access expression naming a static data member, 17993 // ... 17994 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 17995 break; 17996 17997 // Rebuild as a non-odr-use MemberExpr. 17998 MarkNotOdrUsed(); 17999 return MemberExpr::Create( 18000 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18001 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18002 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18003 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18004 return ExprEmpty(); 18005 } 18006 18007 case Expr::BinaryOperatorClass: { 18008 auto *BO = cast<BinaryOperator>(E); 18009 Expr *LHS = BO->getLHS(); 18010 Expr *RHS = BO->getRHS(); 18011 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18012 if (BO->getOpcode() == BO_PtrMemD) { 18013 ExprResult Sub = Rebuild(LHS); 18014 if (!Sub.isUsable()) 18015 return Sub; 18016 LHS = Sub.get(); 18017 // -- If e is a comma expression, ... 18018 } else if (BO->getOpcode() == BO_Comma) { 18019 ExprResult Sub = Rebuild(RHS); 18020 if (!Sub.isUsable()) 18021 return Sub; 18022 RHS = Sub.get(); 18023 } else { 18024 break; 18025 } 18026 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18027 LHS, RHS); 18028 } 18029 18030 // -- If e has the form (e1)... 18031 case Expr::ParenExprClass: { 18032 auto *PE = cast<ParenExpr>(E); 18033 ExprResult Sub = Rebuild(PE->getSubExpr()); 18034 if (!Sub.isUsable()) 18035 return Sub; 18036 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18037 } 18038 18039 // -- If e is a glvalue conditional expression, ... 18040 // We don't apply this to a binary conditional operator. FIXME: Should we? 18041 case Expr::ConditionalOperatorClass: { 18042 auto *CO = cast<ConditionalOperator>(E); 18043 ExprResult LHS = Rebuild(CO->getLHS()); 18044 if (LHS.isInvalid()) 18045 return ExprError(); 18046 ExprResult RHS = Rebuild(CO->getRHS()); 18047 if (RHS.isInvalid()) 18048 return ExprError(); 18049 if (!LHS.isUsable() && !RHS.isUsable()) 18050 return ExprEmpty(); 18051 if (!LHS.isUsable()) 18052 LHS = CO->getLHS(); 18053 if (!RHS.isUsable()) 18054 RHS = CO->getRHS(); 18055 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18056 CO->getCond(), LHS.get(), RHS.get()); 18057 } 18058 18059 // [Clang extension] 18060 // -- If e has the form __extension__ e1... 18061 case Expr::UnaryOperatorClass: { 18062 auto *UO = cast<UnaryOperator>(E); 18063 if (UO->getOpcode() != UO_Extension) 18064 break; 18065 ExprResult Sub = Rebuild(UO->getSubExpr()); 18066 if (!Sub.isUsable()) 18067 return Sub; 18068 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18069 Sub.get()); 18070 } 18071 18072 // [Clang extension] 18073 // -- If e has the form _Generic(...), the set of potential results is the 18074 // union of the sets of potential results of the associated expressions. 18075 case Expr::GenericSelectionExprClass: { 18076 auto *GSE = cast<GenericSelectionExpr>(E); 18077 18078 SmallVector<Expr *, 4> AssocExprs; 18079 bool AnyChanged = false; 18080 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18081 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18082 if (AssocExpr.isInvalid()) 18083 return ExprError(); 18084 if (AssocExpr.isUsable()) { 18085 AssocExprs.push_back(AssocExpr.get()); 18086 AnyChanged = true; 18087 } else { 18088 AssocExprs.push_back(OrigAssocExpr); 18089 } 18090 } 18091 18092 return AnyChanged ? S.CreateGenericSelectionExpr( 18093 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18094 GSE->getRParenLoc(), GSE->getControllingExpr(), 18095 GSE->getAssocTypeSourceInfos(), AssocExprs) 18096 : ExprEmpty(); 18097 } 18098 18099 // [Clang extension] 18100 // -- If e has the form __builtin_choose_expr(...), the set of potential 18101 // results is the union of the sets of potential results of the 18102 // second and third subexpressions. 18103 case Expr::ChooseExprClass: { 18104 auto *CE = cast<ChooseExpr>(E); 18105 18106 ExprResult LHS = Rebuild(CE->getLHS()); 18107 if (LHS.isInvalid()) 18108 return ExprError(); 18109 18110 ExprResult RHS = Rebuild(CE->getLHS()); 18111 if (RHS.isInvalid()) 18112 return ExprError(); 18113 18114 if (!LHS.get() && !RHS.get()) 18115 return ExprEmpty(); 18116 if (!LHS.isUsable()) 18117 LHS = CE->getLHS(); 18118 if (!RHS.isUsable()) 18119 RHS = CE->getRHS(); 18120 18121 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18122 RHS.get(), CE->getRParenLoc()); 18123 } 18124 18125 // Step through non-syntactic nodes. 18126 case Expr::ConstantExprClass: { 18127 auto *CE = cast<ConstantExpr>(E); 18128 ExprResult Sub = Rebuild(CE->getSubExpr()); 18129 if (!Sub.isUsable()) 18130 return Sub; 18131 return ConstantExpr::Create(S.Context, Sub.get()); 18132 } 18133 18134 // We could mostly rely on the recursive rebuilding to rebuild implicit 18135 // casts, but not at the top level, so rebuild them here. 18136 case Expr::ImplicitCastExprClass: { 18137 auto *ICE = cast<ImplicitCastExpr>(E); 18138 // Only step through the narrow set of cast kinds we expect to encounter. 18139 // Anything else suggests we've left the region in which potential results 18140 // can be found. 18141 switch (ICE->getCastKind()) { 18142 case CK_NoOp: 18143 case CK_DerivedToBase: 18144 case CK_UncheckedDerivedToBase: { 18145 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18146 if (!Sub.isUsable()) 18147 return Sub; 18148 CXXCastPath Path(ICE->path()); 18149 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18150 ICE->getValueKind(), &Path); 18151 } 18152 18153 default: 18154 break; 18155 } 18156 break; 18157 } 18158 18159 default: 18160 break; 18161 } 18162 18163 // Can't traverse through this node. Nothing to do. 18164 return ExprEmpty(); 18165 } 18166 18167 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18168 // Check whether the operand is or contains an object of non-trivial C union 18169 // type. 18170 if (E->getType().isVolatileQualified() && 18171 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18172 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18173 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18174 Sema::NTCUC_LValueToRValueVolatile, 18175 NTCUK_Destruct|NTCUK_Copy); 18176 18177 // C++2a [basic.def.odr]p4: 18178 // [...] an expression of non-volatile-qualified non-class type to which 18179 // the lvalue-to-rvalue conversion is applied [...] 18180 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18181 return E; 18182 18183 ExprResult Result = 18184 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18185 if (Result.isInvalid()) 18186 return ExprError(); 18187 return Result.get() ? Result : E; 18188 } 18189 18190 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18191 Res = CorrectDelayedTyposInExpr(Res); 18192 18193 if (!Res.isUsable()) 18194 return Res; 18195 18196 // If a constant-expression is a reference to a variable where we delay 18197 // deciding whether it is an odr-use, just assume we will apply the 18198 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18199 // (a non-type template argument), we have special handling anyway. 18200 return CheckLValueToRValueConversionOperand(Res.get()); 18201 } 18202 18203 void Sema::CleanupVarDeclMarking() { 18204 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18205 // call. 18206 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18207 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18208 18209 for (Expr *E : LocalMaybeODRUseExprs) { 18210 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18211 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18212 DRE->getLocation(), *this); 18213 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18214 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18215 *this); 18216 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18217 for (VarDecl *VD : *FP) 18218 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18219 } else { 18220 llvm_unreachable("Unexpected expression"); 18221 } 18222 } 18223 18224 assert(MaybeODRUseExprs.empty() && 18225 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18226 } 18227 18228 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18229 VarDecl *Var, Expr *E) { 18230 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18231 isa<FunctionParmPackExpr>(E)) && 18232 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18233 Var->setReferenced(); 18234 18235 if (Var->isInvalidDecl()) 18236 return; 18237 18238 // Record a CUDA/HIP static device/constant variable if it is referenced 18239 // by host code. This is done conservatively, when the variable is referenced 18240 // in any of the following contexts: 18241 // - a non-function context 18242 // - a host function 18243 // - a host device function 18244 // This also requires the reference of the static device/constant variable by 18245 // host code to be visible in the device compilation for the compiler to be 18246 // able to externalize the static device/constant variable. 18247 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18248 auto *CurContext = SemaRef.CurContext; 18249 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18250 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18251 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18252 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18253 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18254 } 18255 18256 auto *MSI = Var->getMemberSpecializationInfo(); 18257 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18258 : Var->getTemplateSpecializationKind(); 18259 18260 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18261 bool UsableInConstantExpr = 18262 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18263 18264 // C++20 [expr.const]p12: 18265 // A variable [...] is needed for constant evaluation if it is [...] a 18266 // variable whose name appears as a potentially constant evaluated 18267 // expression that is either a contexpr variable or is of non-volatile 18268 // const-qualified integral type or of reference type 18269 bool NeededForConstantEvaluation = 18270 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18271 18272 bool NeedDefinition = 18273 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18274 18275 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18276 "Can't instantiate a partial template specialization."); 18277 18278 // If this might be a member specialization of a static data member, check 18279 // the specialization is visible. We already did the checks for variable 18280 // template specializations when we created them. 18281 if (NeedDefinition && TSK != TSK_Undeclared && 18282 !isa<VarTemplateSpecializationDecl>(Var)) 18283 SemaRef.checkSpecializationVisibility(Loc, Var); 18284 18285 // Perform implicit instantiation of static data members, static data member 18286 // templates of class templates, and variable template specializations. Delay 18287 // instantiations of variable templates, except for those that could be used 18288 // in a constant expression. 18289 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18290 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18291 // instantiation declaration if a variable is usable in a constant 18292 // expression (among other cases). 18293 bool TryInstantiating = 18294 TSK == TSK_ImplicitInstantiation || 18295 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18296 18297 if (TryInstantiating) { 18298 SourceLocation PointOfInstantiation = 18299 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18300 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18301 if (FirstInstantiation) { 18302 PointOfInstantiation = Loc; 18303 if (MSI) 18304 MSI->setPointOfInstantiation(PointOfInstantiation); 18305 // FIXME: Notify listener. 18306 else 18307 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18308 } 18309 18310 if (UsableInConstantExpr) { 18311 // Do not defer instantiations of variables that could be used in a 18312 // constant expression. 18313 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18314 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18315 }); 18316 18317 // Re-set the member to trigger a recomputation of the dependence bits 18318 // for the expression. 18319 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18320 DRE->setDecl(DRE->getDecl()); 18321 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18322 ME->setMemberDecl(ME->getMemberDecl()); 18323 } else if (FirstInstantiation || 18324 isa<VarTemplateSpecializationDecl>(Var)) { 18325 // FIXME: For a specialization of a variable template, we don't 18326 // distinguish between "declaration and type implicitly instantiated" 18327 // and "implicit instantiation of definition requested", so we have 18328 // no direct way to avoid enqueueing the pending instantiation 18329 // multiple times. 18330 SemaRef.PendingInstantiations 18331 .push_back(std::make_pair(Var, PointOfInstantiation)); 18332 } 18333 } 18334 } 18335 18336 // C++2a [basic.def.odr]p4: 18337 // A variable x whose name appears as a potentially-evaluated expression e 18338 // is odr-used by e unless 18339 // -- x is a reference that is usable in constant expressions 18340 // -- x is a variable of non-reference type that is usable in constant 18341 // expressions and has no mutable subobjects [FIXME], and e is an 18342 // element of the set of potential results of an expression of 18343 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18344 // conversion is applied 18345 // -- x is a variable of non-reference type, and e is an element of the set 18346 // of potential results of a discarded-value expression to which the 18347 // lvalue-to-rvalue conversion is not applied [FIXME] 18348 // 18349 // We check the first part of the second bullet here, and 18350 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18351 // FIXME: To get the third bullet right, we need to delay this even for 18352 // variables that are not usable in constant expressions. 18353 18354 // If we already know this isn't an odr-use, there's nothing more to do. 18355 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18356 if (DRE->isNonOdrUse()) 18357 return; 18358 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18359 if (ME->isNonOdrUse()) 18360 return; 18361 18362 switch (OdrUse) { 18363 case OdrUseContext::None: 18364 assert((!E || isa<FunctionParmPackExpr>(E)) && 18365 "missing non-odr-use marking for unevaluated decl ref"); 18366 break; 18367 18368 case OdrUseContext::FormallyOdrUsed: 18369 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18370 // behavior. 18371 break; 18372 18373 case OdrUseContext::Used: 18374 // If we might later find that this expression isn't actually an odr-use, 18375 // delay the marking. 18376 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18377 SemaRef.MaybeODRUseExprs.insert(E); 18378 else 18379 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18380 break; 18381 18382 case OdrUseContext::Dependent: 18383 // If this is a dependent context, we don't need to mark variables as 18384 // odr-used, but we may still need to track them for lambda capture. 18385 // FIXME: Do we also need to do this inside dependent typeid expressions 18386 // (which are modeled as unevaluated at this point)? 18387 const bool RefersToEnclosingScope = 18388 (SemaRef.CurContext != Var->getDeclContext() && 18389 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18390 if (RefersToEnclosingScope) { 18391 LambdaScopeInfo *const LSI = 18392 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18393 if (LSI && (!LSI->CallOperator || 18394 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18395 // If a variable could potentially be odr-used, defer marking it so 18396 // until we finish analyzing the full expression for any 18397 // lvalue-to-rvalue 18398 // or discarded value conversions that would obviate odr-use. 18399 // Add it to the list of potential captures that will be analyzed 18400 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18401 // unless the variable is a reference that was initialized by a constant 18402 // expression (this will never need to be captured or odr-used). 18403 // 18404 // FIXME: We can simplify this a lot after implementing P0588R1. 18405 assert(E && "Capture variable should be used in an expression."); 18406 if (!Var->getType()->isReferenceType() || 18407 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18408 LSI->addPotentialCapture(E->IgnoreParens()); 18409 } 18410 } 18411 break; 18412 } 18413 } 18414 18415 /// Mark a variable referenced, and check whether it is odr-used 18416 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18417 /// used directly for normal expressions referring to VarDecl. 18418 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18419 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18420 } 18421 18422 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18423 Decl *D, Expr *E, bool MightBeOdrUse) { 18424 if (SemaRef.isInOpenMPDeclareTargetContext()) 18425 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18426 18427 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18428 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18429 return; 18430 } 18431 18432 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18433 18434 // If this is a call to a method via a cast, also mark the method in the 18435 // derived class used in case codegen can devirtualize the call. 18436 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18437 if (!ME) 18438 return; 18439 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18440 if (!MD) 18441 return; 18442 // Only attempt to devirtualize if this is truly a virtual call. 18443 bool IsVirtualCall = MD->isVirtual() && 18444 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18445 if (!IsVirtualCall) 18446 return; 18447 18448 // If it's possible to devirtualize the call, mark the called function 18449 // referenced. 18450 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18451 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18452 if (DM) 18453 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18454 } 18455 18456 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18457 /// 18458 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18459 /// handled with care if the DeclRefExpr is not newly-created. 18460 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18461 // TODO: update this with DR# once a defect report is filed. 18462 // C++11 defect. The address of a pure member should not be an ODR use, even 18463 // if it's a qualified reference. 18464 bool OdrUse = true; 18465 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18466 if (Method->isVirtual() && 18467 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18468 OdrUse = false; 18469 18470 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18471 if (!isConstantEvaluated() && FD->isConsteval() && 18472 !RebuildingImmediateInvocation) 18473 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18474 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18475 } 18476 18477 /// Perform reference-marking and odr-use handling for a MemberExpr. 18478 void Sema::MarkMemberReferenced(MemberExpr *E) { 18479 // C++11 [basic.def.odr]p2: 18480 // A non-overloaded function whose name appears as a potentially-evaluated 18481 // expression or a member of a set of candidate functions, if selected by 18482 // overload resolution when referred to from a potentially-evaluated 18483 // expression, is odr-used, unless it is a pure virtual function and its 18484 // name is not explicitly qualified. 18485 bool MightBeOdrUse = true; 18486 if (E->performsVirtualDispatch(getLangOpts())) { 18487 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18488 if (Method->isPure()) 18489 MightBeOdrUse = false; 18490 } 18491 SourceLocation Loc = 18492 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18493 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18494 } 18495 18496 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18497 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18498 for (VarDecl *VD : *E) 18499 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18500 } 18501 18502 /// Perform marking for a reference to an arbitrary declaration. It 18503 /// marks the declaration referenced, and performs odr-use checking for 18504 /// functions and variables. This method should not be used when building a 18505 /// normal expression which refers to a variable. 18506 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18507 bool MightBeOdrUse) { 18508 if (MightBeOdrUse) { 18509 if (auto *VD = dyn_cast<VarDecl>(D)) { 18510 MarkVariableReferenced(Loc, VD); 18511 return; 18512 } 18513 } 18514 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18515 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18516 return; 18517 } 18518 D->setReferenced(); 18519 } 18520 18521 namespace { 18522 // Mark all of the declarations used by a type as referenced. 18523 // FIXME: Not fully implemented yet! We need to have a better understanding 18524 // of when we're entering a context we should not recurse into. 18525 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18526 // TreeTransforms rebuilding the type in a new context. Rather than 18527 // duplicating the TreeTransform logic, we should consider reusing it here. 18528 // Currently that causes problems when rebuilding LambdaExprs. 18529 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18530 Sema &S; 18531 SourceLocation Loc; 18532 18533 public: 18534 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18535 18536 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18537 18538 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18539 }; 18540 } 18541 18542 bool MarkReferencedDecls::TraverseTemplateArgument( 18543 const TemplateArgument &Arg) { 18544 { 18545 // A non-type template argument is a constant-evaluated context. 18546 EnterExpressionEvaluationContext Evaluated( 18547 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18548 if (Arg.getKind() == TemplateArgument::Declaration) { 18549 if (Decl *D = Arg.getAsDecl()) 18550 S.MarkAnyDeclReferenced(Loc, D, true); 18551 } else if (Arg.getKind() == TemplateArgument::Expression) { 18552 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18553 } 18554 } 18555 18556 return Inherited::TraverseTemplateArgument(Arg); 18557 } 18558 18559 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18560 MarkReferencedDecls Marker(*this, Loc); 18561 Marker.TraverseType(T); 18562 } 18563 18564 namespace { 18565 /// Helper class that marks all of the declarations referenced by 18566 /// potentially-evaluated subexpressions as "referenced". 18567 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18568 public: 18569 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18570 bool SkipLocalVariables; 18571 18572 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18573 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18574 18575 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18576 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18577 } 18578 18579 void VisitDeclRefExpr(DeclRefExpr *E) { 18580 // If we were asked not to visit local variables, don't. 18581 if (SkipLocalVariables) { 18582 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18583 if (VD->hasLocalStorage()) 18584 return; 18585 } 18586 18587 // FIXME: This can trigger the instantiation of the initializer of a 18588 // variable, which can cause the expression to become value-dependent 18589 // or error-dependent. Do we need to propagate the new dependence bits? 18590 S.MarkDeclRefReferenced(E); 18591 } 18592 18593 void VisitMemberExpr(MemberExpr *E) { 18594 S.MarkMemberReferenced(E); 18595 Visit(E->getBase()); 18596 } 18597 }; 18598 } // namespace 18599 18600 /// Mark any declarations that appear within this expression or any 18601 /// potentially-evaluated subexpressions as "referenced". 18602 /// 18603 /// \param SkipLocalVariables If true, don't mark local variables as 18604 /// 'referenced'. 18605 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18606 bool SkipLocalVariables) { 18607 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18608 } 18609 18610 /// Emit a diagnostic that describes an effect on the run-time behavior 18611 /// of the program being compiled. 18612 /// 18613 /// This routine emits the given diagnostic when the code currently being 18614 /// type-checked is "potentially evaluated", meaning that there is a 18615 /// possibility that the code will actually be executable. Code in sizeof() 18616 /// expressions, code used only during overload resolution, etc., are not 18617 /// potentially evaluated. This routine will suppress such diagnostics or, 18618 /// in the absolutely nutty case of potentially potentially evaluated 18619 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18620 /// later. 18621 /// 18622 /// This routine should be used for all diagnostics that describe the run-time 18623 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18624 /// Failure to do so will likely result in spurious diagnostics or failures 18625 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18626 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18627 const PartialDiagnostic &PD) { 18628 switch (ExprEvalContexts.back().Context) { 18629 case ExpressionEvaluationContext::Unevaluated: 18630 case ExpressionEvaluationContext::UnevaluatedList: 18631 case ExpressionEvaluationContext::UnevaluatedAbstract: 18632 case ExpressionEvaluationContext::DiscardedStatement: 18633 // The argument will never be evaluated, so don't complain. 18634 break; 18635 18636 case ExpressionEvaluationContext::ConstantEvaluated: 18637 // Relevant diagnostics should be produced by constant evaluation. 18638 break; 18639 18640 case ExpressionEvaluationContext::PotentiallyEvaluated: 18641 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18642 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18643 FunctionScopes.back()->PossiblyUnreachableDiags. 18644 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18645 return true; 18646 } 18647 18648 // The initializer of a constexpr variable or of the first declaration of a 18649 // static data member is not syntactically a constant evaluated constant, 18650 // but nonetheless is always required to be a constant expression, so we 18651 // can skip diagnosing. 18652 // FIXME: Using the mangling context here is a hack. 18653 if (auto *VD = dyn_cast_or_null<VarDecl>( 18654 ExprEvalContexts.back().ManglingContextDecl)) { 18655 if (VD->isConstexpr() || 18656 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18657 break; 18658 // FIXME: For any other kind of variable, we should build a CFG for its 18659 // initializer and check whether the context in question is reachable. 18660 } 18661 18662 Diag(Loc, PD); 18663 return true; 18664 } 18665 18666 return false; 18667 } 18668 18669 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18670 const PartialDiagnostic &PD) { 18671 return DiagRuntimeBehavior( 18672 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18673 } 18674 18675 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18676 CallExpr *CE, FunctionDecl *FD) { 18677 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18678 return false; 18679 18680 // If we're inside a decltype's expression, don't check for a valid return 18681 // type or construct temporaries until we know whether this is the last call. 18682 if (ExprEvalContexts.back().ExprContext == 18683 ExpressionEvaluationContextRecord::EK_Decltype) { 18684 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18685 return false; 18686 } 18687 18688 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18689 FunctionDecl *FD; 18690 CallExpr *CE; 18691 18692 public: 18693 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18694 : FD(FD), CE(CE) { } 18695 18696 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18697 if (!FD) { 18698 S.Diag(Loc, diag::err_call_incomplete_return) 18699 << T << CE->getSourceRange(); 18700 return; 18701 } 18702 18703 S.Diag(Loc, diag::err_call_function_incomplete_return) 18704 << CE->getSourceRange() << FD << T; 18705 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18706 << FD->getDeclName(); 18707 } 18708 } Diagnoser(FD, CE); 18709 18710 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18711 return true; 18712 18713 return false; 18714 } 18715 18716 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18717 // will prevent this condition from triggering, which is what we want. 18718 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18719 SourceLocation Loc; 18720 18721 unsigned diagnostic = diag::warn_condition_is_assignment; 18722 bool IsOrAssign = false; 18723 18724 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18725 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18726 return; 18727 18728 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18729 18730 // Greylist some idioms by putting them into a warning subcategory. 18731 if (ObjCMessageExpr *ME 18732 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18733 Selector Sel = ME->getSelector(); 18734 18735 // self = [<foo> init...] 18736 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18737 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18738 18739 // <foo> = [<bar> nextObject] 18740 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18741 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18742 } 18743 18744 Loc = Op->getOperatorLoc(); 18745 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18746 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18747 return; 18748 18749 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18750 Loc = Op->getOperatorLoc(); 18751 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18752 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18753 else { 18754 // Not an assignment. 18755 return; 18756 } 18757 18758 Diag(Loc, diagnostic) << E->getSourceRange(); 18759 18760 SourceLocation Open = E->getBeginLoc(); 18761 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18762 Diag(Loc, diag::note_condition_assign_silence) 18763 << FixItHint::CreateInsertion(Open, "(") 18764 << FixItHint::CreateInsertion(Close, ")"); 18765 18766 if (IsOrAssign) 18767 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18768 << FixItHint::CreateReplacement(Loc, "!="); 18769 else 18770 Diag(Loc, diag::note_condition_assign_to_comparison) 18771 << FixItHint::CreateReplacement(Loc, "=="); 18772 } 18773 18774 /// Redundant parentheses over an equality comparison can indicate 18775 /// that the user intended an assignment used as condition. 18776 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18777 // Don't warn if the parens came from a macro. 18778 SourceLocation parenLoc = ParenE->getBeginLoc(); 18779 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18780 return; 18781 // Don't warn for dependent expressions. 18782 if (ParenE->isTypeDependent()) 18783 return; 18784 18785 Expr *E = ParenE->IgnoreParens(); 18786 18787 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18788 if (opE->getOpcode() == BO_EQ && 18789 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18790 == Expr::MLV_Valid) { 18791 SourceLocation Loc = opE->getOperatorLoc(); 18792 18793 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18794 SourceRange ParenERange = ParenE->getSourceRange(); 18795 Diag(Loc, diag::note_equality_comparison_silence) 18796 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18797 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18798 Diag(Loc, diag::note_equality_comparison_to_assign) 18799 << FixItHint::CreateReplacement(Loc, "="); 18800 } 18801 } 18802 18803 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18804 bool IsConstexpr) { 18805 DiagnoseAssignmentAsCondition(E); 18806 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18807 DiagnoseEqualityWithExtraParens(parenE); 18808 18809 ExprResult result = CheckPlaceholderExpr(E); 18810 if (result.isInvalid()) return ExprError(); 18811 E = result.get(); 18812 18813 if (!E->isTypeDependent()) { 18814 if (getLangOpts().CPlusPlus) 18815 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18816 18817 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18818 if (ERes.isInvalid()) 18819 return ExprError(); 18820 E = ERes.get(); 18821 18822 QualType T = E->getType(); 18823 if (!T->isScalarType()) { // C99 6.8.4.1p1 18824 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18825 << T << E->getSourceRange(); 18826 return ExprError(); 18827 } 18828 CheckBoolLikeConversion(E, Loc); 18829 } 18830 18831 return E; 18832 } 18833 18834 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18835 Expr *SubExpr, ConditionKind CK) { 18836 // Empty conditions are valid in for-statements. 18837 if (!SubExpr) 18838 return ConditionResult(); 18839 18840 ExprResult Cond; 18841 switch (CK) { 18842 case ConditionKind::Boolean: 18843 Cond = CheckBooleanCondition(Loc, SubExpr); 18844 break; 18845 18846 case ConditionKind::ConstexprIf: 18847 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18848 break; 18849 18850 case ConditionKind::Switch: 18851 Cond = CheckSwitchCondition(Loc, SubExpr); 18852 break; 18853 } 18854 if (Cond.isInvalid()) { 18855 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18856 {SubExpr}); 18857 if (!Cond.get()) 18858 return ConditionError(); 18859 } 18860 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18861 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18862 if (!FullExpr.get()) 18863 return ConditionError(); 18864 18865 return ConditionResult(*this, nullptr, FullExpr, 18866 CK == ConditionKind::ConstexprIf); 18867 } 18868 18869 namespace { 18870 /// A visitor for rebuilding a call to an __unknown_any expression 18871 /// to have an appropriate type. 18872 struct RebuildUnknownAnyFunction 18873 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18874 18875 Sema &S; 18876 18877 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18878 18879 ExprResult VisitStmt(Stmt *S) { 18880 llvm_unreachable("unexpected statement!"); 18881 } 18882 18883 ExprResult VisitExpr(Expr *E) { 18884 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18885 << E->getSourceRange(); 18886 return ExprError(); 18887 } 18888 18889 /// Rebuild an expression which simply semantically wraps another 18890 /// expression which it shares the type and value kind of. 18891 template <class T> ExprResult rebuildSugarExpr(T *E) { 18892 ExprResult SubResult = Visit(E->getSubExpr()); 18893 if (SubResult.isInvalid()) return ExprError(); 18894 18895 Expr *SubExpr = SubResult.get(); 18896 E->setSubExpr(SubExpr); 18897 E->setType(SubExpr->getType()); 18898 E->setValueKind(SubExpr->getValueKind()); 18899 assert(E->getObjectKind() == OK_Ordinary); 18900 return E; 18901 } 18902 18903 ExprResult VisitParenExpr(ParenExpr *E) { 18904 return rebuildSugarExpr(E); 18905 } 18906 18907 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18908 return rebuildSugarExpr(E); 18909 } 18910 18911 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18912 ExprResult SubResult = Visit(E->getSubExpr()); 18913 if (SubResult.isInvalid()) return ExprError(); 18914 18915 Expr *SubExpr = SubResult.get(); 18916 E->setSubExpr(SubExpr); 18917 E->setType(S.Context.getPointerType(SubExpr->getType())); 18918 assert(E->getValueKind() == VK_RValue); 18919 assert(E->getObjectKind() == OK_Ordinary); 18920 return E; 18921 } 18922 18923 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 18924 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 18925 18926 E->setType(VD->getType()); 18927 18928 assert(E->getValueKind() == VK_RValue); 18929 if (S.getLangOpts().CPlusPlus && 18930 !(isa<CXXMethodDecl>(VD) && 18931 cast<CXXMethodDecl>(VD)->isInstance())) 18932 E->setValueKind(VK_LValue); 18933 18934 return E; 18935 } 18936 18937 ExprResult VisitMemberExpr(MemberExpr *E) { 18938 return resolveDecl(E, E->getMemberDecl()); 18939 } 18940 18941 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 18942 return resolveDecl(E, E->getDecl()); 18943 } 18944 }; 18945 } 18946 18947 /// Given a function expression of unknown-any type, try to rebuild it 18948 /// to have a function type. 18949 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 18950 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 18951 if (Result.isInvalid()) return ExprError(); 18952 return S.DefaultFunctionArrayConversion(Result.get()); 18953 } 18954 18955 namespace { 18956 /// A visitor for rebuilding an expression of type __unknown_anytype 18957 /// into one which resolves the type directly on the referring 18958 /// expression. Strict preservation of the original source 18959 /// structure is not a goal. 18960 struct RebuildUnknownAnyExpr 18961 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 18962 18963 Sema &S; 18964 18965 /// The current destination type. 18966 QualType DestType; 18967 18968 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 18969 : S(S), DestType(CastType) {} 18970 18971 ExprResult VisitStmt(Stmt *S) { 18972 llvm_unreachable("unexpected statement!"); 18973 } 18974 18975 ExprResult VisitExpr(Expr *E) { 18976 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18977 << E->getSourceRange(); 18978 return ExprError(); 18979 } 18980 18981 ExprResult VisitCallExpr(CallExpr *E); 18982 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 18983 18984 /// Rebuild an expression which simply semantically wraps another 18985 /// expression which it shares the type and value kind of. 18986 template <class T> ExprResult rebuildSugarExpr(T *E) { 18987 ExprResult SubResult = Visit(E->getSubExpr()); 18988 if (SubResult.isInvalid()) return ExprError(); 18989 Expr *SubExpr = SubResult.get(); 18990 E->setSubExpr(SubExpr); 18991 E->setType(SubExpr->getType()); 18992 E->setValueKind(SubExpr->getValueKind()); 18993 assert(E->getObjectKind() == OK_Ordinary); 18994 return E; 18995 } 18996 18997 ExprResult VisitParenExpr(ParenExpr *E) { 18998 return rebuildSugarExpr(E); 18999 } 19000 19001 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19002 return rebuildSugarExpr(E); 19003 } 19004 19005 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19006 const PointerType *Ptr = DestType->getAs<PointerType>(); 19007 if (!Ptr) { 19008 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19009 << E->getSourceRange(); 19010 return ExprError(); 19011 } 19012 19013 if (isa<CallExpr>(E->getSubExpr())) { 19014 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19015 << E->getSourceRange(); 19016 return ExprError(); 19017 } 19018 19019 assert(E->getValueKind() == VK_RValue); 19020 assert(E->getObjectKind() == OK_Ordinary); 19021 E->setType(DestType); 19022 19023 // Build the sub-expression as if it were an object of the pointee type. 19024 DestType = Ptr->getPointeeType(); 19025 ExprResult SubResult = Visit(E->getSubExpr()); 19026 if (SubResult.isInvalid()) return ExprError(); 19027 E->setSubExpr(SubResult.get()); 19028 return E; 19029 } 19030 19031 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19032 19033 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19034 19035 ExprResult VisitMemberExpr(MemberExpr *E) { 19036 return resolveDecl(E, E->getMemberDecl()); 19037 } 19038 19039 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19040 return resolveDecl(E, E->getDecl()); 19041 } 19042 }; 19043 } 19044 19045 /// Rebuilds a call expression which yielded __unknown_anytype. 19046 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19047 Expr *CalleeExpr = E->getCallee(); 19048 19049 enum FnKind { 19050 FK_MemberFunction, 19051 FK_FunctionPointer, 19052 FK_BlockPointer 19053 }; 19054 19055 FnKind Kind; 19056 QualType CalleeType = CalleeExpr->getType(); 19057 if (CalleeType == S.Context.BoundMemberTy) { 19058 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19059 Kind = FK_MemberFunction; 19060 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19061 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19062 CalleeType = Ptr->getPointeeType(); 19063 Kind = FK_FunctionPointer; 19064 } else { 19065 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19066 Kind = FK_BlockPointer; 19067 } 19068 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19069 19070 // Verify that this is a legal result type of a function. 19071 if (DestType->isArrayType() || DestType->isFunctionType()) { 19072 unsigned diagID = diag::err_func_returning_array_function; 19073 if (Kind == FK_BlockPointer) 19074 diagID = diag::err_block_returning_array_function; 19075 19076 S.Diag(E->getExprLoc(), diagID) 19077 << DestType->isFunctionType() << DestType; 19078 return ExprError(); 19079 } 19080 19081 // Otherwise, go ahead and set DestType as the call's result. 19082 E->setType(DestType.getNonLValueExprType(S.Context)); 19083 E->setValueKind(Expr::getValueKindForType(DestType)); 19084 assert(E->getObjectKind() == OK_Ordinary); 19085 19086 // Rebuild the function type, replacing the result type with DestType. 19087 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19088 if (Proto) { 19089 // __unknown_anytype(...) is a special case used by the debugger when 19090 // it has no idea what a function's signature is. 19091 // 19092 // We want to build this call essentially under the K&R 19093 // unprototyped rules, but making a FunctionNoProtoType in C++ 19094 // would foul up all sorts of assumptions. However, we cannot 19095 // simply pass all arguments as variadic arguments, nor can we 19096 // portably just call the function under a non-variadic type; see 19097 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19098 // However, it turns out that in practice it is generally safe to 19099 // call a function declared as "A foo(B,C,D);" under the prototype 19100 // "A foo(B,C,D,...);". The only known exception is with the 19101 // Windows ABI, where any variadic function is implicitly cdecl 19102 // regardless of its normal CC. Therefore we change the parameter 19103 // types to match the types of the arguments. 19104 // 19105 // This is a hack, but it is far superior to moving the 19106 // corresponding target-specific code from IR-gen to Sema/AST. 19107 19108 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19109 SmallVector<QualType, 8> ArgTypes; 19110 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19111 ArgTypes.reserve(E->getNumArgs()); 19112 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19113 Expr *Arg = E->getArg(i); 19114 QualType ArgType = Arg->getType(); 19115 if (E->isLValue()) { 19116 ArgType = S.Context.getLValueReferenceType(ArgType); 19117 } else if (E->isXValue()) { 19118 ArgType = S.Context.getRValueReferenceType(ArgType); 19119 } 19120 ArgTypes.push_back(ArgType); 19121 } 19122 ParamTypes = ArgTypes; 19123 } 19124 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19125 Proto->getExtProtoInfo()); 19126 } else { 19127 DestType = S.Context.getFunctionNoProtoType(DestType, 19128 FnType->getExtInfo()); 19129 } 19130 19131 // Rebuild the appropriate pointer-to-function type. 19132 switch (Kind) { 19133 case FK_MemberFunction: 19134 // Nothing to do. 19135 break; 19136 19137 case FK_FunctionPointer: 19138 DestType = S.Context.getPointerType(DestType); 19139 break; 19140 19141 case FK_BlockPointer: 19142 DestType = S.Context.getBlockPointerType(DestType); 19143 break; 19144 } 19145 19146 // Finally, we can recurse. 19147 ExprResult CalleeResult = Visit(CalleeExpr); 19148 if (!CalleeResult.isUsable()) return ExprError(); 19149 E->setCallee(CalleeResult.get()); 19150 19151 // Bind a temporary if necessary. 19152 return S.MaybeBindToTemporary(E); 19153 } 19154 19155 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19156 // Verify that this is a legal result type of a call. 19157 if (DestType->isArrayType() || DestType->isFunctionType()) { 19158 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19159 << DestType->isFunctionType() << DestType; 19160 return ExprError(); 19161 } 19162 19163 // Rewrite the method result type if available. 19164 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19165 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19166 Method->setReturnType(DestType); 19167 } 19168 19169 // Change the type of the message. 19170 E->setType(DestType.getNonReferenceType()); 19171 E->setValueKind(Expr::getValueKindForType(DestType)); 19172 19173 return S.MaybeBindToTemporary(E); 19174 } 19175 19176 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19177 // The only case we should ever see here is a function-to-pointer decay. 19178 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19179 assert(E->getValueKind() == VK_RValue); 19180 assert(E->getObjectKind() == OK_Ordinary); 19181 19182 E->setType(DestType); 19183 19184 // Rebuild the sub-expression as the pointee (function) type. 19185 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19186 19187 ExprResult Result = Visit(E->getSubExpr()); 19188 if (!Result.isUsable()) return ExprError(); 19189 19190 E->setSubExpr(Result.get()); 19191 return E; 19192 } else if (E->getCastKind() == CK_LValueToRValue) { 19193 assert(E->getValueKind() == VK_RValue); 19194 assert(E->getObjectKind() == OK_Ordinary); 19195 19196 assert(isa<BlockPointerType>(E->getType())); 19197 19198 E->setType(DestType); 19199 19200 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19201 DestType = S.Context.getLValueReferenceType(DestType); 19202 19203 ExprResult Result = Visit(E->getSubExpr()); 19204 if (!Result.isUsable()) return ExprError(); 19205 19206 E->setSubExpr(Result.get()); 19207 return E; 19208 } else { 19209 llvm_unreachable("Unhandled cast type!"); 19210 } 19211 } 19212 19213 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19214 ExprValueKind ValueKind = VK_LValue; 19215 QualType Type = DestType; 19216 19217 // We know how to make this work for certain kinds of decls: 19218 19219 // - functions 19220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19221 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19222 DestType = Ptr->getPointeeType(); 19223 ExprResult Result = resolveDecl(E, VD); 19224 if (Result.isInvalid()) return ExprError(); 19225 return S.ImpCastExprToType(Result.get(), Type, 19226 CK_FunctionToPointerDecay, VK_RValue); 19227 } 19228 19229 if (!Type->isFunctionType()) { 19230 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19231 << VD << E->getSourceRange(); 19232 return ExprError(); 19233 } 19234 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19235 // We must match the FunctionDecl's type to the hack introduced in 19236 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19237 // type. See the lengthy commentary in that routine. 19238 QualType FDT = FD->getType(); 19239 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19240 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19241 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19242 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19243 SourceLocation Loc = FD->getLocation(); 19244 FunctionDecl *NewFD = FunctionDecl::Create( 19245 S.Context, FD->getDeclContext(), Loc, Loc, 19246 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19247 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19248 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19249 19250 if (FD->getQualifier()) 19251 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19252 19253 SmallVector<ParmVarDecl*, 16> Params; 19254 for (const auto &AI : FT->param_types()) { 19255 ParmVarDecl *Param = 19256 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19257 Param->setScopeInfo(0, Params.size()); 19258 Params.push_back(Param); 19259 } 19260 NewFD->setParams(Params); 19261 DRE->setDecl(NewFD); 19262 VD = DRE->getDecl(); 19263 } 19264 } 19265 19266 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19267 if (MD->isInstance()) { 19268 ValueKind = VK_RValue; 19269 Type = S.Context.BoundMemberTy; 19270 } 19271 19272 // Function references aren't l-values in C. 19273 if (!S.getLangOpts().CPlusPlus) 19274 ValueKind = VK_RValue; 19275 19276 // - variables 19277 } else if (isa<VarDecl>(VD)) { 19278 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19279 Type = RefTy->getPointeeType(); 19280 } else if (Type->isFunctionType()) { 19281 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19282 << VD << E->getSourceRange(); 19283 return ExprError(); 19284 } 19285 19286 // - nothing else 19287 } else { 19288 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19289 << VD << E->getSourceRange(); 19290 return ExprError(); 19291 } 19292 19293 // Modifying the declaration like this is friendly to IR-gen but 19294 // also really dangerous. 19295 VD->setType(DestType); 19296 E->setType(Type); 19297 E->setValueKind(ValueKind); 19298 return E; 19299 } 19300 19301 /// Check a cast of an unknown-any type. We intentionally only 19302 /// trigger this for C-style casts. 19303 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19304 Expr *CastExpr, CastKind &CastKind, 19305 ExprValueKind &VK, CXXCastPath &Path) { 19306 // The type we're casting to must be either void or complete. 19307 if (!CastType->isVoidType() && 19308 RequireCompleteType(TypeRange.getBegin(), CastType, 19309 diag::err_typecheck_cast_to_incomplete)) 19310 return ExprError(); 19311 19312 // Rewrite the casted expression from scratch. 19313 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19314 if (!result.isUsable()) return ExprError(); 19315 19316 CastExpr = result.get(); 19317 VK = CastExpr->getValueKind(); 19318 CastKind = CK_NoOp; 19319 19320 return CastExpr; 19321 } 19322 19323 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19324 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19325 } 19326 19327 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19328 Expr *arg, QualType ¶mType) { 19329 // If the syntactic form of the argument is not an explicit cast of 19330 // any sort, just do default argument promotion. 19331 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19332 if (!castArg) { 19333 ExprResult result = DefaultArgumentPromotion(arg); 19334 if (result.isInvalid()) return ExprError(); 19335 paramType = result.get()->getType(); 19336 return result; 19337 } 19338 19339 // Otherwise, use the type that was written in the explicit cast. 19340 assert(!arg->hasPlaceholderType()); 19341 paramType = castArg->getTypeAsWritten(); 19342 19343 // Copy-initialize a parameter of that type. 19344 InitializedEntity entity = 19345 InitializedEntity::InitializeParameter(Context, paramType, 19346 /*consumed*/ false); 19347 return PerformCopyInitialization(entity, callLoc, arg); 19348 } 19349 19350 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19351 Expr *orig = E; 19352 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19353 while (true) { 19354 E = E->IgnoreParenImpCasts(); 19355 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19356 E = call->getCallee(); 19357 diagID = diag::err_uncasted_call_of_unknown_any; 19358 } else { 19359 break; 19360 } 19361 } 19362 19363 SourceLocation loc; 19364 NamedDecl *d; 19365 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19366 loc = ref->getLocation(); 19367 d = ref->getDecl(); 19368 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19369 loc = mem->getMemberLoc(); 19370 d = mem->getMemberDecl(); 19371 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19372 diagID = diag::err_uncasted_call_of_unknown_any; 19373 loc = msg->getSelectorStartLoc(); 19374 d = msg->getMethodDecl(); 19375 if (!d) { 19376 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19377 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19378 << orig->getSourceRange(); 19379 return ExprError(); 19380 } 19381 } else { 19382 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19383 << E->getSourceRange(); 19384 return ExprError(); 19385 } 19386 19387 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19388 19389 // Never recoverable. 19390 return ExprError(); 19391 } 19392 19393 /// Check for operands with placeholder types and complain if found. 19394 /// Returns ExprError() if there was an error and no recovery was possible. 19395 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19396 if (!Context.isDependenceAllowed()) { 19397 // C cannot handle TypoExpr nodes on either side of a binop because it 19398 // doesn't handle dependent types properly, so make sure any TypoExprs have 19399 // been dealt with before checking the operands. 19400 ExprResult Result = CorrectDelayedTyposInExpr(E); 19401 if (!Result.isUsable()) return ExprError(); 19402 E = Result.get(); 19403 } 19404 19405 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19406 if (!placeholderType) return E; 19407 19408 switch (placeholderType->getKind()) { 19409 19410 // Overloaded expressions. 19411 case BuiltinType::Overload: { 19412 // Try to resolve a single function template specialization. 19413 // This is obligatory. 19414 ExprResult Result = E; 19415 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19416 return Result; 19417 19418 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19419 // leaves Result unchanged on failure. 19420 Result = E; 19421 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19422 return Result; 19423 19424 // If that failed, try to recover with a call. 19425 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19426 /*complain*/ true); 19427 return Result; 19428 } 19429 19430 // Bound member functions. 19431 case BuiltinType::BoundMember: { 19432 ExprResult result = E; 19433 const Expr *BME = E->IgnoreParens(); 19434 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19435 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19436 if (isa<CXXPseudoDestructorExpr>(BME)) { 19437 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19438 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19439 if (ME->getMemberNameInfo().getName().getNameKind() == 19440 DeclarationName::CXXDestructorName) 19441 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19442 } 19443 tryToRecoverWithCall(result, PD, 19444 /*complain*/ true); 19445 return result; 19446 } 19447 19448 // ARC unbridged casts. 19449 case BuiltinType::ARCUnbridgedCast: { 19450 Expr *realCast = stripARCUnbridgedCast(E); 19451 diagnoseARCUnbridgedCast(realCast); 19452 return realCast; 19453 } 19454 19455 // Expressions of unknown type. 19456 case BuiltinType::UnknownAny: 19457 return diagnoseUnknownAnyExpr(*this, E); 19458 19459 // Pseudo-objects. 19460 case BuiltinType::PseudoObject: 19461 return checkPseudoObjectRValue(E); 19462 19463 case BuiltinType::BuiltinFn: { 19464 // Accept __noop without parens by implicitly converting it to a call expr. 19465 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19466 if (DRE) { 19467 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19468 if (FD->getBuiltinID() == Builtin::BI__noop) { 19469 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19470 CK_BuiltinFnToFnPtr) 19471 .get(); 19472 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19473 VK_RValue, SourceLocation(), 19474 FPOptionsOverride()); 19475 } 19476 } 19477 19478 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19479 return ExprError(); 19480 } 19481 19482 case BuiltinType::IncompleteMatrixIdx: 19483 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19484 ->getRowIdx() 19485 ->getBeginLoc(), 19486 diag::err_matrix_incomplete_index); 19487 return ExprError(); 19488 19489 // Expressions of unknown type. 19490 case BuiltinType::OMPArraySection: 19491 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19492 return ExprError(); 19493 19494 // Expressions of unknown type. 19495 case BuiltinType::OMPArrayShaping: 19496 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19497 19498 case BuiltinType::OMPIterator: 19499 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19500 19501 // Everything else should be impossible. 19502 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19503 case BuiltinType::Id: 19504 #include "clang/Basic/OpenCLImageTypes.def" 19505 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19506 case BuiltinType::Id: 19507 #include "clang/Basic/OpenCLExtensionTypes.def" 19508 #define SVE_TYPE(Name, Id, SingletonId) \ 19509 case BuiltinType::Id: 19510 #include "clang/Basic/AArch64SVEACLETypes.def" 19511 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19512 case BuiltinType::Id: 19513 #include "clang/Basic/PPCTypes.def" 19514 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19515 #include "clang/Basic/RISCVVTypes.def" 19516 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19517 #define PLACEHOLDER_TYPE(Id, SingletonId) 19518 #include "clang/AST/BuiltinTypes.def" 19519 break; 19520 } 19521 19522 llvm_unreachable("invalid placeholder type!"); 19523 } 19524 19525 bool Sema::CheckCaseExpression(Expr *E) { 19526 if (E->isTypeDependent()) 19527 return true; 19528 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19529 return E->getType()->isIntegralOrEnumerationType(); 19530 return false; 19531 } 19532 19533 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19534 ExprResult 19535 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19536 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19537 "Unknown Objective-C Boolean value!"); 19538 QualType BoolT = Context.ObjCBuiltinBoolTy; 19539 if (!Context.getBOOLDecl()) { 19540 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19541 Sema::LookupOrdinaryName); 19542 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19543 NamedDecl *ND = Result.getFoundDecl(); 19544 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19545 Context.setBOOLDecl(TD); 19546 } 19547 } 19548 if (Context.getBOOLDecl()) 19549 BoolT = Context.getBOOLType(); 19550 return new (Context) 19551 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19552 } 19553 19554 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19555 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19556 SourceLocation RParen) { 19557 19558 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19559 19560 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19561 return Spec.getPlatform() == Platform; 19562 }); 19563 19564 VersionTuple Version; 19565 if (Spec != AvailSpecs.end()) 19566 Version = Spec->getVersion(); 19567 19568 // The use of `@available` in the enclosing function should be analyzed to 19569 // warn when it's used inappropriately (i.e. not if(@available)). 19570 if (getCurFunctionOrMethodDecl()) 19571 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19572 else if (getCurBlock() || getCurLambda()) 19573 getCurFunction()->HasPotentialAvailabilityViolations = true; 19574 19575 return new (Context) 19576 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19577 } 19578 19579 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19580 ArrayRef<Expr *> SubExprs, QualType T) { 19581 if (!Context.getLangOpts().RecoveryAST) 19582 return ExprError(); 19583 19584 if (isSFINAEContext()) 19585 return ExprError(); 19586 19587 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19588 // We don't know the concrete type, fallback to dependent type. 19589 T = Context.DependentTy; 19590 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19591 } 19592